From ca7f212c2dbe1406963b964cf34ba089c1de12a3 Mon Sep 17 00:00:00 2001 From: uzairansaruzi Date: Fri, 20 Nov 2026 13:07:40 -0500 Subject: [PATCH 1/2] fix(auth): keep legacy custom headers when their Keychain migration fails Delete the pre-#16 global custom-header entry only after the per-server save succeeds, so a failed migration keeps the only copy and retries on the next launch. Fixes #1785 Co-Authored-By: Claude Opus 5.5 --- HermesMobile/Auth/AuthManager.swift | 5 +++-- .../CustomHeaderInjectionTests.swift | 20 ++++++++++++++++++- docs/adr/0148-server-custom-headers.md | 2 +- docs/agents/multi-server-state-isolation.md | 2 +- 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/HermesMobile/Auth/AuthManager.swift b/HermesMobile/Auth/AuthManager.swift index d473128bd..4a9e56697 100644 --- a/HermesMobile/Auth/AuthManager.swift +++ b/HermesMobile/Auth/AuthManager.swift @@ -579,8 +579,9 @@ final class AuthManager { if let scoped = try? keychain.load(.customHeaders, scope: scope) { stored = scoped } else if let legacy = try? keychain.load(.customHeaders) { - try? keychain.save(legacy, forKey: .customHeaders, scope: scope) - try? keychain.delete(.customHeaders) + if (try? keychain.save(legacy, forKey: .customHeaders, scope: scope)) != nil { + try? keychain.delete(.customHeaders) + } stored = legacy } else { stored = nil diff --git a/HermesMobileTests/CustomHeaderInjectionTests.swift b/HermesMobileTests/CustomHeaderInjectionTests.swift index df8bf6019..81b8816f9 100644 --- a/HermesMobileTests/CustomHeaderInjectionTests.swift +++ b/HermesMobileTests/CustomHeaderInjectionTests.swift @@ -201,7 +201,7 @@ final class CustomHeaderSSEInjectionTests: XCTestCase { @MainActor final class CustomHeaderAuthManagerTests: XCTestCase { private func makeManager( - keychain: InMemoryKeychainStore, + keychain: KeychainStoring, store: CustomHeaderStore, client: MockAuthAPIClient ) -> AuthManager { @@ -373,6 +373,24 @@ final class CustomHeaderAuthManagerTests: XCTestCase { XCTAssertNotNil(keychain.scopedValue(.customHeaders, scope: "https://legacy.test")) XCTAssertNil(keychain.savedValues[.customHeaders]) } + + func testLaunchKeepsLegacyGlobalHeadersWhenTheirMigrationFails() throws { + let keychain = FailingKeychain() + let encoded = try XCTUnwrap([CustomHeader(name: "Authorization", value: "Bearer saved")].encodedForStorage()) + try keychain.save(encoded, forKey: .customHeaders) + try keychain.save("https://legacy.test", forKey: .serverURL) + keychain.failingKeys = [.customHeaders] + let store = CustomHeaderStore() + + _ = makeManager( + keychain: keychain, + store: store, + client: MockAuthAPIClient(authStatus: AuthStatusResponse(authEnabled: false)) + ) + + XCTAssertEqual(store.snapshot().map(\.value), ["Bearer saved"]) + XCTAssertEqual(try keychain.load(.customHeaders), encoded) + } } final class RedirectingMockURLProtocol: URLProtocol { diff --git a/docs/adr/0148-server-custom-headers.md b/docs/adr/0148-server-custom-headers.md index 3b2605094..e0d8b4187 100644 --- a/docs/adr/0148-server-custom-headers.md +++ b/docs/adr/0148-server-custom-headers.md @@ -10,7 +10,7 @@ Lives in: `HermesMobile/Auth/AuthManager.swift` ## Hydrate custom headers before building any client -`AuthManager.hydrateCustomHeaders(for:)` loads a webui server's custom headers into the live snapshot before any client is built, so the first request after launch already carries them (#255). On the first launch after the per-server split there's no scoped entry yet, so it migrates the pre-#16 global blob in place, writing it under the scoped key and dropping the global remnant; the steady state costs one scoped Keychain read (#16). `AuthManager.enterActiveServer` relies on this, then enters `.loggedIn` optimistically: a stale cookie is demoted by the first 401 in `handleAPIError`. A Hermes server sends no webui headers and is signed in only while its own `BotConnection` record exists; without one its sign-in form shows (#899). +`AuthManager.hydrateCustomHeaders(for:)` loads a webui server's custom headers into the live snapshot before any client is built, so the first request after launch already carries them (#255). On the first launch after the per-server split there's no scoped entry yet, so it migrates the pre-#16 global blob in place, writing it under the scoped key and dropping the global remnant only once that write succeeds, so a failed write still applies the headers and retries on the next launch (#1785); the steady state costs one scoped Keychain read (#16). `AuthManager.enterActiveServer` relies on this, then enters `.loggedIn` optimistically: a stale cookie is demoted by the first 401 in `handleAPIError`. A Hermes server sends no webui headers and is signed in only while its own `BotConnection` record exists; without one its sign-in form shows (#899). Lives in: `HermesMobile/Auth/AuthManager.swift` diff --git a/docs/agents/multi-server-state-isolation.md b/docs/agents/multi-server-state-isolation.md index ae3ae7691..4f47ae53c 100644 --- a/docs/agents/multi-server-state-isolation.md +++ b/docs/agents/multi-server-state-isolation.md @@ -211,7 +211,7 @@ server's content even if the purge fails. | Hermes cache rows (two Hermes servers and a webui one; per-Profile keys; cleared with their server) | `CacheStoreTests.testHermesRowsStayWithTheirServerAndClearWithIt`, `testHermesKeysCarryTheServerProfileAndLineageRoot` | | Per-server identity (no re-seed, mirror on activate/set-active/update/remove) | `ServerRegistryTests` (`testActivateDoesNotReseedIdentityWhenServerAlreadyExists`, `testSetActiveMirrorsTheNewActiveIdentityToDefaults`, `testUpdateMirrorsToDefaultsOnlyWhenServerIsActive`, `testReactivatingAnExistingServerMirrorsItsIdentityToDefaults`, `testActivatingANewServerDoesNotMirrorIntoEmptyDefaults`), `AuthManagerStateTests.testUpdateServerIdentityPersistsAndMirrorsTheActiveServer` | | Per-server browsed Kanban Board | `KanbanFeatureStateTests.testBrowsedBoardIsRestoredForTheSameServerAndIsolatedFromOthers`, `testStaleSavedBoardIsDroppedAndColdStartFallsBackToCurrentBoard` | -| Per-server custom headers | `CustomHeaderSSEInjectionTests.testSSEStreamSourcesHeadersFromActiveServerStore`, `CustomHeaderAuthManagerTests.testLaunchMigratesLegacyGlobalHeadersToActiveServerScope`, `AuthManagerStateTests` (`testSignOutLeavesOtherServerHeadersAndRegistryIntact`, `testAddServerFailureKeepsActiveServerAndItsHeaders`) | +| Per-server custom headers | `CustomHeaderSSEInjectionTests.testSSEStreamSourcesHeadersFromActiveServerStore`, `CustomHeaderAuthManagerTests` (`testLaunchMigratesLegacyGlobalHeadersToActiveServerScope`, `testLaunchKeepsLegacyGlobalHeadersWhenTheirMigrationFails`), `AuthManagerStateTests` (`testSignOutLeavesOtherServerHeadersAndRegistryIntact`, `testAddServerFailureKeepsActiveServerAndItsHeaders`) | | Per-server cookies | `AuthManagerStateTests` (`testSignOutClearsOnlyActiveServerCookies`, `testRemoveNonActiveServerClearsOnlyItsCookies`, `testUnauthorizedClearsOnlyActiveServerCookies`) | | Default model/profile | No persisted state to leak (server-fresh per active server); covered by the switch mechanism. | | Chat thumbnail cache (attachment vs. media key, namespace boundary) | `TranscriptMediaParserTests.testAttachmentAndMediaCacheKeysNeverCollide`. The same path under two servers or sessions has no test. | From 497cc1a84a79d7716692e68106f5a8ad44821937 Mon Sep 17 00:00:00 2001 From: uzairansaruzi Date: Fri, 20 Nov 2026 13:15:35 -0500 Subject: [PATCH 2/2] fix(auth): drop the legacy header entry on any header write A copy a failed migration left would otherwise be read for a server added later, or bring back headers the user cleared. Co-Authored-By: Claude Fable 5.2 --- HermesMobile/Auth/AuthManager.swift | 1 + .../CustomHeaderInjectionTests.swift | 17 +++++++++++++++++ docs/adr/0148-server-custom-headers.md | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/HermesMobile/Auth/AuthManager.swift b/HermesMobile/Auth/AuthManager.swift index 4a9e56697..e6a31fc13 100644 --- a/HermesMobile/Auth/AuthManager.swift +++ b/HermesMobile/Auth/AuthManager.swift @@ -571,6 +571,7 @@ final class AuthManager { } else { try? keychain.delete(.customHeaders, scope: scope) } + try? keychain.delete(.customHeaders) } private func hydrateCustomHeaders(for server: URL) { diff --git a/HermesMobileTests/CustomHeaderInjectionTests.swift b/HermesMobileTests/CustomHeaderInjectionTests.swift index 81b8816f9..f70271a05 100644 --- a/HermesMobileTests/CustomHeaderInjectionTests.swift +++ b/HermesMobileTests/CustomHeaderInjectionTests.swift @@ -391,6 +391,23 @@ final class CustomHeaderAuthManagerTests: XCTestCase { XCTAssertEqual(store.snapshot().map(\.value), ["Bearer saved"]) XCTAssertEqual(try keychain.load(.customHeaders), encoded) } + + func testAHeaderWriteRetiresLegacyHeadersAFailedMigrationLeft() throws { + let keychain = FailingKeychain() + let encoded = try XCTUnwrap([CustomHeader(name: "Authorization", value: "Bearer saved")].encodedForStorage()) + try keychain.save(encoded, forKey: .customHeaders) + try keychain.save("https://legacy.test", forKey: .serverURL) + keychain.failingKeys = [.customHeaders] + let manager = makeManager( + keychain: keychain, + store: CustomHeaderStore(), + client: MockAuthAPIClient(authStatus: AuthStatusResponse(authEnabled: false)) + ) + + manager.updateCustomHeaders([]) + + XCTAssertNil(try keychain.load(.customHeaders)) + } } final class RedirectingMockURLProtocol: URLProtocol { diff --git a/docs/adr/0148-server-custom-headers.md b/docs/adr/0148-server-custom-headers.md index e0d8b4187..c2cfba31c 100644 --- a/docs/adr/0148-server-custom-headers.md +++ b/docs/adr/0148-server-custom-headers.md @@ -10,7 +10,7 @@ Lives in: `HermesMobile/Auth/AuthManager.swift` ## Hydrate custom headers before building any client -`AuthManager.hydrateCustomHeaders(for:)` loads a webui server's custom headers into the live snapshot before any client is built, so the first request after launch already carries them (#255). On the first launch after the per-server split there's no scoped entry yet, so it migrates the pre-#16 global blob in place, writing it under the scoped key and dropping the global remnant only once that write succeeds, so a failed write still applies the headers and retries on the next launch (#1785); the steady state costs one scoped Keychain read (#16). `AuthManager.enterActiveServer` relies on this, then enters `.loggedIn` optimistically: a stale cookie is demoted by the first 401 in `handleAPIError`. A Hermes server sends no webui headers and is signed in only while its own `BotConnection` record exists; without one its sign-in form shows (#899). +`AuthManager.hydrateCustomHeaders(for:)` loads a webui server's custom headers into the live snapshot before any client is built, so the first request after launch already carries them (#255). On the first launch after the per-server split there's no scoped entry yet, so it migrates the pre-#16 global blob in place, writing it under the scoped key and dropping the global remnant only once that write succeeds, so a failed write still applies the headers and retries on the next launch (#1785). `persistCustomHeaders(for:)` drops that remnant on any header write, so a copy a failed migration left can't reach a server added later or bring back headers the user cleared; the steady state costs one scoped Keychain read (#16). `AuthManager.enterActiveServer` relies on this, then enters `.loggedIn` optimistically: a stale cookie is demoted by the first 401 in `handleAPIError`. A Hermes server sends no webui headers and is signed in only while its own `BotConnection` record exists; without one its sign-in form shows (#899). Lives in: `HermesMobile/Auth/AuthManager.swift`