Notes/ServerSecurity.md (12361B)
1# Crossmate Audit
2
3Date: 2026-06-12 (updated 2026-06-16)
4
5Scope: Crossmate iOS/iPadOS app, shared app/extension code, tests, scripts, and
6Cloudflare Workers used by Crossmate. Crossmake was intentionally excluded.
7
8## Summary
9
10The highest-risk issue was the push worker's authentication model. The app
11previously shipped a shared push bearer in its bundle configuration, and the
12worker treated that bearer as the only authorization gate for registering
13devices and publishing pushes. Anyone who extracted that value from a real app
14build could use the worker as Crossmate. That issue has been addressed by
15replacing shared bearer authentication with per-install App Attest enrollment and
16signed worker requests. A temporary legacy-bearer fallback behind an
17environment flag was subsequently removed and the legacy push-bearer secret
18deleted from the worker (see Finding 1), so App Attest is
19now the only authentication path.
20
21The rest of the audit found lower-risk operational and robustness issues around
22push environment handling, local secret storage, engagement room authentication,
23and destructive local-store recovery behavior. All of these have since been
24addressed. The most substantive was the engagement room authentication design
25(Finding 4): the secret-in-URL symptom sat on top of a trust-on-first-use
26room-auth scheme whose HMAC signature added no security. Rooms are now
27registered with the worker ahead of connecting (secret in a POST body, never a
28URL), and the connect signature is verified against the worker-held secret.
29
30## Findings
31
32### 1. Push worker used a bearer secret embedded in the app
33
34Status: Fixed.
35
36Impact: High.
37
38The app read `CrossmatePushBearer` from its bundle configuration and sent it to
39the push worker. The Cloudflare worker accepted that shared value as sufficient
40authorization for `/register`, `/publish`, and unregister operations. Because the
41same bearer was present in every distributed build, extracting one app binary
42would expose the credential for all clients.
43
44The implemented replacement keeps Crossmate account-free while removing the
45global shared secret. Updated clients now enroll a per-install App Attest key
46with the worker, store the key ID locally, and sign each protected push request.
47The worker verifies Apple App Attest attestation, stores only the public key and
48assertion counter, and accepts push operations only when signed by the registered
49key. Existing collaborative games remain compatible for updated clients because
50CloudKit game state and push address derivation did not change; clients simply
51re-register the same push addresses under the new authentication scheme.
52
53The worker initially retained a legacy bearer fallback behind an
54environment flag as a rollback window. Resolved
552026-06-12: the fallback branch was removed from `Workers/push-worker.js`, the
56updated worker was redeployed, and the legacy push-bearer secret was
57deleted from the worker. App Attest is now the only authentication path.
58
59Deployment notes:
60
61- `APP_ATTEST_ROOT_CERT_PEM` has been uploaded to Cloudflare from
62 Apple's published App Attest root certificate.
63- `crossmate-push` has been deployed with App Attest environment and app identity
64 variables.
65- The regenerated `Crossmate iOS Distribution` provisioning profile includes
66 `com.apple.developer.devicecheck.appattest-environment`.
67- App Attest enrollment and signed worker requests have been validated on a real
68 client after the initial implementation session.
69
70### 2. Push environment handling can diverge between APNs entitlement and client registration
71
72Status: Fixed.
73
74Impact: Low (debug builds only).
75
76`Crossmate.entitlements` hardcoded `aps-environment: production`, while
77`PushClient` selected `sandbox` under `#if DEBUG` and `production` otherwise.
78TestFlight and App Store builds are release-signed, so both sides agreed on
79production there; the mismatch only affected local device debug builds, where the
80token's APNs environment and the environment registered with the worker could
81disagree and pushes silently fail. That failure mode was a diagnosability
82annoyance during development rather than a user-facing risk.
83
84Resolved 2026-06-12: a single `APS_ENVIRONMENT` build setting in `project.yml`
85(`development` for Debug, `production` for Release) is now substituted into both
86the `aps-environment` entitlement and a `CrossmateAPSEnvironment` Info.plist
87key. `PushClient` reads the Info.plist key instead of inferring from
88`#if DEBUG`, and disables push (failable init, logged to diagnostics) if the
89value is missing or unrecognised. Because the entitlement and the worker
90registration now derive from the same variable, they cannot diverge. This also
91corrects the Debug entitlement itself: development-signed builds previously
92claimed `production` while their provisioning profile said `development`.
93
94### 3. Account push secret storage and generation path is weakly guarded
95
96Status: Fixed.
97
98Impact: Low.
99
100The account push secret is stored in local defaults, and random generation
101failure was not treated as a hard failure: `generatePushSecret()` in
102`AccountPushCoordinator` discarded the `SecRandomCopyBytes` result, so on a
103(vanishingly unlikely) failure the minted secret would be the base64 of 32 zero
104bytes.
105
106Moving the local copy to the Keychain would change little, because the secret is
107deliberately replicated across the account's devices as a CloudKit `Decision`
108record — the private CloudKit database is already its dominant home. The
109severity is therefore Low rather than Medium.
110
111The boundary this finding originally documented — the secret is the HMAC key
112from which per-game push addresses are derived, those addresses acted as bearer
113capabilities, and the worker's `handlePublish` did not check that a caller
114participates in the game it pushed to, so any App Attest-enrolled client that
115learned a derived address could publish to that account — has since been closed
116(participation gating, below).
117
118Resolved 2026-06-12 (secret hardening): `generatePushSecret()` now checks the
119`SecRandomCopyBytes` status with a `precondition` (crashing is preferable to
120durably converging a predictable HMAC key across the account's devices) and
121reuses the existing `Data.base64URLEncodedString()` helper.
122
123Resolved 2026-06-16 (participation gating): publishing to a game now requires
124proving participation, mirroring the engagement room-secret scheme (Finding 4).
125Each shared game carries a per-game push credential (`GamePushCredentials` — an
126unguessable `credID` plus a 256-bit secret) in the Game record's `notification`
127field, synced only to CKShare participants. Devices register their per-game push
128addresses with the worker keyed under that `credID`, and a publish is signed
129with the game secret (HMAC over the App Attest request's already-validated body
130hash, timestamp, and nonce). The worker verifies the signature against the
131secret it holds for the credID and resolves targets only among addresses
132registered under it — so a caller can reach a game's participants only if it
133holds that game's secret, i.e. it is a participant. A signature alone would not
134have sufficed (the worker can't tell which addresses belong to which game), so
135the device address registration is credID-bound too; that binding is the part
136that actually closes the hole. Account-scoped sibling pushes
137(accountJoined/accountSeen) carry no credID and stay on the App-Attest-only
138path; their addresses derive from the account secret in the private database and
139were never participant-spoofable. Deployment: the Game record gains a
140`notification` String field (Development + Production) and the updated push
141worker must be deployed; older clients lose game pushes (the durable CloudKit
142path is unaffected), which is acceptable pre-release.
143
144### 4. Engagement room authentication is trust-on-first-use and its signature adds no security
145
146Status: Fixed.
147
148Impact: Medium.
149
150The secret-in-URL exposure originally flagged here was the symptom; the room
151authentication design underneath was the actual weakness.
152
153The client sent both the room secret and an HMAC-SHA256 signature over
154`roomID|authorID|deviceID|timestamp|nonce` as query parameters. The worker
155verified that signature using the secret supplied in the same request
156(`room-worker.js`), so anyone could mint a valid signature for any secret
157they chose — the HMAC added nothing. The real gate was a trust-on-first-use
158`secretHash` stored in the Durable Object: the first client to connect to a
159room defined its secret, and later connections had to match it. The secret
160itself was the bearer credential, and it travelled in the query string, where
161it could appear in logs, diagnostics, proxies, and tooling surfaces.
162
163Resolved 2026-06-12 (code): the worker gained a `POST /rooms/{id}/register`
164endpoint that stores the room secret from the request body — first write wins,
165re-registration with the same secret is an idempotent success, and a different
166secret is refused with 409. The websocket connect no longer accepts a `secret`
167parameter at all; the worker verifies the HMAC signature against the
168registered secret and refuses unregistered rooms. Timestamp-freshness and
169nonce-single-use checks already existed on the worker and are unchanged — with
170a server-held key they now carry real authentication. Clients register
171idempotently before every connect, which preserves the previous de-facto
172behavior that an idle-expired Durable Object room is resurrected by whichever
173creds-holder returns first, and removes any ordering race between the minting
174peer and peers that receive the creds via CloudKit. A 409 (room ID registered
175under a different secret, e.g. squatted after idle expiry) is surfaced as
176`EngagementReconcileOutcome.roomRejected`, and `EngagementLifecycle` clears the
177Game record's `engagement` field so a fresh room is minted and LWW converges
178the peers onto it.
179
180Deployed 2026-06-12: the updated worker refuses TOFU connects, so clients
181running builds that predate this change lose the live engagement channel
182(graceful — the durable CloudKit Moves path is unaffected). It was deployed
183alongside the updated clients.
184
185### 5. Core Data store recovery can erase local state
186
187Status: Fixed.
188
189Impact: Medium.
190
191The local persistence recovery path could wipe the Core Data store when store
192load or migration fails. The in-code rationale
193(`PersistenceController.recreateStore`) was that the store is a rebuildable
194cache of CloudKit, so a wipe is recoverable via refetch. That rationale does not
195hold in two cases:
196
197- iCloud sync is user-toggleable (`isICloudSyncEnabled`). For a user with sync
198 disabled, the local store is the *only* copy of their games, and the wipe is
199 total, permanent data loss.
200- Even with sync on, offline edits not yet uploaded through the sync engine are
201 lost.
202
203Resolved 2026-06-12: `recreateStore` now moves the failing store files
204(including the `-wal`/`-shm` sidecars) aside under a `.broken-<timestamp>`
205suffix before destroying and rebuilding, so the data stays inspectable and
206recoverable instead of being erased. The recovery event — including the original
207load error and the preserved file names — is surfaced through the diagnostics
208`EventLog`. `PersistenceController` gained an injectable store URL for tests,
209and targeted tests now cover both the failure path (broken store preserved
210byte-for-byte, empty store rebuilt) and the healthy path (reopening an existing
211store triggers no recovery). Preserved backups are not auto-pruned; the path
212requires a failed migration, so accumulation is not a practical concern.
213
214## Verification Performed
215
216After the App Attest push-auth changes, these checks passed:
217
218- `node --check Workers/push-worker.js`
219- `xcodegen generate`
220- `bash Scripts/build.sh`
221- `bash Scripts/test-unit.sh`
222
223Cloudflare was also updated operationally:
224
225- `APP_ATTEST_ROOT_CERT_PEM` secret uploaded.
226- `crossmate-push` deployed to its workers.dev URL.
227
228## Release Validation
229
230The App Attest challenge/registration path and signed worker requests have been
231validated on a real client. The remaining release checks are the broader
232end-to-end collaboration and push-delivery behaviors:
233
234- Fresh install registers for notifications.
235- Two updated clients can continue an existing collaborative game.
236- Background push delivery still works.
237- Worker logs remain clean during normal registration and publish traffic.