Skip to content

Commit 39d8f6a

Browse files
browclaude
andcommitted
fix(ios): keep rejected enrollment journals until replaced
A rejected journal was deleted before its replacement was prepared, so a failed challenge fetch or restart lost the rejection count and reset the backoff. Keep the rejected journal until the fresh request overwrites it. A 400 or 401 can also reject a request that committed before its response was lost, once its attestation certificate expires. The replacement then conflicts with the live installation, consumes its challenge, and replays as 404, which replaced again at once with the count reset. Count every replacement and apply the doubling wait to a 404 that follows one, so each such cycle mints a bounded number of App Attest keys. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Tom Brow <[email protected]>
1 parent bde482d commit 39d8f6a

2 files changed

Lines changed: 104 additions & 60 deletions

File tree

‎mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzDevPushEnrollmentDriver.swift‎

Lines changed: 30 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -404,13 +404,15 @@ public final class BuzzDevPushEnrollmentDriver {
404404
deviceToken: Data,
405405
relayURL: URL
406406
) async throws -> BuzzPushEndpointGrantRecord {
407-
try await enroll(deviceToken: deviceToken, relayURL: relayURL, rejectedReplacements: 0)
407+
try await enroll(deviceToken: deviceToken, relayURL: relayURL, replacing: nil)
408408
}
409409

