diff --git a/HermesMobile/Auth/AuthManager.swift b/HermesMobile/Auth/AuthManager.swift index d473128bd..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) { @@ -579,8 +580,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..f70271a05 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,41 @@ 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) + } + + 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 3b2605094..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; 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` 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. |