Repository navigation
fix(notifications): recover Apple push after the installation key changes - #977
Conversation
… again An iPhone whose installation key no longer matches the server's (the app lost its journal, or the server was saved again under another address, which gives a new key for the same device ID) had every push registration refused with 403 and held forever. Servers that report installation_reset_available now answer the owning account with push_installation_key_mismatch. On that answer the registrar calls resetApplePushInstallation with the current key, starts the journal over with the same key, and registers the same intent at generation 1. It tries this once per registration attempt; a second mismatch, a failed reset, permission_denied, a renewal, or a server without the capability keep the existing hold-and-retry behaviour.
A reset that times out or meets a server error now leaves the intent pending, so the next trigger resets again, which the contract makes safe. Only a refused reset holds the generation. Documents the reset outcome on the registrar and shares the reset receipt decoding between transports.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Session proof and reset API iosApp/iosApp/Networking/APIv2/APIv2PushModels.swift, iosApp/iosApp/Networking/APIv2/APIv2Client.swift, iosApp/iosApp/Networking/APIv2/APIv2RetrySafety.swift, iosApp/iosApp/Notifications/ApplePushRegistrationChannel.swift |
The API supports paginated session retrieval and installation reset. The registration channel checks session pages for a matching non-current session and sends reset requests. |
Shared installation journal iosApp/iosApp/Notifications/ApplePushInstallationJournal.swift |
The journal resolves saved-server links to shared records, stores owner history, and tracks intent ownership. It removes links when the recorded deployment identity no longer matches. |
Registration sharing and mismatch recovery iosApp/iosApp/Notifications/ApplePushRegistration.swift, iosApp/iosApp/Notifications/ApplePushDisplayTargets.swift |
The registrar links records after deployment-identity and session-proof checks. It manages display targets across linked addresses and resets eligible non-teardown key mismatches before retrying at a higher generation. |
Retirement routing and retries iosApp/iosApp/Notifications/ApplePushRegistration.swift, iosApp/iosApp/Notifications/ApplePushRetirement.swift |
Retirement attempts can use another saved address that still shares the record. The queue checks that the route still maps to the recorded slot before sending. |
Sharing and recovery behavior tests iosApp/Tests/ApplePushOrderedRegistrationTests.swift |
The test harness configures session pages, deployment identities, reset responses, and asynchronous gates. Tests cover sharing, ownership changes, stale links, credential failures, retirement routing, teardown races, and reset outcomes. |
Estimated code review effort: 4 (Complex) | ~45 minutes
Change: Bug fix
Sequence Diagram(s)
sequenceDiagram
participant ApplePushRegistrar
participant ApplePushRegistrationChannel
participant LoginSessionsAPI
participant ApplePushInstallationJournal
ApplePushRegistrar->>ApplePushRegistrationChannel: Check for shared backend session
ApplePushRegistrationChannel->>LoginSessionsAPI: Fetch session pages
LoginSessionsAPI-->>ApplePushRegistrationChannel: Return session pages
ApplePushRegistrationChannel-->>ApplePushRegistrar: Report session match
ApplePushRegistrar->>ApplePushInstallationJournal: Link shared installation record
ApplePushRegistrar->>ApplePushRegistrationChannel: Register with shared installation key
Possibly related PRs
- Silo-Server/silo-apple#867: Adds installation retirement and journal generations, which share lifecycle state with this change.
Suggested labels: api-v2, impact: usability, evidence-required
Suggested reviewers: quick104
Merge Risk: 
Minimal · up to 79b2e
-
This change lets saved addresses that reach the same server share an Apple push installation, and it recovers push registration after an installation-key mismatch. The reviewed concurrency and ownership races were fixed and have regression tests, and no unresolved defect is supported by the supplied evidence. The remaining notes are a test timing choice and a known fallback risk already listed by the maintainers. Server-side support in silo-server#3352 was not yet merged when the review was written. The author also did not demonstrate APNs delivery or rerun the full suite and tvOS/macOS builds locally.
Security architecture risk: 
Moderate · up to 79b2e
-
The recovery flow preserves notification ordering, but a previously linked address can retain access to a shared installation key after that address changes hands. Under those conditions, the new endpoint could obtain authority to disable this device’s notifications on the original server.
Retained concerns
- Medium · security · inferred: A persisted alias can disclose the surviving deployment’s installation key after endpoint reassignment. Session proof authorizes initial sharing, but later registration and retirement routing accept the persisted link while cached deployment identity remains unchanged; failed identity discovery does not invalidate that identity. If a formerly proven address comes under another operator’s control and is selected for registration or retirement, journal-slot equality does not establish that it still reaches the proven deployment. The endpoint can receive the shared key, device ID, and generation. The documented retirement contract uses those values without login credentials. Before this PR, a second address retained its separate key rather than receiving the working key from the surviving address. Explicitly detected identity changes and slot changes are handled, but they do not cover stale identity after reassignment.
Security review details
-
Security Blast Radius
- inferred — The demonstrated exposure concerns a shared Apple Push installation for one device and deployment across its linked addresses. An attacker must control an endpoint previously proven as an alias, not merely supply an arbitrary matching deployment ID. The client contract supports session-free retirement with the disclosed key; broader account, tenant, or data-store compromise is not established.
Security Findings and Attack Paths
- inferred — After legitimate linking, a reassigned alias can retain its cached deployment identity and persisted link. If selected for a queued retirement, route selection and slot validation can succeed without a current login session or fresh backend proof, transmitting the surviving deployment’s key to the new endpoint. Tests verify protection after an identity change is supplied and the link is actually removed; that counterevidence does not establish protection when identity discovery fails or remains stale.
Trust Boundaries and Controls
- observed — Initial sharing requires session-membership evidence beyond self-asserted deployment identity. Saved-server requests require matching account ID and epoch, and allocation and display-target writes run under owner authority. Journal-slot checks block sends after an actual unlink. These controls protect initial linking and local ownership but do not independently authenticate a persisted alias’s current deployment.
Resilience and Maintainability Implications
- observed — Reset recovery preserves the key, advances the generation, and disables further reset/share recursion for that retry. Unknown reset outcomes remain pending. Teardown establishes its fence before suspension, while retirement allocation waits for the ordered registration turn and then advances the generation. This limits stale recovery work without relying solely on cancellation.
Hardening Proposals
- proposed — Bind shared-key use and retirement routing to current, independently verifiable deployment authority. Where that authority cannot be established, defer transmission rather than treating cached identity or slot equality as sufficient. Revalidate the binding after asynchronous proof and before committing a new link; cover reassignment with failed identity discovery and session-free retirement in focused transition tests.
Pre-merge checks: 
4 · 
1
-
Failed checks: 1 warning Passed checks: 4 passed-
Full details: Description check
-
Explanation
The description directly explains the Apple push installation-key mismatch recovery, reset endpoint integration, shared installation records, registration behavior, testing, and known risks. These topics match the changeset.
-
Full details: Docstring Coverage
-
Explanation
Docstring coverage is 78.95% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 38 functions across 9 files.
Resolution
Write docstrings for the functions missing them to satisfy the coverage threshold.
-
Finishing Touches
-
Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
|
This reset path can restore Apple push delivery, making notifications visible on iPhone, iPhone Duo (folded and open), and iPad. The Evidence section says there is no user-visible change and provides only server logs, so it does not show this effect. Please add a recording or captures showing a notification arriving for each of those device configurations, identified with the device and build or commit. Suggested fix: No diff — add the requested notification evidence. Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
| // The same key, and no generation: the server accepts any | ||
| // positive generation now, and this record starts again at 1. | ||
| let fresh = ApplePushInstallationRecord(installationKey: command.installationKey, generation: 0, latest: nil) | ||
| restarted = try ApplePushInstallationJournal.plan(fresh, desired: command.intent, renewDisplayToken: false) |
There was a problem hiding this comment.
Generation ordering failure in iosApp/iosApp/Notifications/ApplePushRegistration.swift occurs when an aborted sign-out followed by restore resets ApplePushInstallationRecord to generation 0 and restarts registration at generation 1 with the same command.installationKey. ApplePushRetirementQueue.cancel removes only queued records, so an already-dispatched retirement with that key and a higher generation can arrive after the reset and recovered registration, causing the server to accept the stale retirement and disable pushes that restore just re-enabled.
Prompt for LLM
File iosApp/iosApp/Notifications/ApplePushRegistration.swift:
Line 605 to 608:
Generation ordering failure in iosApp/iosApp/Notifications/ApplePushRegistration.swift occurs when an aborted sign-out followed by restore resets ApplePushInstallationRecord to generation 0 and restarts registration at generation 1 with the same command.installationKey. ApplePushRetirementQueue.cancel removes only queued records, so an already-dispatched retirement with that key and a higher generation can arrive after the reset and recovered registration, causing the server to accept the stale retirement and disable pushes that restore just re-enabled.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Agreed, and it's worse than a lost registration: once a stale retirement with a higher generation lands, a registration restarted at 1 would get 409s until the counter caught up. Fixed in d751581. After a reset the app registers at the generation after the refused one, above everything this record sent before the reset, so a retirement still in flight from before it is ordered below the new registration and refused.
There was a problem hiding this comment.
That addresses the original finding as described. Registering at the next generation, rather than restarting at 1, keeps the recovered registration above earlier retirements from the same installation record. A delayed retirement therefore cannot disable it or leave subsequent registrations receiving 409s while the counter catches up.
The separate cross-address retirement race remains outside this fix; it does not invalidate this correction.
There was a problem hiding this comment.
Actionable comments posted: 1

