Commit 0320995c authored by Kourser's avatar Kourser
Browse files

fix: authentification Digest et choix du schéma pour le serveur Calibre

Se connecter à un calibre-server échouait avec des identifiants
corrects. Deux causes, trouvées en sondant un vrai serveur.

Son `--auth-mode` vaut `auto` par défaut, et cela signifie Digest, pas
Basic : le serveur renvoie `WWW-Authenticate: Digest realm="calibre",
algorithm=MD5, qop="auth"` et refuse un en-tête Basic. Le client n'en
envoyait que du Basic. L'authentification Digest est donc implémentée —
MD5 par obligation du schéma, pas par choix — avec mémorisation du
challenge entre les requêtes, sans quoi chaque appel coûterait deux
allers-retours. Le calcul est vérifié contre le vecteur publié de la
RFC 2617 : c'est la seule façon de le valider sans serveur.

Et une adresse tapée sans schéma partait en HTTP. Pour un nom public
sans port, donc derrière un proxy inverse, nginx répond 301 vers HTTPS
et le chargement d'URL abandonne l'en-tête Authorization en route : un
401 avec le bon mot de passe, sans rien pour le comprendre. Le schéma se
déduit maintenant de la forme de l'hôte, et une tentative HTTP qui
échoue est rejouée une fois en HTTPS.

Au passage, le diagnostic : les erreurs HTTP nomment la requête qui a
échoué, un 405 est signalé à part parce que Calibre répond 404 à un
chemin inconnu et jamais 405, la sonde trace chaque requête avec son
statut, et coller la barre d'adresse du navigateur ou une URL finissant
par /opds ne casse plus l'adresse de base — un --url-prefix, lui, est
conservé.

178 tests au vert.

Co-Authored-By: default avatarClaude Opus 5 <noreply@anthropic.com>
parent 55876151
Loading
Loading
Loading
Loading
+18 −0
Changes for CHANGELOG.md: 18 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,24 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).

## [Non publié]

### Corrigé
- La connexion à un calibre-server échouait avec des identifiants corrects :
  son `--auth-mode` vaut `auto` par défaut, ce qui signifie **Digest**, et le
  client n'envoyait que du Basic. L'authentification Digest est implémentée
  (MD5, qop=auth), le challenge est retenu entre les requêtes, et le calcul est
  vérifié contre le vecteur publié de la RFC 2617.
- Une adresse sans schéma partait en HTTP. Pour un nom public sans port — donc
  derrière un proxy inverse — nginx répond 301 vers HTTPS et le chargement
  d'URL abandonne l'en-tête `Authorization` au passage : 401 avec le bon mot de
  passe. Le schéma est maintenant déduit de la forme de l'hôte, et une
  tentative HTTP qui échoue est rejouée en HTTPS.
- Coller la barre d'adresse du navigateur, ou une URL finissant par `/opds` ou
  `/mobile`, ne casse plus l'adresse de base. Un `--url-prefix`, lui, est
  conservé.
- Les erreurs HTTP nomment la requête qui a échoué. Un 405 est signalé à part :
  calibre-server répond 404 à un chemin inconnu, jamais 405, donc un 405 veut
  dire qu'autre chose répond.

### Ajouté
- Podbook est utilisable sans serveur Calibre : import d'EPUB et de PDF depuis
  Fichiers, iCloud Drive ou la feuille de partage, avec extraction du titre, de
