commit e877f59799d89a3c33c5e25c0a50bfa02c0db44e
parent 8ae285555ab75412e69cb6f2cda8e4407f73bd64
Author: Jean Schurger <jean@schurger.org>
Date: Fri, 13 Nov 2026 16:53:47 -0500
Test the authenticated HTTP path against git http-backend; precise refusal message (401 vs 403)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
4 files changed, 139 insertions(+), 2 deletions(-)
diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift
@@ -175,7 +175,8 @@ final class AppModel {
static func describe(_ error: Error) -> String {
if let git = error as? GitError {
switch git {
- case .unauthorized: return "Courriel ou mot de passe refusé par le nuage Subsurface."
+ case .unauthorized: return "Le nuage Subsurface a refusé ce courriel et ce mot de passe (réponse 401). Vérifiez-les, ou créez un compte s'il n'existe pas encore."
+ case .http(403): return "Le nuage Subsurface interdit l'accès à ce carnet (réponse 403)."
case .notFound: return "Aucun carnet trouvé pour ce compte."
case .network(let what): return "Connexion impossible : \(what)"
case .http(let code): return "Le nuage Subsurface a répondu par une erreur (\(code))."
diff --git a/Packages/DiveKit/Sources/GitLite/Client.swift b/Packages/DiveKit/Sources/GitLite/Client.swift
@@ -89,7 +89,7 @@ public struct HTTPTransport: GitTransport {
guard let http = response as? HTTPURLResponse else { throw GitError.network("réponse inattendue") }
switch http.statusCode {
case 200: return Array(data)
- case 401, 403: throw GitError.unauthorized
+ case 401: throw GitError.unauthorized
case 404: throw GitError.notFound
default: throw GitError.http(http.statusCode)
}
diff --git a/Packages/DiveKit/Sources/GitTestSupport/GitHTTPServer.swift b/Packages/DiveKit/Sources/GitTestSupport/GitHTTPServer.swift
@@ -0,0 +1,82 @@
+#if os(macOS)
+import Foundation
+
+/// Vrai serveur git « smart HTTP » local, avec authentification Basic : un petit serveur Python qui passe les
+/// requêtes à `git http-backend`, comme le fait Apache sur le nuage Subsurface.
+public final class GitHTTPServer {
+ public let port: Int
+ private let process: Process
+
+ static let script = #"""
+import base64, os, subprocess, sys
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+ROOT, USER, PASSWORD = sys.argv[1], sys.argv[2], sys.argv[3]
+EXPECTED = "Basic " + base64.b64encode((USER + ":" + PASSWORD).encode()).decode()
+
+class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+ def log_message(self, *args): pass
+ def handle_git(self):
+ if self.headers.get("Authorization") != EXPECTED:
+ body = b"Unauthorized"
+ self.send_response(401)
+ self.send_header("WWW-Authenticate", 'Basic realm="Test"')
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ return
+ path, _, query = self.path.partition("?")
+ length = int(self.headers.get("Content-Length") or 0)
+ data = self.rfile.read(length) if length else b""
+ env = dict(os.environ, GIT_PROJECT_ROOT=ROOT, GIT_HTTP_EXPORT_ALL="1", PATH_INFO=path, QUERY_STRING=query,
+ REQUEST_METHOD=self.command, CONTENT_TYPE=self.headers.get("Content-Type", ""),
+ CONTENT_LENGTH=str(length), REMOTE_USER=USER, REMOTE_ADDR="127.0.0.1")
+ out = subprocess.run(["git", "http-backend"], input=data, env=env, capture_output=True).stdout
+ head, _, body = out.partition(b"\r\n\r\n")
+ status = 200
+ headers = []
+ for line in head.split(b"\r\n"):
+ name, _, value = line.decode().partition(": ")
+ if name.lower() == "status": status = int(value.split()[0])
+ elif name: headers.append((name, value))
+ self.send_response(status)
+ for name, value in headers: self.send_header(name, value)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ do_GET = handle_git
+ do_POST = handle_git
+
+server = HTTPServer(("127.0.0.1", 0), Handler)
+print(server.server_address[1], flush=True)
+server.serve_forever()
+"""#
+
+ /// `root` contient les dépôts nus servis sous `/git/…` (root/git/<nom>).
+ public init(root: URL, user: String, password: String) throws {
+ let scriptURL = root.appendingPathComponent("server.py")
+ try Data(Self.script.utf8).write(to: scriptURL)
+ process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
+ process.arguments = ["python3", scriptURL.path, root.path, user, password]
+ let output = Pipe()
+ process.standardOutput = output
+ process.standardError = FileHandle.nullDevice
+ try process.run()
+ var line = [UInt8]()
+ while let byte = try output.fileHandleForReading.read(upToCount: 1)?.first, byte != 0x0a { line.append(byte) }
+ guard let port = Int(String(decoding: line, as: UTF8.self)) else {
+ process.terminate()
+ throw NSError(domain: "GitHTTPServer", code: 1, userInfo: [NSLocalizedDescriptionKey: "le serveur de test n'a pas démarré"])
+ }
+ self.port = port
+ }
+
+ public func stop() {
+ process.terminate()
+ }
+
+ deinit { process.terminate() }
+}
+#endif
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/HTTPTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/HTTPTests.swift
@@ -0,0 +1,54 @@
+import XCTest
+import GitLite
+import GitTestSupport
+@testable import SubsurfaceLog
+
+/// Le chemin réel de l'app : URLSession → HTTP avec authentification Basic → `git http-backend`.
+final class HTTPTests: XCTestCase {
+ func testSyncOverAuthenticatedHTTP() async throws {
+ let email = Fixture.branch
+ let password = "S3cret+_-.@"
+ let (seed, _) = try Fixture.makeRemote()
+ let root = try LocalGit.temporaryDirectory("www")
+ let bare = LocalGit(directory: root.appendingPathComponent("git").appendingPathComponent(email))
+ try FileManager.default.createDirectory(at: bare.directory, withIntermediateDirectories: true)
+ try bare.git(["init", "-q", "--bare"])
+ try bare.git(["config", "http.receivepack", "true"])
+ try seed.git(["push", "-q", bare.directory.path, "refs/heads/\(email):refs/heads/\(email)"])
+
+ let server = try GitHTTPServer(root: root, user: email, password: password)
+ defer { server.stop() }
+ let base = URL(string: "http://127.0.0.1:\(server.port)/git/")!.appendingPathComponent(email)
+ let transport = HTTPTransport(baseURL: base, username: email, password: password)
+
+ // Mauvais mot de passe : refus net.
+ do {
+ _ = try await GitClient(transport: HTTPTransport(baseURL: base, username: email, password: "faux"), store: MemoryObjectStore()).refs()
+ XCTFail("aurait dû être refusé")
+ } catch let error as GitError {
+ XCTAssertEqual(error, .unauthorized)
+ }
+
+ // Bon mot de passe : la liste des branches, puis tout le carnet.
+ let refs = try await GitClient(transport: transport, store: MemoryObjectStore()).refs()
+ XCTAssertNotNil(refs.branch(email))
+ let repo = try LogRepository(directory: try LocalGit.temporaryDirectory("local"), branch: email, authorName: "DiveLog", authorEmail: email)
+ let first = try await repo.sync(transport: transport)
+ XCTAssertTrue(first.downloaded)
+ var log = try await repo.logbook()
+ XCTAssertEqual(log.dives.map(\.number), [43, 42, 41])
+
+ // Une modification part et se retrouve dans le dépôt du serveur.
+ try await repo.enqueue(.editDive(when: Fixture.when(2024, 7, 13, 10, 15, 30), number: 41, fields: ["buddy": "Par HTTP"]))
+ let second = try await repo.sync(transport: transport)
+ XCTAssertEqual(second.sent.count, 1)
+ try bare.git(["fsck", "--strict"])
+ XCTAssertTrue(try bare.text(["show", "\(email):2024/07/13-Sat-10=15=30/Dive-41"]).contains("buddy \"Par HTTP\""))
+
+ // Un second appareil récupère la modification.
+ let other = try LogRepository(directory: try LocalGit.temporaryDirectory("other"), branch: email, authorName: "DiveLog", authorEmail: email)
+ _ = try await other.sync(transport: transport)
+ log = try await other.logbook()
+ XCTAssertEqual(log.dives.last?.buddy, "Par HTTP")
+ }
+}