Review info
-
Run configuration-
- Source mode: Auto
- Repository: Unavailable
- Branch: Unavailable
- File: No configuration file from this repository applied
- Commit: Unavailable
- Layers: Organization UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
256ecc1f-50a4-4a1b-b587-a901beeb7939
Files selected for processing: 7-
iosApp/Tests/ApplePushOrderedRegistrationTests.swiftiosApp/iosApp/Networking/APIv2/APIv2Client.swiftiosApp/iosApp/Networking/APIv2/APIv2PushModels.swiftiosApp/iosApp/Networking/APIv2/APIv2RetrySafety.swiftiosApp/iosApp/Notifications/ApplePushInstallationJournal.swiftiosApp/iosApp/Notifications/ApplePushRegistration.swiftiosApp/iosApp/Notifications/ApplePushRegistrationChannel.swift
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
-
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d167787417
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let fresh = ApplePushInstallationRecord(installationKey: command.installationKey, generation: 0, latest: nil) | ||
| restarted = try ApplePushInstallationJournal.plan(fresh, desired: command.intent, renewDisplayToken: false) |
There was a problem hiding this comment.
Clear the old hold when restarting the installation journal
In the iOS registrar, if an earlier reset refusal held generation 1, a token/profile change can allocate generation 2 and successfully reset the installation. This restart then reuses generation 1 without clearing the old held[serverID] entry. If the post-reset registration fails with a transport error before reaching the server, dispatch returns .uncertain, but the next same-intent foreground attempt returns .notSent(reason: "held") because the old hold matches the new generation. Notifications remain unrecovered for the remainder of the six-hour hold window, unless the app is relaunched. Clear the old hold after a successful reset, or keep generations monotonic.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: a new test reproduced it on the old code (the retry after a successful reset came back notSent(held)). Fixed in d751581 by keeping generations increasing. After a reset, the registration goes out at the generation after the refused one instead of restarting at 1. The server's cleared installation accepts any positive generation, so a hold from an earlier attempt can no longer match it.
…lation reset After an owner reset the journal restarted at generation 1. A retirement from a sign-out already sent at a higher generation could then land after the new registration and switch push off, and every later registration from the lower generation got 409. A hold left on generation 1 by an earlier refused reset also blocked the replay of a post-reset registration whose answer was lost, for six hours. The registration after a reset now takes the next generation above the highest the record has allocated. The cleared installation accepts any positive generation, so the server still binds it, and nothing sent before the reset can outrank it.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d751581b72
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if mayResetInstallation, !command.isRenewal, Self.isInstallationKeyMismatch(error) { | ||
| return await resetInstallation(after: command, body: body, through: channel) |
There was a problem hiding this comment.
Exclude teardown intents from installation-key recovery
If the same server is saved at two URLs and the newer entry has recovered successfully, removing the older entry can disable notifications for the surviving one when its retirement request fails in transport or exceeds retirementBudget. unregister then sends a new pushMode == "off" intent, which passes this non-renewal guard and resets the surviving entry's installation before disabling it. The surviving entry still has an accepted journal entry and current display target, so subsequent foreground attempts return .unchanged and leave pushes disabled until another intent change. An off teardown should not reclaim an installation belonging to another saved entry.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in edc0d54. A teardown's off no longer triggers the reset. On a mismatch it gets today's hold, and the retirement queued after it still runs, so the alias that's still saved keeps the installation. testTeardownOffOnAKeyMismatchIsHeldWithoutAReset covers it; it sent a reset and came back .registered before the fix.
| return await dispatch(retry, allocating: restarted.record, body: body, through: channel, | ||
| mayResetInstallation: false) |
There was a problem hiding this comment.
Reconcile display targets when recovering a second server address
When a second saved URL for the same deployment/profile is recovered with a display token while the original URL's target remains, this retry creates two local targets. ApplePushDisplayTargetStore.save only replaces targets with the same registryServerID, so it preserves the original target. ApplePushDisplayStateReader.route then returns .ambiguousTarget at ApplePushDisplayMetadata.swift:195–196, and NotificationService skips display fetching for every push naming that server/profile. Notifications therefore retain generic content despite successful recovery, and the original URL's previously working display route also stops working. Recovery needs to reconcile legitimate alias targets while retaining the existing protection against unrelated servers claiming the same identity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: after the second alias recovers, both aliases hold a display target for the same server and profile, route returns .ambiguousTarget, and pushes for that server fall back to generic content.
I haven't fixed it in this PR because the direct fix weakens the identity check. Dropping other entries' targets with the same server_id after a reset trusts an ID each server reports about itself. A saved server could then claim another server's identity, trigger a reset and take over its display route. The safe options need new logic: renew each other alias with the same identity and profile after a reset, and drop only the targets whose own server answers with a mismatch. Or have an alias drop its own target when a renewal gets a mismatch, which only takes effect when the target expires. The PR lists this under Risks while a maintainer picks the approach.
There was a problem hiding this comment.
Fixed in fca323e, 83605dd and a989b95, with the journal now shared per server rather than per address.
When an address hits push_installation_key_mismatch, the app looks for another saved address that reports the same server_id. That ID only picks which address to ask. The proof is a login session: the mismatched address's own current session ID has to appear in the other address's session list, each fetched with that address's own credentials. Only the same backend can list it, so a server that merely claims the ID never receives the key.
Once proven, the two addresses share one journal record and key, and nothing is reset. An accepted registration removes the other address's display target, so one target is left per server and profile, and pushes keep their text. A renewal that hits the mismatch hands the installation and target to the other address, which also repairs a device already left with two targets.
Tests cover a proven second address, a server claiming the same ID without the proof, and the handover. An end-to-end run with one server saved under two addresses is in the PR body.
…rdown's off When one server is saved under two addresses and the older entry is removed, its off intent meets the surviving entry's key. Resetting there cleared the surviving entry's installation before disabling it. A teardown's off now keeps the hold behaviour on a key mismatch.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: edc0d543ff
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let serverID = channel.owner.serverID | ||
| let mismatch = "http_403_\(Self.installationKeyMismatch)" | ||
| do { | ||
| let receipt = try await channel.reset(command.intent.body.deviceId, command.installationKey) |
There was a problem hiding this comment.
Restore the surviving alias when the recovered entry is removed
If A is registered and a second saved URL B for the same deployment/account/profile recovers here, removing B successfully retires the only live installation while A's journal still says .accepted. Credential cleanup removes only B's display target, so A's still-current target makes needsDisplayToken false and register returns .unchanged on subsequent foregrounds with the same intent, leaving the still-saved, signed-in A without notifications. This reaches the normal .retired early return in unregister, not the off fallback protected by the new guard. Record the alias handoff so retiring the recovered entry can restore registration through a surviving saved entry.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is handled by the shared-record commits (fca323e onward), and the case still holds at b5403a8. Both addresses now share one record, which keeps each address's last owner. When the address that registered last is removed, its retirement stops the installation, and the next saved-server pass registers the surviving address again as itself with the shared key. testSurvivingAddressTakesTheSharedInstallationBackAfterTheHolderIsRemoved covers this sequence and passes at b5403a8.
🤖 Claude Code (claude-opus-5-5)
…r's proven addresses One server saved under two addresses has one installation for this device, but each address kept its own journal record and key, so the second address hit a key mismatch and, after a reset, both kept a display target and pushes for that server lost their text. On a key mismatch, an address now looks for another saved address that reports the same server identity and lists this address's own login session. Session IDs are random and only the issuing backend knows them, so the reported identity alone never shares a key. A proven address links its record to the other's, registers with that key at the next generation, and a renewal hands the installation over instead. An accepted registration removes the other addresses' display targets, and removing an address that does not hold the installation sends nothing.
… holder leaves A shared installation record remembered only the owner of its latest intent, so once the address that registered last was removed or lost its session, the other address could not register again until it was the active server. The record now keeps each address's last owner, and maintenance registers a surviving address as itself when the latest owner no longer holds its session. A link also records the deployment identity it was proven for, and is dropped once the address reports another deployment, so a different server later saved at that address never gets the shared key.
…tallation record A renewal that links to another address's record allocates no intent, and a record from an earlier build stores no owners, so the linking address's owner never reached the shared record and it could not take the installation back once the other address left. Linking now carries over the owners both records know, including each one's latest.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
Actionable comments posted: 1

Review info
-
Run configuration-
- Source mode: Auto
- Repository: Unavailable
- Branch: Unavailable
- File: No configuration file from this repository applied
- Commit: Unavailable
- Layers: Organization UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
b20509e9-417e-4712-9b3e-0842c678b502
Files selected for processing: 7-
iosApp/Tests/ApplePushOrderedRegistrationTests.swiftiosApp/iosApp/Networking/APIv2/APIv2Client.swiftiosApp/iosApp/Networking/APIv2/APIv2PushModels.swiftiosApp/iosApp/Notifications/ApplePushDisplayTargets.swiftiosApp/iosApp/Notifications/ApplePushInstallationJournal.swiftiosApp/iosApp/Notifications/ApplePushRegistration.swiftiosApp/iosApp/Notifications/ApplePushRegistrationChannel.swift
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
-
| func dropLink(of serverID: String, unlessProvenFor identity: String) throws { | ||
| guard let link = try storedLink(of: serverID), link.provenServerID != identity else { return } | ||
| guard keychain.delete(Self.linkAccount(for: serverID)) else { throw JournalError.writeFailed } |
There was a problem hiding this comment.
Deployment isolation fails when the address owning a shared record changes deployments because dropLink returns immediately for an address with no outgoing link, leaving other addresses attached to its record. With B linked to A, registering A against a replacement deployment overwrites B's shared installation state, removes B's display target through sharingRecord, and makes saved-server maintenance follow A's owner instead of B's original deployment; preserve the original deployment's record for its remaining aliases when detaching the record-owning address.
Prompt for LLM
File iosApp/iosApp/Notifications/ApplePushInstallationJournal.swift:
Line 210 to 212:
Deployment isolation fails when the address owning a shared record changes deployments because `dropLink` returns immediately for an address with no outgoing link, leaving other addresses attached to its record. With B linked to A, registering A against a replacement deployment overwrites B's shared installation state, removes B's display target through `sharingRecord`, and makes saved-server maintenance follow A's owner instead of B's original deployment; preserve the original deployment's record for its remaining aliases when detaching the record-owning address.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Fixed, though not with a handover: a9e444d and 5b314f7 change how a shared record is stored.
The first time a record is shared, it moves to a Keychain item of its own (shared-<UUID>) that no address owns, and both addresses get a link that records the server ID it was proven for. No address owns the record's slot any more. One that later reports another server drops only its own link, deleting anything left in its own slot first, and starts over with a new key. The other addresses keep the record, its key and their display targets.
A handover (6af5878) was tried first. It could be interrupted between Keychain writes, it missed addresses that were removed but still linked, and it missed link chains. Moving the record to a slot no address owns removes all three. testFirstAddressReportingAnotherDeploymentLeavesTheSharedRecordToTheSecond covers this case: the first address starts at generation 1 with a new key, and the second keeps registering with the shared key.
There was a problem hiding this comment.
That addresses the original finding as described; a handover isn’t required.
The important change is that every address now links to an address-independent shared record. The first address no longer has special ownership, so when its deployment identity changes, it can detach without replacing the record or disturbing the remaining addresses’ key, generation history, or display targets. Deleting its old address-local slot before unlinking also prevents stale installation state from being reused.
testFirstAddressReportingAnotherDeploymentLeavesTheSharedRecordToTheSecond targets the reported failure directly: the changed address gets a fresh key at generation 1, while the other address retains the shared key.
Based on that explanation, I consider the original concern addressed. I haven’t independently inspected the updated commits.
| guard let own = try? await loginSessions(nil).currentSession?.id, !own.isEmpty else { return false } | ||
| var cursor: String? | ||
| for _ in 0..<Self.maximumSessionPages { | ||
| guard let page = try? await holder.loginSessions(cursor) else { return false } |
There was a problem hiding this comment.
Stale ownership validation allows this method to return true after either session changes: holder requests check ownership only before suspension, and this channel's owner can change while holder pages are being fetched. After each page returns, revalidate both channels against the captured owners through their authority gates before inspecting the page or accepting it as proof, and return false if either ownership check fails.
Also found in:
iosApp/iosApp/Notifications/ApplePushRegistrationChannel.swift:35-35
Kody rule violation: Fence asynchronous results by scope and invalidation generation
guard let page = try? await holder.loginSessions(cursor) else { return false }
do {
try await commit({})
try await holder.commit({})
} catch {
return false
}Prompt for LLM
File iosApp/iosApp/Notifications/ApplePushRegistrationChannel.swift:
Line 38:
Stale ownership validation allows this method to return true after either session changes: holder requests check ownership only before suspension, and this channel's owner can change while holder pages are being fetched. After each page returns, revalidate both channels against the captured owners through their authority gates before inspecting the page or accepting it as proof, and return false if either ownership check fails.
**Also found in:**
- `iosApp/iosApp/Notifications/ApplePushRegistrationChannel.swift:35-35`
Suggested Code:
guard let page = try? await holder.loginSessions(cursor) else { return false }
do {
try await commit({})
try await holder.commit({})
} catch {
return false
}
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Not changing this one. sharesBackend proves that two addresses reach one backend: the holder lists the other address's login session. A sign-out or account switch while the pages load doesn't change which backend an address reaches, so a result read after the switch is still true. Nothing in the check writes owner-bound state. The writes that follow are the generation allocation and the display target in dispatch, and both run through channel.commit, which refuses them once the owner has changed. Re-checking after every page would add two authority checks per page and guard nothing the commit fence doesn't already guard.
There was a problem hiding this comment.
Agreed—the suggestion conflates proof of backend identity with authority to commit owner-bound changes.
A session listed by the holder still establishes that the two addresses reached the same backend, even if either session changes while the request is in flight. That result does not itself authorize a write. As you describe it, channel.commit separately fences generation allocation and display-target updates against the captured owner.
Given those commit fences, the original suggestion does not identify an unprotected mutation or show how stale proof bypasses authorization. Adding two checks after every page would invalidate a still-valid backend observation without closing a demonstrated correctness gap.
I would not require this change or treat this finding as an actionable violation of the rule.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a989b95f53
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if owner.serverID != serverID, let own = record.owners?[serverID], !(await holdsSavedSession(owner)) { | ||
| owner = own |
There was a problem hiding this comment.
Fall back to a valid alias after the holder's session is rejected
While an unrelated server is active, if the last-registering alias's access token expires and its refresh is rejected, a surviving alias with a valid session is never tried. savedSessionAccount only checks the persisted account/epoch, and HTTPClient.renewInactiveServer leaves that slot intact on .rejected, so holdsSavedSession remains true and every alias iteration selects the unusable holder again. Consequently APNs token changes and display-token renewals cannot reach this deployment until the user activates an alias or signs in again. Fall back to the alias's recorded owner on definitive credential rejection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b62d6a9. The saved-server client now throws credentialRejected when the address's refresh is refused (ApproverBearer.rejected). registerSavedServers then registers once more as this address's own last owner from record.owners. A refresh that only failed for now (no answer, 5xx, provider_unavailable) still surfaces as noCredential and leaves the installation where it is, so a short outage at one address doesn't move the installation or its profile to the other. testSurvivingAddressRegistersAsItselfWhenTheHolderHasNoCredential covers both: a 503 refresh sends nothing, and a 401 refresh registers through the other address with the shared key.
| try journal.link(serverID, toRecordOf: candidate, provenFor: identity) | ||
| guard let record = try journal.load(serverID: serverID) else { return nil } |
There was a problem hiding this comment.
Clear stale holds when linking to a shared installation record
Unlike the fixed reset path, the new registerShared path can reuse a held generation from the discarded installation record: B held at generation 2 can allocate 3, link to A at generation 1, and retry at 2. If that retry fails in transport before reaching the server, the next same-intent attempt returns .notSent(reason: "held") rather than replaying the pending registration, delaying APNs-token recovery for six hours. Clear held[serverID] after a successful link, or scope holds to the installation key as well as generation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b62d6a9: held[serverID] is cleared once the address links to the shared record, since a hold names a generation of the record it replaced. testHoldOnTheReplacedRecordDoesNotBlockTheSharedRegistration reproduces your sequence: held at 2, mismatch at 3, link, a lost answer at shared generation 2. The next attempt now replays generation 2 instead of returning notSent(held).
…eft the server An address whose link was dropped could still be named as the last to register in the other address's record, so removing that address sent nothing and maintenance kept routing it through the departed one. The latest owner now counts as another address only while it still shares the record. When the address that owns a shared record reports another server, the addresses linked to it take over the record and key, and it starts over with its own.
There was a problem hiding this comment.
Actionable comments posted: 1

Review info
-
Run configuration-
- Source mode: Auto
- Repository: Unavailable
- Branch: Unavailable
- File: No configuration file from this repository applied
- Commit: Unavailable
- Layers: Organization UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
261b2f94-a9a5-4a14-b688-571f894f589a
Files selected for processing: 3-
iosApp/Tests/ApplePushOrderedRegistrationTests.swiftiosApp/iosApp/Notifications/ApplePushInstallationJournal.swiftiosApp/iosApp/Notifications/ApplePushRegistration.swift
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
-
Follow-up review fixes for the shared installation record: - Check that the address still resolves to the slot a command was planned from before sending a registration or a reset, and before storing the display target from its answer, so a link that ended in between neither sends the shared key nor brings back the moved address's target. - Return the shared record's slot from the share path before its first await, so a link that ends during it is caught. - Recheck a fallback `off`'s teardown once it gets its turn, so an `off` queued behind the other address's registration is not sent after that registration ended the teardown. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Maintainer review summaryReviewed head: 8fea10a (this rerun's fixes in 6d4a794, 7bbbdab, 79b2e5d, 20c3c76, f5d0541, c1348ea and 8fea10a, on top of b5403a8). Base: main at 3bd7573. The server half, silo-server#3352, is merged. Fit: 7/10 · Readiness: 9/10 — conditional (assuming CI is green) Fit 7. Same as the last round. A reinstalled iPhone, or the same server saved under a second address, never gets push back, so this closes a real gap in the core notification experience, and the fix sits at the right boundary: an owner-only reset on the server and recovery in the app. The score is held down by cost and parity. The shared-record machinery (links, per-address owners, stale-link handling, alias routing) is a large client surface for the second-address case, and Android has no matching recovery path and no linked parity issue. Readiness 9. Every defect found in this PR's code is fixed, each with a regression test that failed first. The behavior was shown live against server main. What remains is a server-side gap tracked in its own issue, plus three accepted trade-offs listed below. Fixed in this round
The last two came from the cross-provider rounds. Codex (gpt-6.1-sol) reviewed 6d4a794 and 7bbbdab: round 1 found the stored-alias problem, and round 2 marked it resolved and found the read-before-route race. Both are fixed above. Round 2 found nothing else in the actor ordering, back-off bookkeeping, or the proof change. The last five rows came from the Codex GitHub reviews of 79b2e5d, 20c3c76, f5d0541 and c1348ea. Declined with evidence: serializing a routed retirement's last synchronous steps with link removal ( Left for the maintainers
Validated features
Validation statusTask #336 lists C1 and C2 as not run on iPhone and iPad, so no recorded pass can regress. I couldn't read the board itself (no project scope in this environment). Other checks
🤖 Claude Code (claude-opus-5-5) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b5403a8fc6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let holder = try? journal.load(serverID: candidate)?.latest?.intent.owner, | ||
| let holderChannel = savedServers.channel(for: holder), | ||
| await channel.sharesBackend(with: holderChannel) else { continue } |
There was a problem hiding this comment.
Validate the holder before trusting its backend proof
If A and B share a record last registered by B, and B now reports another deployment while its old session remains saved, a third address C claiming A's server_id can pass this check using only B's replacement backend. The stale-link check above applies to candidate A, but the session proof comes from latest owner B without checking B's deployment or whether its link is stale. A backend controlling B and C can therefore supply both session responses and make registerShared send A's still-live installation key to C without contacting A. This was reproduced with the extracted proof, journal, and channel code in an isolated Swift harness. Revalidate the holder's deployment and link before using its session list to authorize sharing the candidate's record.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. shareProvenRecord asked the record's latest owner for the session proof, and that can be another address that has moved to another server since, with its link not yet dropped. That server could vouch for a third address claiming the first address's server ID, and the third address then got the shared key.
Fixed in 6d4a794: the proof now goes through the candidate's own last owner, which is the address whose server ID and link were just checked. An address that moved is never asked. testProofComesFromTheCandidatesOwnAddressNotTheLastToRegister reproduces your sequence. At b5403a8 the third address got the first address's key and no reset was sent. Now it resets with its own key.
Verified at 79b2e5d: the push registration suites (92 tests) and the full SiloTests suite (3692 tests) pass on an iPhone 17 Pro simulator (iOS 27.0). A live run against server main confirmed the two-address sharing still works.
🤖 Claude Code (claude-opus-5-5)
…s, and retire through one still sharing it The session proof for a candidate address now comes from that address's own last owner, whose deployment was just checked, rather than from the address that registered last on the shared record. That address may have moved to another server since, and could vouch for a third address claiming the first one's identity. A retirement for an address that shares its record now goes to another saved address still sharing it, so a retry months later never carries the shared key to whatever server answers at the departed address. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y attempt A retirement for an address sharing its record was queued with another sharing address's URL. If that address later moved to another server, a retry still went there with the shared key. The queue now keeps the departing address's own URL and asks the registrar for a route on each attempt: another saved address that still shares the record, checked at that moment, or the stored URL when none does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The retirement queue read the record's key before the route lookup suspended. If the departing address was added again for another server during that lookup, its link ended, the route came back empty, and the already-read shared key went to the departing address. The queue now chooses the route first, then reads the record, and sends nothing when the departing address and the chosen one no longer share the record the route was chosen for. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
| guard await dropStaleLink(of: alias), sharesRecord(alias, with: entry.serverID), | ||
| let aliasURL = ServerRegistry.url(forServerId: alias), | ||
| let slot = try? journal.recordSlot(for: alias) else { continue } | ||
| return ApplePushRetirementRoute(serverURL: aliasURL, alias: alias, slot: slot) |
There was a problem hiding this comment.
Credential exposure in retirement routing occurs because dropStaleLink treats savedServerIdentity, whose production implementation only returns the persisted verifiedServerId, as confirmation that an alias still reaches the original deployment. If the alias's address is reassigned before its next identity refresh, the route sends the shared X-Push-Installation-Key to the replacement server, exposing the credential that authorizes retirement on the original deployment; require fresh authenticated evidence that the alias still reaches that deployment before forwarding the key.
Prompt for LLM
File iosApp/iosApp/Notifications/ApplePushRegistration.swift:
Line 470 to 473:
Credential exposure in retirement routing occurs because `dropStaleLink` treats `savedServerIdentity`, whose production implementation only returns the persisted `verifiedServerId`, as confirmation that an alias still reaches the original deployment. If the alias's address is reassigned before its next identity refresh, the route sends the shared `X-Push-Installation-Key` to the replacement server, exposing the credential that authorizes retirement on the original deployment; require fresh authenticated evidence that the alias still reaches that deployment before forwarding the key.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
The trigger is real, but this route doesn't add the exposure, so I'm not changing it here.
- The alias already receives the shared key under the same check. Every saved-server pass and display-token renewal for the alias (
registerSavedServers,register→dispatch) sendsX-Push-Installation-Keywith the shared key to the alias's URL. That is gated by the same cachedverifiedServerIdthroughdropStaleLink. If the alias's address were reassigned before its next identity refresh, those requests would carry the key there first. A fresh proof on the retirement path alone wouldn't close that. - Without the route, the retirement goes to the departing address's own URL. That address has been removed or signed out, and its server ID is never checked again for up to 90 days of retries. The alias is still saved, and its cached ID is refreshed whenever it's activated or brought to the foreground. So the route never sends the key anywhere the default path wouldn't, and it usually sends it somewhere better checked.
- A live check per send wouldn't be authenticated evidence either.
GET /api/v2/system/identityis self-reported, and the session proof costs up to 11 requests and needs the alias's stored session.
The PR body lists the cached-ID limit under Risks, for every shared-key send. Refreshing an inactive address's server ID before any shared-key send would be a separate change across all those paths.
🤖 Claude Code (claude-opus-5-5)
There was a problem hiding this comment.
Agreed—the original suggestion is not justified as a critical, retirement-route-specific blocker.
The retirement route relies on the same cached-identity trust model as the other shared-key sends. Requiring fresh proof only here would leave that broader exposure unresolved. Routing through a still-saved alias also avoids relying exclusively on a departing address that may receive retries long after removal.
One qualification: the alias’s registration or renewal is not guaranteed to run before a retirement attempt, so those paths do not prove the key was already exposed. The retirement request can still be the first disclosure after reassignment. That preserves the underlying risk, but does not establish that this route needs a standalone fix.
A fresh self-reported server_id would not provide authenticated proof either. Stronger protection should be designed consistently across all shared-key sends, with explicit handling when session-based proof is unavailable.
Given the documented limitation, I would not require this route-only change for this PR. No repository or issue changes have been made.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 79b2e5dfb6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| guard try journal.recordSlot(for: serverID) == slot else { | ||
| throw ApplePushInstallationJournal.JournalError.linkChanged | ||
| } | ||
| try journal.save(allocated, serverID: serverID) |
There was a problem hiding this comment.
Persist shared allocations into the captured record slot
If maintenance for another alias unlinks this address while its allocation runs on the TokenStore actor, the link can disappear between this guard and save. ApplePushInstallationJournal.save resolves serverID again, so it writes the live shared installation key into the address's now-private slot. The later resolves check suppresses only this request: the next registration loads that copied record and sends the surviving alias's key to the replacement backend. A focused Swift harness reproduces this despite the unlink succeeding. Persist into the captured slot, or serialize unlinking with the check/write.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed from the source. The slot check and journal.save run inside channel.commit, on the TokenStore actor. While the registrar awaits that commit, it can run dropStaleLink for this address, and save(_:serverID:) resolved the link again. An unlink that landed between the two wrote the shared record, key included, into the address's own slot, and the next registration sent that key to the server the address reaches now.
Fixed in 20c3c76: the journal gains save(_:slot:), and the allocation writes to the slot it just checked. An unlink in that gap leaves the generation in the shared record, where it belongs, and the existing resolves check stops the send. The journal's other writes (allocateRetirement, record) run on the registrar actor with no suspension between load and save, and links change only there, so they can't interleave.
There's no regression test for this one. The race is between two actors inside one synchronous closure, and the harness has no deterministic way to land the unlink between the check and the write. The push registration suites (93 tests) and the full SiloTests suite (3693 tests) pass at 20c3c76 on an iPhone 17 Pro simulator (iOS 27.0).
🤖 Claude Code (claude-opus-5-5)
| if try journal.dropLink(of: serverID, unlessProvenFor: identity) { | ||
| displayTargets.removeTargets(registeredBy: serverID) |
There was a problem hiding this comment.
Clear generation holds when dropping a shared-record link
If A has generation 1 held because its accepted registration lacked a display token, and B subsequently shares A's record and registers, held[A] remains intact. When A reports another deployment, this path removes its link but leaves that hold. A then starts a fresh journal at generation 1; if its first registration fails in transport, the next same-intent attempt returns .notSent(reason: "held") rather than replaying the pending request, blocking push recovery until the old six-hour hold expires. This sequence reproduces in a focused Swift harness. Clear the address's hold after a successful unlink, as the sharing path already does when replacing a record.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 20c3c76: when dropStaleLink drops a link, it also clears that address's hold, as the sharing path already does when it replaces a record. testHoldEndsWithTheLinkItNamedAGenerationOf follows your sequence. Generation 1 is held after a registration accepted without a display token, the second address shares the record, the first address moves to another server, and its first registration there loses its answer. At 79b2e5d the replay came back notSent(held). At 20c3c76 it replays generation 1 and is accepted. The push registration suites (93 tests) and the full SiloTests suite (3693 tests) pass.
🤖 Claude Code (claude-opus-5-5)
…a hold with its link The allocation's slot check and its journal write run on the TokenStore actor while the registrar can unlink the address. The write resolved the address's link again, so an unlink that landed between the two left the shared record, with its key, in the address's own slot, and its next registration sent that key to the server it reaches now. The write now goes to the slot that was checked. Dropping a stale link also clears the address's held generation: the hold named a generation of the shared record, and the address starts over at generation 1, where an old hold blocked replaying a lost registration for six hours. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 20c3c76a5c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| guard resolves(serverID, to: slot) else { return .notSent(reason: Self.linkChangedReason) } | ||
| let receipt: APIv2ApplePushRegistrationReceipt | ||
| do { | ||
| receipt = try await channel.send(command.intent.body, command.installationKey, command.generation) |
There was a problem hiding this comment.
Revalidate shared-record links after credential awaits
For a saved alias B sharing A's record, this guard runs before ApplePushSavedServerClient.send awaits savedSessionAccount, freshAccessToken, and savedProfileToken. If concurrent retirement maintenance detects B's replacement deployment and removes its link during those waits, the resumed transport still posts A's live shared installation key to B's replacement backend, exposing the credential that can retire A's pushes. This reproduces with the extracted registrar/channel code by pausing credential lookup and unlinking B through retryPendingRetirements. Move the link validation to the final dispatch boundary after credential lookup, serialized with unlinking, for both registration and reset requests.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in f5d0541. The link check before channel.send ran before ApplePushSavedServerClient.send awaited the stored session, a possible token refresh, and the profile token. An address that reported another server during those waits still sent the shared key.
The saved-server transport now takes a keyGate and runs it last, after every credential await and right before the request leaves, for both registration and reset. The registrar's gate first ends a stale link against the address's current server ID. It then confirms the address still resolves to a record holding the key the request carries. When either fails, nothing is sent and the registration comes back notSent("journal_link_changed"). The active server's requests go through HTTPClient, whose final dispatch is already fenced by its identity-transition gate.
testSharedKeyIsCheckedAgainRightBeforeASavedAddressSends pauses a saved address's registration, flips its server ID, then lets it continue. At 20c3c76 the shared key went to that address. Now nothing does. At f5d0541 on an iPhone 17 Pro simulator (iOS 27.0), the push registration suites pass (94 tests) and the full SiloTests suite passes (3694 tests).
The check still runs just before URLSession takes the request, so a change in the instant between the two isn't caught. That gap can't be closed on the client.
🤖 Claude Code (claude-opus-5-5)
…ntial lookups A saved address's registration or reset checked its link before the transport awaited the stored session, a token refresh and the profile token. If the address reported another server meanwhile, the request still left with the shared installation key. The saved-server transport now asks the registrar, right before the request leaves, whether the address still holds the key it carries, after ending a stale link; when it doesn't, nothing is sent. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f5d0541969
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| send: { try await api.registerApplePush($0, installationKey: $1, generation: $2, auth: owner.request) }, | ||
| reset: { try await api.resetApplePushInstallation(deviceID: $0, installationKey: $1, auth: owner.request) }, |
There was a problem hiding this comment.
Gate active-server requests after their credential awaits
When active alias B shares A's record, an auth capture/refresh inside applePushRequest can suspend after dispatch checks the slot. If maintenance for A unlinks B after it reports another deployment, these active closures still send A's live key to B's replacement backend; the HTTP owner fence checks credentials, not the journal link. The new keyGate only protects savedChannel: an extracted registrar harness blocks the equivalent saved request but still sends the active request after unlinking. Apply the same post-credential ownership check at the active dispatch boundary for registration and reset, because the leaked key can retire A's pushes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in c1348ea. My earlier note that HTTPClient's identity-transition gate covers the active server was too broad. That gate fences owner and server switches, not the push journal's links. An active address that reports another server can be unlinked by a maintenance pass for the other address while its request captures or refreshes credentials.
HTTPClient.requestData gains an optional beforeDispatch hook. It runs after the credential capture and any refresh, right before each send of an owner-scoped request, including the resend after a 401 refresh. registerApplePush and resetApplePushInstallation pass the same key check the saved-server transport uses (holdsKey): end a stale link, then confirm the address still holds the key. Both transports now refuse with ApplePushRegistrationError.keyWithdrawn, and nothing is sent.
testSharedKeyIsCheckedAgainRightBeforeTheActiveServerSends pauses the active address's registration, flips its server ID, then lets it continue. At f5d0541 the shared key went out and the registration was accepted. Now it comes back notSent("journal_link_changed") and sends nothing. On an iPhone 17 Pro simulator (iOS 27.0), the full SiloTests suite passed (3695 tests) just before a refactor-only cleanup, and the push registration suites (95 tests) pass at c1348ea.
🤖 Claude Code (claude-opus-5-5)
… credential capture The active server's registration and reset go through HTTPClient, which fences owner and server switches but not the push journal's links. An address that reported another server while the request captured or refreshed its credentials still sent the shared installation key. HTTPClient.requestData gains an optional beforeDispatch hook, run right before each send of an owner-scoped request; the push registration and reset pass the same key check the saved-server transport runs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c1348ea7d2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ) | ||
| // The caller's last check, after the credential capture and any | ||
| // refresh above, right before the request leaves. | ||
| try await beforeDispatch?() |
There was a problem hiding this comment.
Recheck the key before retrying on the saved address
On iOS with a LocalRoute, an active alias's POST can wait on a LAN connection and then retry the saved URL after cannotConnectToHost or a TLS failure. The added hook covers the initial dispatch and 401 retry, but the separate fallback in HTTPClient.send at lines 1619–1623 never invokes it. If retirement maintenance unlinks that alias during the LAN wait, the fallback still sends its former shared installation key to the replacement backend; this reproduces with the extracted transport. Pass the hook through and rerun it before the saved-address retry for both registration and reset.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 8fea10a. The local-route fallback in HTTPClient.send went to the saved address without the hook. The hook now runs inside perform, ahead of its synchronous dispatch fence, so the fence still sits right before the send. It runs again before the saved-address retry in send. A refusal on that retry is rethrown unchanged (DispatchHookRefusal), not wrapped as a transport failure, so it doesn't mark the server unreachable.
testSharedKeyIsCheckedAgainBeforeTheSavedAddressFallback gives the active address a local route, refuses the LAN connection, and flips the address's server ID during that attempt. At c1348ea the request then went to the saved address with the shared key and was accepted. Now it comes back notSent("journal_link_changed"), and the only request is the refused LAN one. At 8fea10a on an iPhone 17 Pro simulator (iOS 27.0), the full SiloTests suite passes (3696 tests).
🤖 Claude Code (claude-opus-5-5)
| let departing = try journal.recordSlot(for: entry.serverID) | ||
| let alias = try journal.recordSlot(for: routed.alias) | ||
| guard departing == routed.slot, alias == routed.slot else { |
There was a problem hiding this comment.
Serialize routed retirement dispatch with link removal
If alias A reports another deployment while B's pending retirement is being routed through it, the registrar can unlink A after this comparison because attempt runs on a different actor. B still resolves to the shared record, so the following load succeeds and transport posts the shared installation key to A's replacement backend, even when another saved alias retains that live installation. This reproduces with the extracted queue and journal by pausing the record read after route validation and unlinking A. Serialize validation and starting the retirement transport with link removal; consecutive Keychain reads on the queue actor do not prevent this race.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
I'm not changing this one. After the route check, attempt makes only synchronous Keychain reads on the queue actor and then calls the transport. APIv2Client.retireApplePushInstallation builds the request and calls session.data(for:) with no await in between. So the window you describe is an unlink on another actor landing within those synchronous steps. That's the same irreducible gap that sits between any check and URLSession taking a request. Every other key-bearing path in this PR now checks at the same point, right before the send, and stops there.
Closing that last instant would mean holding off every unlink until each send's request has been handed to URLSession. That's a lock across two actors, and a send that never completes could block maintenance for good. The earlier versions of this path left real awaits between check and send: the route lookup, and the read before it. Those are fixed in 7bbbdab and 79b2e5d.
🤖 Claude Code (claude-opus-5-5)
…lback An active request that tried the local route first and then went again to the saved address skipped the push key check on that second send. The local attempt can wait on a LAN connection, and the address's link to a shared record can end meanwhile. The beforeDispatch hook now runs inside perform, ahead of its dispatch fence, and again before the saved-address retry in send. A refusal there is rethrown as is rather than reported as a transport failure, so it doesn't mark the server unreachable. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Problem
Related issue: Silo-Server/silo-server#3348
Validation tasks: reaches #336 C1 and C2 (neither has a result yet)
The server side of this fix is Silo-Server/silo-server#3352, now merged.
When an iPhone sends an Apple push installation key that does not match the one the server stored for its device ID, the server refuses every registration with 403. The app holds the refusal and tries again after six hours or on the next launch, and gets the same 403 each time, so notifications never come back for that server. This happens when the device ID survives but the key does not: the app loses its installation record, or the same server is added again under a different address. The second case produces a mismatch every time, because the record that holds the key is stored per server address while the device ID is shared.
silo-server#3352 tells the owning account about the mismatch with the problem type
push_installation_key_mismatchand addsPOST /api/v2/devices/push/apple/reset. With this change the app uses them. When the mismatch comes from the same server saved under a second address, and that address proves it reaches the same server, both addresses share one installation record and key, and nothing is reset. Otherwise the app clears its own installation on the server with its current key and registers again.Approach
When a registration gets
push_installation_key_mismatchand the server's Apple push capability reportsinstallation_reset_available, the registrar callsresetApplePushInstallationwith the current key. It then sends the same registration again with the same key at the next generation. The cleared installation accepts any positive generation, and the next one stays above everything the device sent before the reset, so a sign-out retirement still in flight, or a hold from an earlier attempt, cannot outrank or block the new registration. It makes one reset per registration attempt: a second mismatch after the reset holds the generation as any 403 does now. A reset that gets no answer (timeout, 5xx) leaves the registration pending, so the next foreground or token change tries again. The contract makes a repeated reset safe. A refused reset holds the generation.Behaviour stays as it is for
permission_denied, for servers that do not report the capability, and for display-token renewals. A mismatch on a renewal means the same server is saved under a second address and that record registered since. Resetting there would let the two records take the installation from each other on every renewal, so only a new or pending registration resets. This departs from the contract's "the app resets its own installation" for that one case. A sign-out's or server removal'soffnever resets either: when the removed address loses the installation to the other one, a reset would clear the address that stays saved and then turn its pushes off. Thatoffis held as today, and the retirement queued after it still runs.Before resetting, the registrar checks whether another saved address is the same server. A matching
server_idfromGET /api/v2/system/identityonly picks which addresses to ask: any server can report any ID, and the installation key alone is enough to retire this device's pushes on the server that holds it. The proof is a login session: the app reads the mismatched address's own current session ID fromGET /api/v2/auth/sessions, then pages through the other address's session list, with that address's own credentials, looking for it (not marked as the caller's own). The list is always read from the address whose server ID was just checked, under its own last owner, never from a third address that happened to register last on a shared record. Session IDs are random UUIDs that only the issuing backend knows, so only the same backend, or a proxy for it, lists one. Each address is asked only about its own sessions, and nothing secret goes to the other address. When the proof holds, the record moves to a Keychain item of its own that no address owns, both addresses are linked to it, and:A link stores the server ID it was proven for. When an address later reports a different server (a reassigned local address, a fresh install at the same URL), only its own link is dropped, along with anything left in its own slot, and it starts over with its own key. The other addresses keep the record and key. While an address still shares the record it can hold the installation for the others. Once it stops sharing, or its server refuses its session's refresh, the others register, remove and restore as themselves. A refresh that only failed for now leaves the installation where it is.
Both transports get the reset and the session check: the active server's session and a saved server's stored session. iOS only; tvOS and macOS do not register for Apple push. Android has no matching recovery path in the contract.
Validation
ApplePushOrderedRegistrationTests: 53 passed. The two newest cases cover a refused refresh at the address that registered last (the other address registers as itself, while a 503 refresh moves nothing), and a hold left on an address's replaced record, which no longer blocks the registration after it links. The two cases before them cover an address that later reports another server: it never sends the shared key there, even with a copy left in its own slot, and the other address keeps the record; and removing or restoring the first address after the second moved, with nothing run for the second in between. The six cases before them cover a proven second address sharing the key with one display target left; a server that claims the sameserver_idbut fails the session check, which never receives the key (two cases: an unknown session ID, and the holder's own current session ID); removing the address that does not hold the installation; a renewal that hands the installation and target over; the other address registering again after the holder is removed; and an address that later reports another server dropping its link. Each new guard was disabled once to confirm its test fails without it.ApplePushOrderedRegistrationTests,ApplePushRegistrationTests,ApplePushNotificationSyncTests): 72 passed, including cases for mismatch with and without the capability,permission_denied,reset: false, the one-reset limit, unanswered and refused resets, a lost answer after a reset that follows an earlier refused one, and a sign-outoffthat meets a mismatch and is held without a reset.SiloTestssuite on an iPhone 17 Pro simulator (iOS 26.5) at the final commit: 3678 tests, 3 failures, all inPlaybackProtocolV3Tests(watch-party seek). The same 3 fail onmainand on this branch before the shared-record commits.Silo(iOS Simulator),SiloTV(tvOS Simulator) andSiloMac(macOS) succeed.scripts/ci/check-no-api-v1.sh: ok.ApplePushOrderedRegistrationTestscover an address whose stale link lends no record, a moved address's display target (also from a late answer), arestoreduring the teardown's lookup, a registration from the other address ending the holder's teardown (also with anoffalready waiting for its turn), and an allocation planned before the link ended. Each failed on the head before its fix and passes at b5403a8. The push registration suites (ApplePushOrderedRegistrationTests,ApplePushRegistrationTests,ApplePushNotificationSyncTests) pass, 89 tests, on an iPhone 17 Pro simulator (iOS 27.0).scripts/ci/check-no-api-v1.sh: ok. The fullSiloTestssuite and the tvOS and macOS builds were not re-run locally for these commits; CI covers them. The stale-link removal failure has no test, since it needs a Keychain delete failure.testProofComesFromTheCandidatesOwnAddressNotTheLastToRegisterfailed at b5403a8 (a third address claiming the first one's server ID got the shared key).testRetirementForASharedRecordGoesThroughAnAddressStillSharingItfailed at b5403a8 and at 6d4a794.testRetryReadsTheRecordAfterItsRoutefailed at 7bbbdab.testHoldEndsWithTheLinkItNamedAGenerationOffailed at 79b2e5d.testSharedKeyIsCheckedAgainRightBeforeASavedAddressSendsfailed at 20c3c76.testSharedKeyIsCheckedAgainRightBeforeTheActiveServerSendsfailed at f5d0541; c1348ea adds an optionalbeforeDispatchhook toHTTPClient.requestDatafor it, which only the push registration and reset pass.testSharedKeyIsCheckedAgainBeforeTheSavedAddressFallbackfailed at c1348ea; 8fea10a runs the hook again before a local-route request's retry at the saved address. 20c3c76 also writes an allocation to the record slot it checked; that race between two actors has no deterministic test. At 8fea10a on an iPhone 17 Pro simulator (iOS 27.0): the fullSiloTestssuite passes (3696 tests, 0 failures).403 mismatch,listSessions×2,200). Signing out of the address that registered last retired the installation, and the other address then registered again with the shared key. At 7bbbdab, a replaced key hash on the server led to403 mismatch,reset 200,register 200, and a later relaunch sent nothing.didRegisterForRemoteNotificationspath. Everything after that (the registrar, the Keychain record and the server) ran unmodified. The steps: sign in at one address and allow notifications (registered), then reinstall the app and sign in to the same server at a second address. That creates a new key for the same device ID. The results are under Evidence.http://127.0.0.1:<port>andhttp://localhost:<port>, which the app saves as two servers. Sign in at the first address and allow notifications, then add the second address and sign in to the same account, with no reinstall. Run once with the build before the shared-record commits and once with the final build on an erased simulator. Results under Evidence.Evidence
Evidence: https://evidence.siloserver.org/r/silo-apple/pr-977/ (request logs from the end-to-end run at 79b2e5d against server main, and the test results at 8fea10a).
The change affects background push registration only, so the evidence is the server log from the local run described under Validation. Before:
mainat 3bd7573. After: this branch at d167787. A notification arriving on a device cannot be shown here: the simulator gets no APNs device token on the test host, and this change does not touch delivery. It only gets the device registered again, which the log shows.Before, on
main: every launch is refused, and the app never sends a reset.After, with this branch (same steps; also seen when the fixed build is installed over the stuck one):
The server then holds an enabled Apple
push_devicesrow for the device, and the installation is bound to the new key. A later relaunch sends nothing more. That run predates d751581, which changed the generation sent after the reset (the next one instead of 1); the request sequence is the same.Same server saved under a second address, before the shared-record commits (edc0d54): the second address resets the installation, and both addresses then keep a display target.
After, at this branch's head: the session check passes, and the second address registers with the first address's key at generation 2, with no reset. A relaunch sends nothing more.
The server's
apple_push_installationsrow for the device is at generation 2. Accepting generation 2 after generation 1 with no reset in between means the second address sent the first address's key.Risks
Checklist
AI Disclosure
offno longer triggers the reset. Both models reviewed it and found nothing. The shared-record commits answer the last open review comment (two display targets for one server). Both models reviewed them in three rounds. Fixed from those rounds: the other address could not register again after the address that registered last was removed or lost its session; a link was never dropped, so a different server later saved at a linked address would get the shared key; and a renewal or a record from an earlier build left an address's owner out of the shared record. Not changed: a different server later answering at the address that owns the shared record still receives its key, which a single address already does today (see Risks). Also dismissed: links in an older format, since the commit that wrote them was never released. After the push, CodeRabbit and Kody found two more cases where an address reports another server: the other address's teardown and maintenance still followed the departed address, and the address whose slot held a shared record kept sending its key. Both are fixed. The second is fixed by keeping shared records in a slot no address owns, after a first fix (handing the record over) failed review: it could be interrupted between Keychain writes, missed removed addresses, and missed link chains. Both models reviewed the last three commits in three rounds; the last round found only a doc comment, now fixed. Codex then found two more: a holder whose refresh was refused kept its saved session, so the other address never took over, and a hold on an address's replaced record could block the registration after the link for six hours. Both are fixed. Both models reviewed those fixes. They found that the first version also moved the installation on a temporary refresh failure, and that its test's token lifetime was tight; both are fixed. Declined: Kody's request to re-check both logins after each page of the session check. The check proves which backend an address reaches, which an account switch doesn't change, and every write after it already runs under the owner fence.Note
Recover Apple push registration when the installation key changes
resetApplePushInstallationandloginSessionsendpoints in APIv2Client.swiftbeforeDispatchkey-ownership check in HTTPClient.swift, so a request is not sent when its server record no longer holds the installation keyoffrequest or retires a shared installation while another saved address still holds the record; reset requests are added to the replay allowlist in APIv2RetrySafety.swift, and link chains deeper than 8 report unreadable journal stateMacroscope summarized 8fea10a.