Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions HermesMobile/Auth/AuthManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,7 @@ final class AuthManager {
} else {
try? keychain.delete(.customHeaders, scope: scope)
}
try? keychain.delete(.customHeaders)
Comment thread
uzairansaruzi marked this conversation as resolved.
Resolved
Comment thread
uzairansaruzi marked this conversation as resolved.
Resolved
}

private func hydrateCustomHeaders(for server: URL) {
Expand All @@ -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)
}
Comment thread
uzairansaruzi marked this conversation as resolved.
Resolved
Comment thread
uzairansaruzi marked this conversation as resolved.
Resolved
stored = legacy
} else {
stored = nil
Expand Down
37 changes: 36 additions & 1 deletion HermesMobileTests/CustomHeaderInjectionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion docs/adr/0148-server-custom-headers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
2 changes: 1 addition & 1 deletion docs/agents/multi-server-state-isolation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down