+4 −3
Changes for Packages/Core/Sources/CalibreKit/CalibreClient+Conversion.swift: 4 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -4,11 +4,12 @@ extension CalibreClient {

    /// What the book already has, and what the server is willing to produce.
    public func conversionData(bookID: Int, libraryID: String? = nil) async throws -> ConversionData {
        let response = try await send(HTTPRequest(url: try url(
        let request = HTTPRequest(url: try url(
            path: "/conversion/book-data/\(bookID)",
            libraryInQuery: libraryID ?? server.defaultLibraryID
        )))
        try check(response)
        ))
        let response = try await send(request)
        try check(response, request)
        do {
            return try JSONDecoder().decode(ConversionData.self, from: response.body)
        } catch {
+84 −36
Changes for Packages/Core/Sources/CalibreKit/CalibreClient.swift: 84 added lines, 36 removed lines.
Original line number Diff line number Diff line
@@ -16,10 +16,16 @@ import Foundation
public struct CalibreClient: Sendable {
    public let server: CalibreServer
    private let transport: any HTTPTransport
    private let authentication: AuthenticationCache

    public init(server: CalibreServer, transport: any HTTPTransport = URLSessionTransport()) {
    public init(
        server: CalibreServer,
        transport: any HTTPTransport = URLSessionTransport(),
        authentication: AuthenticationCache = AuthenticationCache()
    ) {
        self.server = server
        self.transport = transport
        self.authentication = authentication
    }

    // MARK: - Library
@@ -34,7 +40,10 @@ public struct CalibreClient: Sendable {
        do {
            _ = try await libraryInfo()
            return .calibreServer
        } catch CalibreError.notFound, CalibreError.http(status: 404, body: _) {
        } catch CalibreError.notFound, CalibreError.methodNotAllowed,
                  CalibreError.http(status: 404, body: _) {
            // A 404 means no /ajax surface; a 405 means something that is not
            // calibre-server is answering. Either way OPDS is the thing to try.
            let response = try await send(HTTPRequest(url: try url(path: "/opds")))
            return response.isSuccess ? .calibreWeb : .unknown
        }
@@ -71,11 +80,12 @@ public struct CalibreClient: Sendable {
    /// current user may not see — both handled here.
    public func books(ids: [Int], libraryID: String? = nil) async throws -> [Int: CalibreBook] {
        guard !ids.isEmpty else { return [:] }
        let response = try await send(HTTPRequest(url: try url(
        let request = HTTPRequest(url: try url(
            path: "/ajax/books" + librarySegment(libraryID),
            query: [URLQueryItem(name: "ids", value: ids.map(String.init).joined(separator: ","))]
        )))
        try check(response)
        ))
        let response = try await send(request)
        try check(response, request)

        guard let raw = try? JSONSerialization.jsonObject(with: response.body) as? [String: Any] else {
            throw CalibreError.decoding("/ajax/books n'a pas renvoyé un objet JSON")
@@ -92,10 +102,11 @@ public struct CalibreClient: Sendable {
    }

    public func book(id: Int, libraryID: String? = nil) async throws -> CalibreBook {
        let response = try await send(HTTPRequest(url: try url(
        let request = HTTPRequest(url: try url(
            path: "/ajax/book/\(id)" + librarySegment(libraryID)
        )))
        try check(response)
        ))
        let response = try await send(request)
        try check(response, request)
        let decoder = JSONDecoder()
        decoder.userInfo[CalibreBook.idKey] = id
        do {
@@ -135,18 +146,20 @@ public struct CalibreClient: Sendable {
    }

    public func downloadFormat(bookID: Int, format: String, libraryID: String? = nil) async throws -> Data {
        let response = try await send(HTTPRequest(url: try downloadURL(
        let request = HTTPRequest(url: try downloadURL(
            bookID: bookID, what: format.uppercased(), libraryID: libraryID
        )))
        try check(response)
        ))
        let response = try await send(request)
        try check(response, request)
        return response.body
    }

    public func downloadCover(bookID: Int, libraryID: String? = nil) async throws -> Data {
        let response = try await send(HTTPRequest(url: try downloadURL(
        let request = HTTPRequest(url: try downloadURL(
            bookID: bookID, what: "cover", libraryID: libraryID
        )))
        try check(response)
        ))
        let response = try await send(request)
        try check(response, request)
        return response.body
    }

@@ -174,10 +187,11 @@ public struct CalibreClient: Sendable {
        let library = libraryID ?? server.defaultLibraryID
        guard let library else { throw CalibreError.invalidURL("library_id requis pour la position de lecture") }
        let which = "\(bookID):\(format.uppercased())"
        let response = try await send(HTTPRequest(url: try url(
        let request = HTTPRequest(url: try url(
            path: "/book-get-last-read-position/\(library)/\(which)"
        )))
        try check(response)
        ))
        let response = try await send(request)
        try check(response, request)
        return (try? JSONDecoder().decode([ReadingPosition].self, from: response.body)) ?? []
    }

@@ -190,13 +204,14 @@ public struct CalibreClient: Sendable {
        let library = libraryID ?? server.defaultLibraryID
        guard let library else { throw CalibreError.invalidURL("library_id requis pour la position de lecture") }
        let body = try JSONEncoder().encode(position)
        let response = try await send(HTTPRequest(
        let request = HTTPRequest(
            method: "POST",
            url: try url(path: "/book-set-last-read-position/\(library)/\(bookID)/\(format.uppercased())"),
            headers: ["Content-Type": "application/json"],
            body: body
        ))
        try check(response)
        )
        let response = try await send(request)
        try check(response, request)
    }

    // MARK: - calibredb over HTTP
@@ -210,13 +225,14 @@ public struct CalibreClient: Sendable {
        libraryID: String? = nil
    ) async throws -> Data {
        let body = try JSONEncoder().encode(arguments)
        let response = try await send(HTTPRequest(
        let request = HTTPRequest(
            method: "POST",
            url: try url(path: "/cdb/cmd/\(command)", libraryInQuery: libraryID),
            headers: ["Content-Type": "application/json"],
            body: body
        ))
        try check(response)
        )
        let response = try await send(request)
        try check(response, request)
        return response.body
    }

@@ -251,22 +267,52 @@ public struct CalibreClient: Sendable {
        path.hasPrefix("/conversion/") || path.hasPrefix("/cdb/") || path.hasPrefix("/fts/")
    }

    /// Sends the request, and answers an authentication challenge if one comes
    /// back.
    ///
    /// `calibre-server` defaults to `--auth-mode auto`, which means **Digest**.
    /// A client that only knows Basic gets a 401 with correct credentials and no
    /// way to tell why — so a 401 carrying a Digest challenge is learned and the
    /// request replayed once, signed.
    func send(_ request: HTTPRequest) async throws -> HTTPResponse {
        let response = try await transport.send(await prepared(request))

        guard response.status == 401,
              server.credentials != nil,
              await authentication.learn(from: response)
        else { return response }

        return try await transport.send(await prepared(request))
    }

    private func prepared(_ request: HTTPRequest) async -> HTTPRequest {
        var request = request
        if let auth = server.authorizationHeader {
            request.headers["Authorization"] = auth
        if let header = await authentication.authorization(for: request, server: server) {
            request.headers["Authorization"] = header
        }
        request.headers["Accept"] = request.headers["Accept"] ?? "application/json"
        return try await transport.send(request)
        return request
    }

    func check(_ response: HTTPResponse) throws {
    /// Failures carry the request that produced them.
    ///
    /// Without this, a « HTTP 405 » tells nobody which URL was called, and
    /// diagnosing a connection problem becomes guesswork.
    func check(_ response: HTTPResponse, _ request: HTTPRequest) throws {
        guard !response.isSuccess else { return }
        let body = String(data: response.body.prefix(2048), encoding: .utf8) ?? ""
        let body = String(data: response.body.prefix(2048), encoding: .utf8)?
            .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
        let origin = "\(request.method) \(request.url.absoluteString)"

        switch response.status {
        case 401, 403: throw CalibreError.unauthorized
        case 404: throw CalibreError.notFound(body.isEmpty ? "ressource" : body)
        default: throw CalibreError.http(status: response.status, body: body)
        case 404: throw CalibreError.notFound(origin)
        case 405: throw CalibreError.methodNotAllowed(request: origin)
        default:
            throw CalibreError.http(
                status: response.status,
                body: body.isEmpty ? origin : "\(origin) — \(body)"
            )
        }
    }

@@ -276,10 +322,11 @@ public struct CalibreClient: Sendable {
        query: [URLQueryItem] = [],
        libraryInQuery: String? = nil
    ) async throws -> T {
        let response = try await send(HTTPRequest(url: try url(
        let request = HTTPRequest(url: try url(
            path: path, query: query, libraryInQuery: libraryInQuery
        )))
        try check(response)
        ))
        let response = try await send(request)
        try check(response, request)
        do {
            return try JSONDecoder().decode(type, from: response.body)
        } catch {
@@ -294,13 +341,14 @@ public struct CalibreClient: Sendable {
        query: [URLQueryItem] = [],
        libraryInQuery: String? = nil
    ) async throws -> T {
        let response = try await send(HTTPRequest(
        let request = HTTPRequest(
            method: "POST",
            url: try url(path: path, query: query, libraryInQuery: libraryInQuery),
            headers: body == nil ? [:] : ["Content-Type": "application/json"],
            body: body
        ))
        try check(response)
        )
        let response = try await send(request)
        try check(response, request)
        do {
            return try JSONDecoder().decode(type, from: response.body)
        } catch {
+11 −0
Changes for Packages/Core/Sources/CalibreKit/CalibreError.swift: 11 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -5,6 +5,11 @@ public enum CalibreError: Error, Sendable, Hashable {
    case transport(String)
    case unauthorized
    case notFound(String)
    /// The server matched the route but refuses the method. calibre-server
    /// never does this for the routes Podbook uses — a 405 almost always means
    /// something else is answering: a reverse proxy, a different application on
    /// that port, or a URL prefix that is not what the server expects.
    case methodNotAllowed(request: String)
    case http(status: Int, body: String)
    case decoding(String)
    case notACalibreServer
@@ -24,6 +29,12 @@ extension CalibreError: LocalizedError {
        case .transport(let message): "Erreur de transport : \(message)"
        case .unauthorized: "Identifiants refusés par le serveur Calibre"
        case .notFound(let what): "Introuvable : \(what)"
        case .methodNotAllowed(let request):
            """
            Le serveur refuse la méthode de cette requête : \(request)

            calibre-server ne répond jamais 405 sur cette route. Vérifie que             l'adresse pointe bien sur un calibre-server, et non sur un proxy             inverse, sur Calibre-Web, ou sur un autre service du même port.
            """
        case .http(let status, let body): "HTTP \(status) : \(body)"
        case .decoding(let message): "Réponse illisible : \(message)"
        case .notACalibreServer: "Ce serveur n'expose pas l'API de calibre-server"
+1 −1
Changes for Packages/Core/Sources/CalibreKit/CalibreServer.swift: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -24,7 +24,7 @@ public struct CalibreServer: Sendable, Hashable {
        self.defaultLibraryID = defaultLibraryID
    }

    var authorizationHeader: String? {
    var basicAuthorizationHeader: String? {
        guard let credentials else { return nil }
        let raw = "\(credentials.username):\(credentials.password)"
        guard let encoded = raw.data(using: .utf8)?.base64EncodedString() else { return nil }
Loading