Commit ce9a5e59 authored by Kourser's avatar Kourser
Browse files

fix: le nom de bibliothèque partait encodé deux fois

« Bibliothèque_calibre » arrivait au serveur en
`Biblioth%25C3%25A8que_calibre` : `librarySegment` pré-encodait le nom,
puis `appendingPathComponent` encodait le résultat une seconde fois.
Toute requête nommant une bibliothèque était refusée.

Le bug était invisible parce que `/ajax/library-info` ne nomme aucune
bibliothèque : la connexion réussissait, la sonde passait, et seul le
catalogue restait vide derrière un « Identifiants refusés » qui ne
désignait rien.

Les erreurs portent donc maintenant la requête fautive — méthode et URL
complète. C'est ce qui a rendu le double encodage lisible d'un coup
d'œil, et c'est la raison de garder ce changement.

La sonde et le client final partagent désormais le même
`AuthenticationCache` : le challenge obtenu pendant la connexion n'est
plus redemandé à chaque appel suivant.

Vérifié contre le vrai serveur dans le simulateur iPad : 6 568 livres
listés, couvertures comprises.

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

### Corrigé
- Le nom de la bibliothèque était encodé deux fois : « Bibliothèque_calibre »
  partait en `Biblioth%25C3%25A8que_calibre` et le serveur refusait toute
  requête nommant une bibliothèque. `/ajax/library-info`, qui n'en nomme
  aucune, passait et masquait le problème — la connexion réussissait, le
  catalogue restait vide. Vérifié contre un vrai serveur : 6 568 livres listés.
- Les erreurs portent désormais la requête fautive (méthode et URL complète).
  C'est ce qui a rendu le double encodage visible : « Identifiants refusés »
  tout court ne désignait rien à regarder.
- La connexion à un calibre-server échouait toujours, en 400 « Unsupported
  authentication method ». L'app envoyait un en-tête Basic d'emblée, ce qu'un
  serveur en mode Digest refuse par un 400 et non un 401 — et le rejeu ne se