410+
/// `rejected` is a journal the gateway terminally rejected. It stays durable,
411+
/// with its rejection count, until a fresh request overwrites it.
410412
private func enroll(
411413
deviceToken: Data,
412414
relayURL: URL,
413-
rejectedReplacements: Int
415+
replacing rejected: BuzzPushPendingEnrollmentRecord?
414416
) async throws -> BuzzPushEndpointGrantRecord {
415417
precondition(!deviceToken.isEmpty, "The APNs device token must not be empty")
416418
let relayOrigin = try Self.relayOrigin(relayURL)
@@ -424,37 +426,33 @@ public final class BuzzDevPushEnrollmentDriver {
424426
let storedForOrigin = storedRecords.first {
425427
$0.gatewayOrigin == gatewayOrigin && $0.relayOrigin == relayOrigin.text
426428
}
427-
let pendingEnrollment = try store.pendingEnrollment(
429+
let journal = try store.pendingEnrollment(
428430
gatewayOrigin: gatewayOrigin,
429431
relayOrigin: relayOrigin.text
430432
)
433+
let pendingEnrollment = journal == rejected ? nil : journal
431434
if let pending = pendingEnrollment,
432435
pending.relayPubkey != relayPubkey || pending.endpointHash != endpointHash
433436
|| pending.expiresAt <= nowSeconds
434437
{
435438
// Finish an unexpired request using its exact journaled endpoint before
436439
// replacing it. A token/key change does not make a response-lost request
437440
// safe to discard, nor does it require revoking sibling installations.
438-
var replacements = 0
439441
if pending.expiresAt > nowSeconds {
440-
if case .replaced(let count) = try await resumeEnrollment(
442+
if case .rejected = try await resumeEnrollment(
441443
pending,
442444
storedRecords: storedRecords,
443445
relayMetadataPubkey: nil
444446
) {
445-
replacements = count
447+
return try await enroll(deviceToken: deviceToken, relayURL: relayURL, replacing: pending)
446448
}
447449
} else {
448450
try store.removePendingEnrollment(
449451
gatewayOrigin: gatewayOrigin,
450452
relayOrigin: relayOrigin.text
451453
)
452454
}
453-
return try await enroll(
454-
deviceToken: deviceToken,
455-
relayURL: relayURL,
456-
rejectedReplacements: replacements
457-
)
455+
return try await enroll(deviceToken: deviceToken, relayURL: relayURL, replacing: nil)
458456
}
459457
let newestSharedGrant = storedRecords.filter {
460458
$0.gatewayOrigin == gatewayOrigin && $0.relayPubkey == relayPubkey
@@ -561,9 +559,10 @@ public final class BuzzDevPushEnrollmentDriver {
561559
keyId: attestation.keyId,
562560
attestation: attestation.attestation,
563561
preparedAt: nowSeconds,
564-
rejectedReplacements: rejectedReplacements
562+
rejectedReplacements: rejected.map { ($0.rejectedReplacements ?? 0) + 1 }
565563
)
566564
// The exact signed request is durable before the first network attempt.
565+
// Saving it is also what replaces a rejected journal.
567566
try store.savePendingEnrollment(pending)
568567
}
569568

@@ -575,12 +574,8 @@ public final class BuzzDevPushEnrollmentDriver {
575574
) {
576575
case .completed(let record):
577576
return record
578-
case .replaced(let count):
579-
return try await enroll(
580-
deviceToken: deviceToken,
581-
relayURL: relayURL,
582-
rejectedReplacements: count
583-
)
577+
case .rejected:
578+
return try await enroll(deviceToken: deviceToken, relayURL: relayURL, replacing: pending)
584579
}
585580
}
586581
return try await completeEnrollment(
@@ -592,8 +587,8 @@ public final class BuzzDevPushEnrollmentDriver {
592587

593588
private enum Resumption {
594589
case completed(BuzzPushEndpointGrantRecord)
595-
/// The journal was discarded; a fresh request carries this rejection count.
596-
case replaced(rejectedReplacements: Int)
590+
/// The gateway terminally rejected the journal, which may now be replaced.
591+
case rejected
597592
}
598593

599594
private func resumeEnrollment(
@@ -615,37 +610,31 @@ public final class BuzzDevPushEnrollmentDriver {
615610
// Only a terminal response permits replacing the old journal with a fresh
616611
// challenge and key. A fresh request's failure propagates instead of
617612
// recursively retrying forever.
618-
try store.removePendingEnrollment(
619-
gatewayOrigin: gatewayOrigin,
620-
relayOrigin: pending.relayOrigin
621-
)
622-
return .replaced(
623-
rejectedReplacements: actual == 404 ? 0 : (pending.rejectedReplacements ?? 0) + 1
624-
)
613+
return .rejected
625614
}
626615
}
627616

628617
/// 404 means the exact replay found no committed installation and its
629-
/// challenge expired. The gateway returns 400 and 401 before looking up a
630-
/// committed installation, so the same bytes can never recover one; those
631-
/// journals are replaced only once old enough, with the wait doubling for
632-
/// each consecutive replacement, because every replacement generates and
633-
/// attests a new App Attest key.
618+
/// challenge is gone. The gateway returns 400 and 401 before looking up a
619+
/// committed installation, so the same bytes can never recover one, even
620+
/// when an earlier attempt committed and its response was lost. Every
621+
/// replacement generates and attests a new App Attest key, so only a first
622+
/// 404 replaces at once. Otherwise the journal must be old enough, with the
623+
/// wait doubling for each consecutive replacement. That bounds new keys when
624+
/// a replacement itself fails, for example with 409 against a live
625+
/// installation for the same token, whose next replay then returns 404.
634626
private func replacesRejectedJournal(
635627
_ pending: BuzzPushPendingEnrollmentRecord,
636628
_ status: Int
637629
) -> Bool {
638-
switch status {
639-
case 404:
630+
guard [400, 401, 404].contains(status) else { return false }
631+
let replacements = pending.rejectedReplacements ?? 0
632+
guard status != 404 || replacements > 0, let preparedAt = pending.preparedAt else {
640633
return true
641-
case 400, 401:
642-
guard let preparedAt = pending.preparedAt else { return true }
643-
let nowSeconds = Int64(now().timeIntervalSince1970)
644-
let doublings = min(pending.rejectedReplacements ?? 0, 20)
645-
return nowSeconds - preparedAt >= Self.rejectedEnrollmentReplacementSeconds << doublings
646-
default:
647-
return false
648634
}
635+
let nowSeconds = Int64(now().timeIntervalSince1970)
636+
let wait = Self.rejectedEnrollmentReplacementSeconds << min(replacements, 20)
637+
return nowSeconds - preparedAt >= wait
649638
}
650639

651640
private func completeEnrollment(

‎mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzDevPushEnrollmentDriverTests.swift‎

Lines changed: 74 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -395,15 +395,21 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase {
395395
func testRejectedEnrollmentReplayIsReplacedOnlyOnTerminalStatus() async throws {
396396
// A journaled request the gateway rejects must not be replayed for its whole
397397
// lifetime, nor replaced (with a fresh App Attest key) on every retry; a
398-
// transient failure must keep the journal.
398+
// transient failure must keep the journal. A fresh 409 models a request that
399+
// committed before its response was lost and was rejected once its
400+
// attestation certificate expired: the replacement conflicts with the live
401+
// installation and its consumed challenge then returns 404.
399402
let interval = BuzzDevPushEnrollmentDriver.rejectedEnrollmentReplacementSeconds
400403
let cases: [(replay: Int, fresh: Int?, elapsed: Int64, legacy: Bool)] = [
401404
(400, 201, interval, false), (401, 201, interval, false), (404, 201, 0, false),
402405
(401, 201, 0, true), (401, nil, interval - 1, false), (401, 401, interval, false),
403-
(503, nil, interval, false),
406+
(401, 409, interval, false), (503, nil, interval, false),
404407
]
405408
for (replayStatus, freshStatus, elapsed, legacy) in cases {
406-
let label = "replay \(replayStatus) after \(elapsed)s, legacy \(legacy)"
409+
let fresh = freshStatus.map(String.init) ?? "none"
410+
let label = "replay \(replayStatus), fresh \(fresh) after \(elapsed)s, legacy \(legacy)"
411+
// Status for a later exact replay of a fresh request.
412+
let freshReplayStatus = freshStatus == 409 ? 404 : freshStatus
407413
let store = MemoryGrantStore()
408414
let appAttest = RecordingAppAttest()
409415
var clock = Self.now
@@ -414,18 +420,27 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase {
414420
lifetimeSeconds: 30 * 86_400
415421
)
416422
var challengeCount = 0
423+
var failChallenge = false
417424
var replayRequests = 0
418425
var freshRequests = 0
426+
var sentChallenges = Set<String>()
419427
URLProtocolStub.handler = { request in
420428
switch (request.httpMethod, request.url?.absoluteString) {
421429
case ("GET", "https://relay.example/"):
422430
return Self.response(request, status: 200, json: [
423431
"push": ["keys": [["pubkey": Self.relayPubkey, "current": true]]]
424432
])
425433
case ("POST", "http://push.example/v1/installations/challenges"):
434+
if failChallenge {
435+
failChallenge = false
436+
throw URLError(.notConnectedToInternet)
437+
}
426438
challengeCount += 1
427439
return Self.response(request, status: 200, json: [
428-
"challenge_id": challengeCount == 1 ? Self.firstChallengeId : Self.secondChallengeId,
440+
"challenge_id": [Self.firstChallengeId, Self.secondChallengeId].indices
441+
.contains(challengeCount - 1)
442+
? [Self.firstChallengeId, Self.secondChallengeId][challengeCount - 1]
443+
: UUID().uuidString.lowercased(),
429444
"challenge": Self.challenge,
430445
"expires_at": clock + 300,
431446
])
@@ -437,7 +452,12 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase {
437452
return Self.response(request, status: replayStatus, json: ["error": "rejected"])
438453
}
439454
freshRequests += 1
440-
let status = try XCTUnwrap(freshStatus, "\(label) must keep the journal")
455+
let challengeId = try XCTUnwrap(body["challenge_id"] as? String)
456+
let isReplay = !sentChallenges.insert(challengeId).inserted
457+
let status = try XCTUnwrap(
458+
isReplay ? freshReplayStatus : freshStatus,
459+
"\(label) must keep the journal"
460+
)
441461
guard status == 201 else {
442462
return Self.response(request, status: status, json: ["error": "rejected"])
443463
}
@@ -469,7 +489,7 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase {
469489
clock += elapsed
470490

471491
// Two retries: the second must not replace a journal again.
472-
for _ in 0..<2 {
492+
for attempt in 0..<2 {
473493
do {
474494
let grant = try await driver.enroll(deviceToken: token, relayURL: Self.relayURL)
475495
XCTAssertEqual(freshStatus, 201, label)
@@ -479,7 +499,11 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase {
479499
route: "v1/installations", _, let actual, _
480500
) {
481501
// The failure stays visible and leaves a durable journal to retry.
482-
XCTAssertEqual(actual, freshStatus ?? replayStatus, label)
502+
XCTAssertEqual(
503+
actual,
504+
(attempt == 0 ? freshStatus : freshReplayStatus) ?? replayStatus,
505+
label
506+
)
483507
XCTAssertEqual(
484508
store.pending.first?.challengeId,
485509
freshStatus == nil ? Self.firstChallengeId : Self.secondChallengeId,
@@ -490,20 +514,51 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase {
490514
XCTAssertEqual(freshRequests, freshStatus == nil ? 0 : freshStatus == 201 ? 1 : 2, label)
491515
XCTAssertEqual(appAttest.preparedAttestations.count, freshStatus == nil ? 1 : 2, label)
492516

493-
guard freshStatus == 401 else { continue }
517+
guard let freshStatus, let freshReplayStatus, freshStatus != 201 else { continue }
494518
// Each consecutive replacement doubles the wait before the next one.
495-
XCTAssertEqual(store.pending.first?.rejectedReplacements, 1)
496-
for (advance, keys) in [(interval, 2), (interval, 3)] {
497-
clock += advance
498-
do {
499-
_ = try await driver.enroll(deviceToken: token, relayURL: Self.relayURL)
500-
XCTFail("Expected the persistent rejection")
501-
} catch BuzzDevPushEnrollmentError.unexpectedStatus(
502-
route: "v1/installations", _, actual: 401, _
503-
) {}
504-
XCTAssertEqual(appAttest.preparedAttestations.count, keys)
519+
XCTAssertEqual(store.pending.first?.rejectedReplacements, 1, label)
520+
clock += interval
521+
await Self.assertEnrollmentStatus(driver, token, freshReplayStatus, label)
522+
XCTAssertEqual(appAttest.preparedAttestations.count, 2, label)
523+
524+
// A replacement that fails before its request is durable keeps the
525+
// rejected journal and its count, even across a driver restart.
526+
clock += interval
527+
failChallenge = true
528+
do {
529+
_ = try await driver.enroll(deviceToken: token, relayURL: Self.relayURL)
530+
XCTFail("Expected the simulated challenge failure: \(label)")
531+
} catch {
532+
XCTAssertEqual((error as NSError).domain, NSURLErrorDomain, label)
505533
}
506-
XCTAssertEqual(store.pending.first?.rejectedReplacements, 2)
534+
XCTAssertEqual(store.pending.first?.rejectedReplacements, 1, label)
535+
let restarted = try makeDriver(
536+
store: store,
537+
appAttest: appAttest,
538+
now: { Date(timeIntervalSince1970: TimeInterval(clock)) },
539+
lifetimeSeconds: 30 * 86_400
540+
)
541+
await Self.assertEnrollmentStatus(restarted, token, freshStatus, label)
542+
XCTAssertEqual(appAttest.preparedAttestations.count, 3, label)
543+
XCTAssertEqual(store.pending.first?.rejectedReplacements, 2, label)
544+
}
545+
}
546+
547+
private static func assertEnrollmentStatus(
548+
_ driver: BuzzDevPushEnrollmentDriver,
549+
_ token: Data,
550+
_ status: Int,
551+
_ label: String
552+
) async {
553+
do {
554+
_ = try await driver.enroll(deviceToken: token, relayURL: relayURL)
555+
XCTFail("Expected gateway status \(status): \(label)")
556+
} catch BuzzDevPushEnrollmentError.unexpectedStatus(
557+
route: "v1/installations", _, let actual, _
558+
) {
559+
XCTAssertEqual(actual, status, label)
560+
} catch {
561+
XCTFail("Unexpected error \(error): \(label)")
507562
}
508563
}
509564

0 commit comments

Comments
 (0)