+9 −2
Changes for Packages/Core/Sources/CalibreKit/CalibreClient.swift: 9 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -238,9 +238,16 @@ public struct CalibreClient: Sendable {

    // MARK: - Plumbing

    /// The library id goes in **raw**.
    ///
    /// Percent-encoding it here and then handing it to `appendingPathComponent`
    /// encodes it twice: a library called « Bibliothèque_calibre » became
    /// `Biblioth%25C3%25A8que_calibre`, and the server refused every request
    /// that named a library — while `/ajax/library-info`, which names none,
    /// worked perfectly and hid the problem.
    private func librarySegment(_ libraryID: String?, requireValue: Bool = false) -> String {
        if let id = libraryID ?? server.defaultLibraryID {
            return "/" + id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
            return "/" + id
        }
        return requireValue ? "/" : ""
    }
@@ -306,7 +313,7 @@ public struct CalibreClient: Sendable {
        let origin = "\(request.method) \(request.url.absoluteString)"

        switch response.status {
        case 401, 403: throw CalibreError.unauthorized
        case 401, 403: throw CalibreError.unauthorized(request: origin)
        case 404: throw CalibreError.notFound(origin)
        case 405: throw CalibreError.methodNotAllowed(request: origin)
        default:
+5 −2
Changes for Packages/Core/Sources/CalibreKit/CalibreError.swift: 5 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -3,7 +3,10 @@ import Foundation
public enum CalibreError: Error, Sendable, Hashable {
    case invalidURL(String)
    case transport(String)
    case unauthorized
    /// Carries the request that was refused: a bare « wrong credentials »
    /// cannot be told apart from « this one request is signed wrong », and the
    /// two have opposite causes.
    case unauthorized(request: String)
    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
@@ -27,7 +30,7 @@ extension CalibreError: LocalizedError {
        switch self {
        case .invalidURL(let value): "URL invalide : \(value)"
        case .transport(let message): "Erreur de transport : \(message)"
        case .unauthorized: "Identifiants refusés par le serveur Calibre"
        case .unauthorized(let request): "Identifiants refusés : \(request)"
        case .notFound(let what): "Introuvable : \(what)"
        case .methodNotAllowed(let request):
            """
+24 −4
Changes for Packages/Core/Sources/PodbookUI/Stores/ConnectionStore.swift: 24 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -71,7 +71,15 @@ public final class ConnectionStore {
            return
        }
        status = .connecting
        let probe = CalibreClient(server: server, transport: makeTransport(server))
        // Un seul cache d'authentification pour la sonde et pour le client
        // final : le challenge appris en se connectant servait, sinon, à rien,
        // et chaque session repayait un aller-retour de refus.
        let credentials = AuthenticationCache()
        let probe = CalibreClient(
            server: server,
            transport: makeTransport(server),
            authentication: credentials
        )

        do {
            let detected = try await probe.detectFlavor()
@@ -97,9 +105,14 @@ public final class ConnectionStore {
                libraries = []
            }

            // Rebuild the client so it carries the resolved library id.
            // Rebuild the client so it carries the resolved library id, but
            // keep what was learned about authentication.
            if let resolved = settings.makeServer() {
                client = CalibreClient(server: resolved, transport: makeTransport(resolved))
                client = CalibreClient(
                    server: resolved,
                    transport: makeTransport(resolved),
                    authentication: credentials
                )
            }
            status = .connected
        } catch {
@@ -127,7 +140,14 @@ public final class ConnectionStore {
    static func message(for error: any Error) -> String {
        if let calibre = error as? CalibreError {
            return switch calibre {
            case .unauthorized: "Identifiants refusés. Le serveur tourne-t-il avec --enable-auth ?"
            case .unauthorized(let origin):
                """
                Identifiants refusés sur cette requête :
                \(origin)

                Si la connexion a pourtant abouti, le mot de passe est bon et \
                c'est la signature de cette requête-là qui est rejetée.
                """
            case .notFound(let origin):
                "Serveur joignable, mais l'API attendue est absente à cette adresse.\n\(origin)"
            case .methodNotAllowed: calibre.errorDescription ?? "Méthode refusée"
+61 −1
Changes for Packages/Core/Tests/CalibreKitTests/CalibreClientTests.swift: 61 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -188,7 +188,9 @@ struct ErrorTests {
    func unauthorized() async throws {
        let (client, transport) = makeClient()
        transport.stub("/ajax/library-info", status: 401, json: "")
        await #expect(throws: CalibreError.unauthorized) {
        await #expect(throws: CalibreError.unauthorized(
            request: "GET http://mac.local:8080/ajax/library-info"
        )) {
            _ = try await client.libraryInfo()
        }
    }
@@ -219,3 +221,61 @@ struct ErrorTests {
        #expect(try await client.detectFlavor() == .unknown)
    }
}

@Suite("Encodage du nom de bibliothèque")
struct LibraryEncodingTests {
    /// Une bibliothèque Calibre s'appelle comme son dossier, accents compris.
    private func makeClient(library: String) -> (CalibreClient, StubTransport) {
        let transport = StubTransport()
        return (
            CalibreClient(
                server: CalibreServer(
                    baseURL: URL(string: "https://levr.kourser.bzh")!,
                    defaultLibraryID: library
                ),
                transport: transport
            ),
            transport
        )
    }

    @Test("Un accent est encodé une seule fois")
    func encodesAccentOnce() async throws {
        let (client, transport) = makeClient(library: "Bibliothèque_calibre")
        transport.stub("/ajax/search/Bibliothèque_calibre", json: Fixtures.searchPage)

        _ = try await client.search()

        let url = try #require(transport.lastRequest?.url.absoluteString)
        #expect(url.contains("Biblioth%C3%A8que_calibre"))
        // Pré-encoder puis laisser appendingPathComponent encoder à nouveau
        // donnait %25C3%25A8, et le serveur refusait toute requête nommant une
        // bibliothèque — alors que /ajax/library-info, qui n'en nomme aucune,
        // passait et masquait le problème.
        #expect(url.contains("%25") == false, "le nom ne doit pas être encodé deux fois")
    }

    @Test("Le téléchargement d'un format subit le même traitement")
    func downloadURLEncodesOnce() throws {
        let (client, _) = makeClient(library: "Bibliothèque_calibre")
        let url = try client.downloadURL(bookID: 42, what: "EPUB").absoluteString
        #expect(url.contains("Biblioth%C3%A8que_calibre"))
        #expect(url.contains("%25") == false)
    }

    @Test("Un nom sans accent reste intact")
    func plainNameUntouched() async throws {
        let (client, transport) = makeClient(library: "Calibre_Library")
        transport.stub("/ajax/search/Calibre_Library", json: Fixtures.searchPage)
        _ = try await client.search()
        #expect(transport.lastRequest?.url.path == "/ajax/search/Calibre_Library")
    }

    @Test("Une espace est bien encodée")
    func spaceIsEncoded() throws {
        let (client, _) = makeClient(library: "Ma Bibliothèque")
        let url = try client.downloadURL(bookID: 1, what: "cover").absoluteString
        #expect(url.contains("Ma%20Biblioth%C3%A8que"))
        #expect(url.contains("%25") == false)
    }
}
Loading