From b7a0050dac7fd22144363525208e1779000b5740 Mon Sep 17 00:00:00 2001 From: jm Date: Thu, 29 Oct 2026 19:19:26 +0000 Subject: [PATCH 1/7] fix(push): retain gateway revocation targets until cleanup succeeds Signed-off-by: jm Co-authored-by: Codex Signed-off-by: jm --- .../BuzzDevPushEnrollmentDriver.swift | 192 +++++++++- .../BuzzDevPushEnrollmentDriverTests.swift | 319 +++++++++++++++- mobile/ios/Runner/AppDelegate.swift | 51 ++- .../ios/Runner/PushEndpointGrantStore.swift | 10 +- .../shared/community/community_provider.dart | 51 ++- mobile/lib/shared/push/push_bootstrap.dart | 107 +++++- mobile/lib/shared/push/push_bridge.dart | 31 ++ .../push/push_lease_revocation_outbox.dart | 242 +++++++++++- .../settings/notification_recovery_test.dart | 13 + .../settings/notification_toggle_test.dart | 4 +- .../push_lease_revocation_outbox_test.dart | 355 +++++++++++++++++- .../shared/push/push_root_isolation_test.dart | 134 +++++++ 12 files changed, 1476 insertions(+), 33 deletions(-) diff --git a/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzDevPushEnrollmentDriver.swift b/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzDevPushEnrollmentDriver.swift index 4b9d6769299..4d7660f605f 100644 --- a/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzDevPushEnrollmentDriver.swift +++ b/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzDevPushEnrollmentDriver.swift @@ -76,6 +76,10 @@ public protocol BuzzPushEndpointGrantStore { func records() throws -> [BuzzPushEndpointGrantRecord] /// Atomically replaces the grant for its gateway and relay origin. func save(_ record: BuzzPushEndpointGrantRecord) throws + /// Atomically updates all grants affected by one installation mutation. + func replaceAll(_ records: [BuzzPushEndpointGrantRecord]) throws + /// Returns pending operations so cancellation can settle every issuance. + func pendingEnrollments() throws -> [BuzzPushPendingEnrollmentRecord] /// Loads the exact retry journal for a gateway and relay origin. func pendingEnrollment( gatewayOrigin: String, @@ -401,6 +405,134 @@ public final class BuzzDevPushEnrollmentDriver { try store.records().filter { $0.gatewayOrigin == gatewayOrigin } } + /// Returns durable pending requests, including enrollment whose response was lost. + public func pendingEnrollments() throws -> [BuzzPushPendingEnrollmentRecord] { + try store.pendingEnrollments().filter { $0.gatewayOrigin == gatewayOrigin } + } + + /// Settles an interrupted enrollment before revoking its resulting authority. + public func revokePendingDelegation(relayOrigin: String, relayPubkey: String) async throws { + try await settlePendingEnrollments(relayOrigin: relayOrigin, relayPubkey: relayPubkey) + let records = try store.records() + for record in records where record.gatewayOrigin == gatewayOrigin + && record.relayOrigin == relayOrigin && (relayPubkey.isEmpty || record.relayPubkey == relayPubkey) + { + if records.contains(where: { + $0.gatewayOrigin == gatewayOrigin && $0.relayOrigin != relayOrigin + && $0.gatewayInstallationHandle == record.gatewayInstallationHandle + && $0.relayPubkey == record.relayPubkey && !$0.endpointGrant.isEmpty + && $0.expiresAt > Int64(now().timeIntervalSince1970) + }) { continue } + if let handle = record.gatewayInstallationHandle, let installation = UUID(uuidString: handle) { + try await revokeDelegation(installationHandle: installation, keyId: record.appAttestKeyId, + relayPubkey: record.relayPubkey, generation: record.generation) + } + } + } + + private func settlePendingEnrollments(relayOrigin: String? = nil, relayPubkey: String) async throws { + for pending in try pendingEnrollments() where (relayOrigin == nil || pending.relayOrigin == relayOrigin) + && (relayPubkey.isEmpty || pending.relayPubkey == relayPubkey) + { + if pending.expiresAt <= Int64(now().timeIntervalSince1970) { + try await retireReplacedDelegation(relayOrigin: pending.relayOrigin, + installationHandle: pending.gatewayInstallationHandle, relayPubkey: pending.relayPubkey) + try store.removePendingEnrollment(gatewayOrigin: gatewayOrigin, relayOrigin: pending.relayOrigin) + } else { + do { + _ = try await completeEnrollment(pending, storedRecords: store.records(), relayMetadataPubkey: nil) + } catch let error as BuzzDevPushEnrollmentError { + // A 404 rules out the journaled installation, not prior authority + // still retained for this origin. + guard case .unexpectedStatus(route: "v1/installations", _, 404, _) = error else { throw error } + try await retireReplacedDelegation(relayOrigin: pending.relayOrigin, + installationHandle: pending.gatewayInstallationHandle, relayPubkey: pending.relayPubkey) + try store.removePendingEnrollment(gatewayOrigin: gatewayOrigin, relayOrigin: pending.relayOrigin) + } + } + } + } + + /// Revokes one exact delegation without contacting its relay. The caller keeps + /// its cleanup journal until this request and the local save both succeed. + public func revokeDelegation( + installationHandle: UUID, keyId: String, relayPubkey: String, generation: Int64, + settlePending: Bool = false + ) async throws { + if settlePending { + let handle = installationHandle.uuidString.lowercased() + let origins = Set(try store.records().filter { + $0.gatewayOrigin == gatewayOrigin && $0.gatewayInstallationHandle == handle + && $0.relayPubkey == relayPubkey + }.map(\.relayOrigin)).union(try pendingEnrollments().filter { + $0.gatewayInstallationHandle == handle && $0.relayPubkey == relayPubkey + }.map(\.relayOrigin)) + for origin in origins { + try await settlePendingEnrollments(relayOrigin: origin, relayPubkey: relayPubkey) + } + var includedOriginal = false + let records = try store.records() + for record in records where record.gatewayOrigin == gatewayOrigin + && record.relayPubkey == relayPubkey + { + if record.gatewayInstallationHandle != handle { + guard origins.contains(record.relayOrigin), !records.contains(where: { + $0.gatewayOrigin == gatewayOrigin && !origins.contains($0.relayOrigin) + && $0.gatewayInstallationHandle == record.gatewayInstallationHandle + && $0.relayPubkey == relayPubkey && !$0.endpointGrant.isEmpty + && $0.expiresAt > Int64(now().timeIntervalSince1970) + }) else { continue } + } + if let handle = record.gatewayInstallationHandle, let installation = UUID(uuidString: handle) { + if installation == installationHandle { includedOriginal = true } + try await revokeDelegation(installationHandle: installation, keyId: record.appAttestKeyId, + relayPubkey: relayPubkey, generation: record.generation) + } + } + if !includedOriginal { + try await revokeDelegation(installationHandle: installationHandle, keyId: keyId, + relayPubkey: relayPubkey, generation: generation) + } + return + } + let matching = try store.records().filter { + $0.gatewayOrigin == gatewayOrigin + && $0.gatewayInstallationHandle == installationHandle.uuidString.lowercased() + && $0.relayPubkey == relayPubkey + } + if !matching.isEmpty && matching.allSatisfy({ $0.expiresAt <= Int64(now().timeIntervalSince1970) }) { return } + if try store.records().contains(where: { + $0.gatewayOrigin == gatewayOrigin + && $0.gatewayInstallationHandle == installationHandle.uuidString.lowercased() + && $0.relayPubkey == relayPubkey && $0.generation > generation + }) { return } + try store.replaceAll(store.records().map { record in + guard record.gatewayOrigin == gatewayOrigin + && record.gatewayInstallationHandle == installationHandle.uuidString.lowercased() + && record.relayPubkey == relayPubkey && record.generation == generation + else { return record } + // Keep the version/lifetime but stop local reuse before awaiting network. + return record.with(endpointGrant: "") + }) + let requestExpiresAt = Int64(now().timeIntervalSince1970) + Self.managementRequestLifetimeSeconds + let clientData = try BuzzPushTranscript.revokeDelegation( + gatewayOrigin: gatewayBaseURL, requestExpiresAt: requestExpiresAt, + installationHandle: installationHandle, relayPubkey: relayPubkey, generation: generation + ) + let assertion = try await appAttest.assertion(keyId: keyId, clientData: clientData) + let response: MutationResponse = try await post( + route: "v1/delegations/revoke", expectedStatus: 200, + body: RevokeDelegationRequest( + v: 2, gatewayOrigin: gatewayOrigin, requestExpiresAt: requestExpiresAt, + installationHandle: installationHandle.uuidString.lowercased(), + relayPubkey: relayPubkey, generation: generation, assertion: assertion + ) + ) + guard response.status == "revoked" else { + throw BuzzDevPushEnrollmentError.invalidResponse(route: "v1/delegations/revoke") + } + } + /// Fetches the relay's current NIP-11 push key, enrolls the APNs endpoint, /// delegates to that key, and durably saves the resulting opaque grant. public func enroll( @@ -458,6 +590,8 @@ public final class BuzzDevPushEnrollmentDriver { ) } } else { + try await retireReplacedDelegation(relayOrigin: pending.relayOrigin, + installationHandle: pending.gatewayInstallationHandle, relayPubkey: pending.relayPubkey) try store.removePendingEnrollment( gatewayOrigin: gatewayOrigin, relayOrigin: relayOrigin.text @@ -468,7 +602,7 @@ public final class BuzzDevPushEnrollmentDriver { let newestSharedGrant = storedRecords.filter { $0.gatewayOrigin == gatewayOrigin && $0.relayPubkey == relayPubkey && $0.endpointHash == endpointHash && $0.endpointEpoch == Self.endpointEpoch - && $0.expiresAt > nowSeconds + 300 + && $0.expiresAt > nowSeconds + 300 && !$0.endpointGrant.isEmpty }.max { $0.generation < $1.generation } if pendingEnrollment == nil, let reusableGrant = newestSharedGrant { // Reuse the newest delegation without invalidating sibling communities. @@ -486,6 +620,8 @@ public final class BuzzDevPushEnrollmentDriver { generation: reusableGrant.generation, expiresAt: reusableGrant.expiresAt ) + try await retireReplacedDelegation(relayOrigin: record.relayOrigin, + installationHandle: record.gatewayInstallationHandle, relayPubkey: record.relayPubkey) try store.save(record) try store.removePendingEnrollment( gatewayOrigin: gatewayOrigin, @@ -849,6 +985,8 @@ public final class BuzzDevPushEnrollmentDriver { generation: generation, expiresAt: pending.expiresAt ) + try await retireReplacedDelegation(relayOrigin: record.relayOrigin, + installationHandle: record.gatewayInstallationHandle, relayPubkey: record.relayPubkey) try store.save(record) try store.removePendingEnrollment( gatewayOrigin: gatewayOrigin, @@ -857,6 +995,26 @@ public final class BuzzDevPushEnrollmentDriver { return record } + private func retireReplacedDelegation( + relayOrigin: String, installationHandle: String?, relayPubkey: String + ) async throws { + let records = try store.records() + guard let old = records.first(where: { + $0.gatewayOrigin == gatewayOrigin && $0.relayOrigin == relayOrigin + }), old.gatewayInstallationHandle != installationHandle || old.relayPubkey != relayPubkey, + let handle = old.gatewayInstallationHandle, let installation = UUID(uuidString: handle) + else { return } + guard !records.contains(where: { + $0.gatewayOrigin == old.gatewayOrigin && $0.relayOrigin != old.relayOrigin + && $0.gatewayInstallationHandle == handle && $0.relayPubkey == old.relayPubkey + && $0.expiresAt > Int64(now().timeIntervalSince1970) && !$0.endpointGrant.isEmpty + }) else { return } + // Keep the old target durable until its revocation succeeds; replacing the + // origin record first would lose it even if the new issuance is journaled. + try await revokeDelegation(installationHandle: installation, keyId: old.appAttestKeyId, + relayPubkey: old.relayPubkey, generation: old.generation) + } + private func makeInstallationId() throws -> String { let bytes = try installationIdBytes() precondition( @@ -1227,3 +1385,35 @@ private struct DelegationConflict: Decodable { case currentGeneration = "current_generation" } } + +private struct RevokeDelegationRequest: Encodable { + let v: Int + let gatewayOrigin: String + let requestExpiresAt: Int64 + let installationHandle: String + let relayPubkey: String + let generation: Int64 + let assertion: String + enum CodingKeys: String, CodingKey { + case v + case gatewayOrigin = "gateway_origin" + case requestExpiresAt = "request_expires_at" + case installationHandle = "installation_handle" + case relayPubkey = "relay_pubkey" + case generation, assertion + } +} +private struct MutationResponse: Decodable { let status: String } + + +private extension BuzzPushEndpointGrantRecord { + func with(endpointGrant: String) -> Self { + Self( + gatewayOrigin: gatewayOrigin, relayOrigin: relayOrigin, relayPubkey: relayPubkey, + relayMetadataPubkey: relayMetadataPubkey, gatewayInstallationHandle: gatewayInstallationHandle, + appAttestKeyId: appAttestKeyId, installationId: installationId, + endpointGrant: endpointGrant, endpointHash: endpointHash, + endpointEpoch: endpointEpoch, generation: generation, expiresAt: expiresAt + ) + } +} diff --git a/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzDevPushEnrollmentDriverTests.swift b/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzDevPushEnrollmentDriverTests.swift index 13ba2d8b8b1..c9e8465d171 100644 --- a/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzDevPushEnrollmentDriverTests.swift +++ b/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzDevPushEnrollmentDriverTests.swift @@ -393,11 +393,13 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase { func testResponseLostEnrollmentSurvivesTokenRotationAndAnotherReplayFailure() async throws { let store = MemoryGrantStore() - let driver = try makeDriver(store: store, appAttest: RecordingAppAttest()) + let appAttest = RecordingAppAttest() + let driver = try makeDriver(store: store, appAttest: appAttest) let rotatedToken = Data(repeating: 42, count: 32) let rotatedHandle = "44444444-4444-4444-8444-444444444444" var oldRequests = 0 var newRequests = 0 + var retirements = 0 var firstBody: [String: Any]? var delegatedHandles: [String] = [] URLProtocolStub.handler = { request in @@ -437,8 +439,17 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase { let handle = try XCTUnwrap(Self.body(request)["installation_handle"] as? String) delegatedHandles.append(handle) return Self.response(request, status: 201, json: ["endpoint_grant": "grant-\(handle)"]) + case ("POST", "http://push.example/v1/delegations/revoke"): + let body = try Self.body(request) + XCTAssertEqual(body["installation_handle"] as? String, Self.installationHandle) + XCTAssertEqual(appAttest.assertionKeyIds.last, Self.keyId) + XCTAssertEqual(body["relay_pubkey"] as? String, Self.relayPubkey) + XCTAssertEqual(body["generation"] as? Int64, 1) + XCTAssertEqual(body["request_expires_at"] as? Int64, Self.now + 240) + retirements += 1 + return Self.response(request, status: 200, json: ["status": "revoked"]) default: - XCTFail("Unexpected request, including any migration/revocation route: \(request.url!)") + XCTFail("Unexpected request \(request.url!)") return Self.response(request, status: 500, json: [:]) } } @@ -456,6 +467,7 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase { let grant = try await driver.enroll(deviceToken: rotatedToken, relayURL: Self.relayURL) XCTAssertEqual(oldRequests, 3) XCTAssertEqual(newRequests, 1) + XCTAssertEqual(retirements, 1) XCTAssertEqual(delegatedHandles, [Self.installationHandle, rotatedHandle]) XCTAssertEqual(grant.endpointHash, Self.hex(SHA256.hash(data: rotatedToken))) XCTAssertTrue(store.pending.isEmpty) @@ -1378,6 +1390,309 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase { } } + func testDirectRevocationRetriesWithoutChallengeAndPreventsLocalGrantReuse() async throws { + let store = MemoryGrantStore(records: [BuzzPushEndpointGrantRecord( + gatewayOrigin: Self.gatewayOrigin, relayOrigin: "wss://relay.example", + relayPubkey: Self.relayPubkey, gatewayInstallationHandle: Self.installationHandle, + appAttestKeyId: Self.keyId, installationId: Self.installationId, + endpointGrant: "old-opaque-grant", endpointHash: Self.hex(SHA256.hash(data: Data((1...32).map(UInt8.init)))), + endpointEpoch: 1, generation: 1, expiresAt: Self.expiresAt + )]) + let appAttest = RecordingAppAttest() + let driver = try makeDriver(store: store, appAttest: appAttest) + var requests = 0 + URLProtocolStub.handler = { request in + XCTAssertEqual(request.url?.path, "/v1/delegations/revoke") + let body = try Self.body(request) + XCTAssertEqual(body["v"] as? Int, 2) + XCTAssertNil(body["challenge"]) + XCTAssertEqual(body["request_expires_at"] as? Int64, Self.now + 240) + XCTAssertEqual(body["generation"] as? Int, 1) + XCTAssertEqual(store.saved.first?.endpointGrant, "") + requests += 1 + if requests == 1 { throw URLError(.networkConnectionLost) } + return Self.response(request, status: 200, json: ["status":"revoked"]) + } + do { + try await driver.revokeDelegation(installationHandle: UUID(uuidString: Self.installationHandle)!, keyId: Self.keyId, relayPubkey: Self.relayPubkey, generation: 1) + XCTFail("Expected lost revocation response") + } catch { XCTAssertEqual((error as NSError).domain, NSURLErrorDomain) } + try await driver.revokeDelegation(installationHandle: UUID(uuidString: Self.installationHandle)!, keyId: Self.keyId, relayPubkey: Self.relayPubkey, generation: 1) + XCTAssertEqual(requests, 2) + XCTAssertEqual(store.saved.first?.endpointGrant, "") + XCTAssertEqual(store.saved.first?.generation, 1) + XCTAssertEqual(store.saved.first?.expiresAt, Self.expiresAt) + } + + func testCanceledFirstEnrollmentSettlesLostInstallationResponseThenRevokes() async throws { + let store = MemoryGrantStore(pending: [BuzzPushPendingEnrollmentRecord( + gatewayOrigin: Self.gatewayOrigin, relayOrigin: "wss://relay.example", relayPubkey: Self.relayPubkey, + endpoint: Self.endpoint, endpointHash: Self.hex(SHA256.hash(data: Data((1...32).map(UInt8.init)))), + expiresAt: Self.expiresAt, installationId: Self.installationId, + challengeId: Self.firstChallengeId, challenge: Self.challenge, keyId: Self.keyId, attestation: Self.attestation)]) + let driver = try makeDriver(store: store, appAttest: RecordingAppAttest()) + var paths: [String] = [] + URLProtocolStub.handler = { request in + let path = request.url!.path + paths.append(path) + switch path { + case "/v1/installations": + return Self.response(request, status: 201, json: ["installation_handle":Self.installationHandle,"endpoint_epoch":1,"expires_at":Self.expiresAt]) + case "/v1/delegations": + return Self.response(request, status: 201, json: ["endpoint_grant":"reissued-grant"]) + case "/v1/delegations/revoke": + XCTAssertEqual(try Self.body(request)["generation"] as? Int, 1) + return Self.response(request, status: 200, json: ["status":"revoked"]) + default: + XCTFail("Unexpected request \(path)") + return Self.response(request, status: 500, json: [:]) + } + } + try await driver.revokePendingDelegation(relayOrigin: "wss://relay.example", relayPubkey: "") + XCTAssertEqual(paths, ["/v1/installations", "/v1/delegations", "/v1/delegations/revoke"]) + XCTAssertTrue(store.pending.isEmpty) + XCTAssertEqual(store.saved.first?.endpointGrant, "") + } + + func testCancellationSettlesLostRenewalAndRevokesItsNewerAuthority() async throws { + let endpointHash = Self.hex(SHA256.hash(data: Data((1...32).map(UInt8.init)))) + let store = MemoryGrantStore(records: [BuzzPushEndpointGrantRecord( + gatewayOrigin: Self.gatewayOrigin, relayOrigin: "wss://relay.example", relayPubkey: Self.relayPubkey, + gatewayInstallationHandle: Self.installationHandle, appAttestKeyId: Self.keyId, + installationId: Self.installationId, endpointGrant: "old-grant", endpointHash: endpointHash, + endpointEpoch: 1, generation: 1, expiresAt: Self.now + 10 + )], pending: [BuzzPushPendingEnrollmentRecord( + gatewayOrigin: Self.gatewayOrigin, relayOrigin: "wss://relay.example", relayPubkey: Self.relayPubkey, + endpoint: Self.endpoint, endpointHash: endpointHash, expiresAt: Self.expiresAt, + installationId: Self.installationId, gatewayInstallationHandle: Self.installationHandle, + keyId: Self.keyId, delegationGeneration: 2, expectedDelegationGeneration: 1 + )]) + let driver = try makeDriver(store: store, appAttest: RecordingAppAttest()) + var current: Int64 = 2 + var revoked: [Int64] = [] + URLProtocolStub.handler = { request in + let body = try Self.body(request) + switch request.url?.path { + case "/v1/delegations": + let expected = try XCTUnwrap(body["expected_generation"] as? Int64) + if expected != current { + return Self.response(request, status: 409, json: ["error":"stale_generation","current_generation":current]) + } + current = try XCTUnwrap(body["generation"] as? Int64) + return Self.response(request, status: 201, json: ["endpoint_grant":"replacement-grant"]) + case "/v1/delegations/revoke": + let generation = try XCTUnwrap(body["generation"] as? Int64) + XCTAssertEqual(generation, current) + revoked.append(generation) + return Self.response(request, status: 200, json: ["status":"revoked"]) + default: + XCTFail("Unexpected request \(request.url!)") + return Self.response(request, status: 500, json: [:]) + } + } + try await driver.revokeDelegation(installationHandle: UUID(uuidString: Self.installationHandle)!, + keyId: Self.keyId, relayPubkey: Self.relayPubkey, generation: 1, settlePending: true) + XCTAssertEqual(revoked, [4]) + XCTAssertTrue(store.pending.isEmpty) + XCTAssertEqual(store.saved.first?.generation, 4) + XCTAssertEqual(store.saved.first?.endpointGrant, "") + XCTAssertEqual(store.saved.first?.expiresAt, Self.expiresAt) + } + + func testReplacementRetiresExactPriorAuthorityBeforeLosingItsRecord() async throws { + let token = Data((1...32).map(UInt8.init)) + let endpointHash = Self.hex(SHA256.hash(data: token)) + let currentHandle = "44444444-4444-4444-8444-444444444444" + let currentKeyId = Data(repeating: 0xBB, count: 32).base64EncodedString() + for (oldEpoch, outcome) in [ + (Int64(1), "success"), (3, "success"), (1, "revocation failure"), + (1, "revocation response loss"), (1, "issuance response loss"), + (1, "shared"), (1, "cached"), (1, "cached revocation failure"), + (1, "expired cleanup failure"), (1, "expired enrollment failure"), + (1, "expired shared cleanup failure"), + ] { + let discardingJournal = outcome.hasPrefix("expired") + let cached = outcome.hasPrefix("cached") || outcome == "shared" + let old = BuzzPushEndpointGrantRecord( + gatewayOrigin: Self.gatewayOrigin, relayOrigin: "wss://relay.example", + relayPubkey: discardingJournal ? String(repeating: "c", count: 64) : Self.relayPubkey, + gatewayInstallationHandle: Self.installationHandle, + appAttestKeyId: Self.keyId, installationId: Self.installationId, + endpointGrant: "old-token-grant", endpointHash: "old-token-hash", + endpointEpoch: oldEpoch, generation: 7, + expiresAt: discardingJournal ? Self.now + 3600 : Self.expiresAt) + let current = BuzzPushEndpointGrantRecord( + gatewayOrigin: Self.gatewayOrigin, relayOrigin: "wss://other.example", + relayPubkey: cached ? Self.relayPubkey : String(repeating: "b", count: 64), + gatewayInstallationHandle: currentHandle, + appAttestKeyId: currentKeyId, installationId: String(repeating: "f", count: 32), + endpointGrant: "current-token-grant", endpointHash: endpointHash, + endpointEpoch: 1, generation: 1, + expiresAt: discardingJournal ? Self.now + 360 : Self.expiresAt) + let shared = BuzzPushEndpointGrantRecord( + gatewayOrigin: old.gatewayOrigin, relayOrigin: "wss://shared.example", + relayPubkey: old.relayPubkey, gatewayInstallationHandle: old.gatewayInstallationHandle, + appAttestKeyId: old.appAttestKeyId, installationId: String(repeating: "e", count: 32), + endpointGrant: old.endpointGrant, endpointHash: old.endpointHash, + endpointEpoch: old.endpointEpoch, generation: old.generation, expiresAt: old.expiresAt) + // MemoryGrantStore.save matches Keychain's gateway+origin replacement, + // so the old target is lost if retirement happens after save. + var store = MemoryGrantStore(records: [old, current] + (outcome == "shared" ? [shared] : [])) + let appAttest = RecordingAppAttest() + var clock = Self.now + var driver = try makeDriver(store: store, appAttest: appAttest, + now: { Date(timeIntervalSince1970: TimeInterval(clock)) }) + var generation: Int64 = cached ? 1 : 0 + var revocations = 0 + URLProtocolStub.handler = { request in + switch (request.httpMethod, request.url?.path) { + case ("GET", "/"): + return Self.response(request, status: 200, + json: ["push": ["keys": [["pubkey": Self.relayPubkey, "current": true]]]]) + case ("POST", "/v1/delegations"): + XCTAssertTrue(!cached || outcome == "shared") + let body = try Self.body(request) + XCTAssertEqual(body["installation_handle"] as? String, currentHandle) + XCTAssertEqual(body["endpoint_epoch"] as? Int, 1) + XCTAssertEqual(store.pending.first?.gatewayInstallationHandle, currentHandle) + let expected = try XCTUnwrap(body["expected_generation"] as? Int64) + if expected != generation { + return Self.response(request, status: 409, + json: ["error": "stale_generation", "current_generation": generation]) + } + let next = try XCTUnwrap(body["generation"] as? Int64) + XCTAssertGreaterThan(next, generation) + generation = next + if outcome == "issuance response loss" && generation == 1 { + throw URLError(.networkConnectionLost) + } + return Self.response(request, status: 201, json: ["endpoint_grant": "renewed-grant"]) + case ("POST", "/v1/delegations/revoke"): + revocations += 1 + let body = try Self.body(request) + XCTAssertEqual(body["installation_handle"] as? String, old.gatewayInstallationHandle) + XCTAssertEqual(body["relay_pubkey"] as? String, old.relayPubkey) + XCTAssertEqual(body["generation"] as? Int64, old.generation) + XCTAssertEqual(appAttest.assertionKeyIds.last, old.appAttestKeyId) + let retained = try XCTUnwrap(store.saved.first { + $0.gatewayInstallationHandle == old.gatewayInstallationHandle && $0.relayPubkey == old.relayPubkey + }) + XCTAssertEqual(retained.gatewayInstallationHandle, old.gatewayInstallationHandle) + XCTAssertEqual(retained.generation, old.generation) + XCTAssertEqual(retained.endpointGrant, "") + if outcome != "shared" { XCTAssertEqual(store.pending.isEmpty, cached) } + if revocations <= (discardingJournal ? 2 : 1) + && (discardingJournal || outcome.contains("revocation failure")) + { + return Self.response(request, status: 503, json: [:]) + } + if revocations == 1 && outcome == "revocation response loss" { + throw URLError(.networkConnectionLost) + } + return Self.response(request, status: 200, json: ["status": "revoked"]) + default: + XCTFail("The current token already has an installation; must not rotate or enroll") + return Self.response(request, status: 409, json: ["error": "endpoint_in_use"]) + } + } + + if outcome.contains("failure") || outcome.contains("loss") { + do { + _ = try await driver.enroll(deviceToken: token, relayURL: Self.relayURL) + XCTFail("Expected failure before replacing the old target: \(outcome)") + } catch { + XCTAssertEqual(store.saved.first?.gatewayInstallationHandle, old.gatewayInstallationHandle) + XCTAssertEqual(store.pending.isEmpty, cached) + } + // Restart from only Codable durable state, including the old target and + // the new issuance journal. A committed response loss needs a fresh grant. + store = MemoryGrantStore( + records: try JSONDecoder().decode([BuzzPushEndpointGrantRecord].self, + from: JSONEncoder().encode(store.saved)), + pending: try JSONDecoder().decode([BuzzPushPendingEnrollmentRecord].self, + from: JSONEncoder().encode(store.pending))) + driver = try makeDriver(store: store, appAttest: appAttest, + now: { Date(timeIntervalSince1970: TimeInterval(clock)) }) + } + if discardingJournal { + let journal = try XCTUnwrap(store.pending.first) + XCTAssertEqual(journal.expiresAt, Self.now + 360) + XCTAssertNotEqual(journal.relayPubkey, old.relayPubkey) + clock = Self.now + 361 + XCTAssertGreaterThan(old.expiresAt, clock) + if outcome.contains("shared") { + try store.save(shared) + try await driver.revokePendingDelegation(relayOrigin: old.relayOrigin, + relayPubkey: journal.relayPubkey) + XCTAssertEqual(revocations, 1, "Only a positive old owner permits skipping retirement") + XCTAssertTrue(store.saved.contains(shared)) + } else { + do { + if outcome.contains("enrollment") { + _ = try await driver.enroll(deviceToken: token, relayURL: Self.relayURL) + } else { + try await driver.revokePendingDelegation(relayOrigin: old.relayOrigin, + relayPubkey: journal.relayPubkey) + } + XCTFail("Failed retirement must retain the replacement journal") + } catch BuzzDevPushEnrollmentError.unexpectedStatus( + route: "v1/delegations/revoke", _, 503, _ + ) {} + XCTAssertEqual(revocations, 2) + XCTAssertEqual(store.pending, [journal]) + XCTAssertEqual(store.saved.first?.gatewayInstallationHandle, old.gatewayInstallationHandle) + XCTAssertEqual(store.saved.first?.relayPubkey, old.relayPubkey) + XCTAssertEqual(store.saved.first?.endpointGrant, "") + try await driver.revokePendingDelegation(relayOrigin: old.relayOrigin, + relayPubkey: journal.relayPubkey) + XCTAssertEqual(revocations, 3) + } + XCTAssertTrue(store.pending.isEmpty) + continue + } + let record = try await driver.enroll(deviceToken: token, relayURL: Self.relayURL) + + XCTAssertEqual(record.gatewayInstallationHandle, currentHandle) + XCTAssertEqual(record.installationId, old.installationId) + XCTAssertEqual(record.endpointEpoch, 1) + XCTAssertEqual(record.endpointHash, endpointHash) + XCTAssertEqual(record.endpointGrant, cached ? current.endpointGrant : "renewed-grant") + XCTAssertEqual(revocations, outcome == "shared" ? 0 : (outcome.contains("revocation") ? 2 : 1)) + XCTAssertEqual(store.saved.first { $0.relayOrigin == old.relayOrigin }, record) + XCTAssertFalse(store.saved.contains(old)) + XCTAssertTrue(store.pending.isEmpty) + XCTAssertTrue(store.saved.contains(current)) + if outcome == "shared" { + XCTAssertTrue(store.saved.contains(shared)) + // Removing the last old origin must leave the new installation and its + // same-signer pending renewal untouched. + let unrelatedPending = BuzzPushPendingEnrollmentRecord( + gatewayOrigin: Self.gatewayOrigin, relayOrigin: record.relayOrigin, + relayPubkey: record.relayPubkey, endpoint: Self.endpoint, endpointHash: endpointHash, + expiresAt: Self.expiresAt, installationId: record.installationId, + gatewayInstallationHandle: currentHandle, keyId: currentKeyId, + delegationGeneration: 2, expectedDelegationGeneration: record.generation) + try store.savePendingEnrollment(unrelatedPending) + try await driver.revokeDelegation(installationHandle: UUID(uuidString: Self.installationHandle)!, + keyId: old.appAttestKeyId, relayPubkey: old.relayPubkey, generation: old.generation, + settlePending: true) + XCTAssertEqual(revocations, 1) + XCTAssertTrue(store.saved.contains(record)) + XCTAssertTrue(store.saved.contains(current)) + XCTAssertEqual(store.pending, [unrelatedPending]) + try await driver.revokePendingDelegation(relayOrigin: record.relayOrigin, + relayPubkey: record.relayPubkey) + XCTAssertEqual(revocations, 1, "A recovered shared installation must not be revoked") + XCTAssertTrue(store.saved.contains(current)) + XCTAssertTrue(store.pending.isEmpty) + let recovered = try XCTUnwrap(store.saved.first { $0.relayOrigin == record.relayOrigin }) + XCTAssertEqual(recovered.gatewayInstallationHandle, currentHandle) + XCTAssertGreaterThan(recovered.generation, record.generation) + XCTAssertFalse(recovered.endpointGrant.isEmpty) + } + } + } + private func makeDriver( gatewayBaseURL: URL = BuzzDevPushEnrollmentDriverTests.gatewayURL, store: BuzzPushEndpointGrantStore, diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift index 9a49b26dbe4..bc9cdcbda42 100644 --- a/mobile/ios/Runner/AppDelegate.swift +++ b/mobile/ios/Runner/AppDelegate.swift @@ -591,7 +591,18 @@ import os.log store: endpointGrantStore, appAttestKeychainAccessGroup: pushKeychainAccessGroup ) - result(try driver.endpointGrants().map(\.flutterArguments)) + var grants = try driver.endpointGrants().map(\.flutterArguments) + for pending in try driver.pendingEnrollments() { + grants.removeAll { $0["relayOrigin"] as? String == pending.relayOrigin } + grants.append([ + "relayOrigin": pending.relayOrigin, "relayPubkey": pending.relayPubkey, + "installationId": pending.installationId, "endpointGrant": "", + "endpointHash": pending.endpointHash, "endpointEpoch": 1, + "generation": max(1, pending.delegationGeneration), "expiresAt": pending.expiresAt, + "pending": true, + ]) + } + result(grants) } catch { result( FlutterError( @@ -601,6 +612,44 @@ import os.log ) ) } + case "revokePushDelegation": + guard enrollmentTask == nil, + let arguments = call.arguments as? [String: Any], + let gatewayText = arguments["gatewayUrl"] as? String, + let gatewayURL = URL(string: gatewayText), + let relayPubkey = arguments["relayPubkey"] as? String, + let generation = arguments["generation"] as? Int64, generation > 0 + else { + result(FlutterError(code: "push_management_busy_or_invalid", message: "Push management is busy or invalid.", details: nil)) + return + } + do { + let driver = try BuzzDevPushEnrollmentDriver( + gatewayBaseURL: gatewayURL, store: endpointGrantStore, + appAttestKeychainAccessGroup: pushKeychainAccessGroup + ) + enrollmentTask = Task { [weak self] in + defer { self?.enrollmentTask = nil } + do { + if let handle = arguments["installationHandle"] as? String, + let installation = UUID(uuidString: handle), let keyId = arguments["keyId"] as? String { + try await driver.revokeDelegation( + installationHandle: installation, keyId: keyId, + relayPubkey: relayPubkey, generation: generation, settlePending: true + ) + } else if let relayOrigin = arguments["relayOrigin"] as? String { + try await driver.revokePendingDelegation(relayOrigin: relayOrigin, relayPubkey: relayPubkey) + } else { throw BuzzDevPushEnrollmentError.invalidRelayURL } + await MainActor.run { result(nil) } + } catch { + await MainActor.run { + result(FlutterError(code: "push_revocation_failed", message: "Push revocation failed.", details: error.localizedDescription)) + } + } + } + } catch { + result(FlutterError(code: "push_revocation_failed", message: "Push revocation failed.", details: error.localizedDescription)) + } case "enrollPush": handleDevPushEnrollment(call, result: result) default: diff --git a/mobile/ios/Runner/PushEndpointGrantStore.swift b/mobile/ios/Runner/PushEndpointGrantStore.swift index c4c80c1298b..24ee829d18b 100644 --- a/mobile/ios/Runner/PushEndpointGrantStore.swift +++ b/mobile/ios/Runner/PushEndpointGrantStore.swift @@ -45,6 +45,10 @@ final class BuzzPushEndpointGrantKeychainStore: BuzzPushEndpointGrantStore { try replaceValue(all, account: Self.recordsAccount) } + func replaceAll(_ records: [BuzzPushEndpointGrantRecord]) throws { + try replaceValue(records, account: Self.recordsAccount) + } + func pendingEnrollment( gatewayOrigin: String, relayOrigin: String @@ -74,7 +78,7 @@ final class BuzzPushEndpointGrantKeychainStore: BuzzPushEndpointGrantStore { try replaceValue(all, account: Self.pendingAccount) } - private func pendingEnrollments() throws -> [BuzzPushPendingEnrollmentRecord] { + func pendingEnrollments() throws -> [BuzzPushPendingEnrollmentRecord] { var query = baseQuery(account: Self.pendingAccount) query[kSecReturnData as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne @@ -141,7 +145,8 @@ final class BuzzPushEndpointGrantKeychainStore: BuzzPushEndpointGrantStore { extension BuzzPushEndpointGrantRecord { var flutterArguments: [String: Any] { - let arguments: [String: Any] = [ + var arguments: [String: Any] = [ + "appAttestKeyId": appAttestKeyId, "relayOrigin": relayOrigin, "relayPubkey": relayPubkey, "installationId": installationId, @@ -151,6 +156,7 @@ extension BuzzPushEndpointGrantRecord { "generation": generation, "expiresAt": expiresAt, ] + if let gatewayInstallationHandle { arguments["gatewayInstallationHandle"] = gatewayInstallationHandle } return arguments } } diff --git a/mobile/lib/shared/community/community_provider.dart b/mobile/lib/shared/community/community_provider.dart index aa77de1d037..6e28f3a78f8 100644 --- a/mobile/lib/shared/community/community_provider.dart +++ b/mobile/lib/shared/community/community_provider.dart @@ -1,4 +1,5 @@ import '../hosted/hosted_relay_auth.dart'; + import 'dart:async'; import 'dart:developer' as developer; import 'dart:math'; @@ -110,7 +111,11 @@ typedef CommunityPushLeaseRevocationEnqueuer = final communityPushLeaseRevocationEnqueuerProvider = Provider((ref) { - return ref.watch(buzzPushLeaseRevocationOutboxProvider).enqueueCommunity; + final outbox = ref.watch(buzzPushLeaseRevocationOutboxProvider); + return (community) => outbox.enqueueCommunity( + community, + remainingCommunities: ref.read(communityListProvider).value ?? const [], + ); }); typedef CommunityPushLeaseRevocationTrigger = Future Function(); @@ -509,6 +514,7 @@ class CommunityListNotifier extends AsyncNotifier> { Future setPushNotificationsEnabled(String id, bool enabled) async { var shouldDeactivate = false; + var gatewayCleanupJournaled = false; await _serializePushMutation(() async { final storage = ref.read(communityStorageProvider); final current = state.value ?? await storage.loadAll(); @@ -529,6 +535,11 @@ class CommunityListNotifier extends AsyncNotifier> { pushNotificationsEnabled: enabled, pushSubscriptionState: pushState, ); + if (!enabled && pushState.pendingTombstoneGeneration == null) { + gatewayCleanupJournaled = await ref.read( + communityPushLeaseRevocationEnqueuerProvider, + )(updated); + } await storage.save(updated); final updatedList = [...current]..[index] = updated; state = AsyncData(updatedList); @@ -536,6 +547,9 @@ class CommunityListNotifier extends AsyncNotifier> { shouldDeactivate = !enabled && pushState.pendingTombstoneGeneration != null; }); + if (gatewayCleanupJournaled) { + unawaited(ref.read(communityPushLeaseRevocationTriggerProvider)()); + } if (shouldDeactivate) { try { await retryPendingPushLeaseTombstone(id); @@ -608,6 +622,41 @@ class CommunityListNotifier extends AsyncNotifier> { final generation = pendingGeneration; if (community == null || generation == null) return; try { + final grants = await readBuzzPushEndpointGrants(); + final matching = grants.where( + (grant) => + grant.relayOrigin == + canonicalBuzzPushRelayOrigin(community.relayUrl), + ); + if (matching.length == 1) { + final grant = matching.single; + final target = grant.gatewayRevocationTarget; + final current = + state.value ?? await ref.read(communityStorageProvider).loadAll(); + final pending = current.where((candidate) => candidate.id == id); + if (pending.isEmpty || + pending.single.pushNotificationsEnabled || + pending.single.pushSubscriptionState.pendingTombstoneGeneration != + generation) { + return; + } + final shared = current.any( + (other) => + other.id != id && + other.pushNotificationsEnabled && + grants.any( + (candidate) => + candidate.relayOrigin == + canonicalBuzzPushRelayOrigin(other.relayUrl) && + candidate.relayPubkey == grant.relayPubkey && + (grant.pending + ? candidate.relayOrigin == grant.relayOrigin + : candidate.gatewayInstallationHandle == + grant.gatewayInstallationHandle), + ), + ); + if (!shared && target != null) await revokeBuzzPushDelegation(target); + } await ref.read(communityPushLeaseDeactivatorProvider)( community, generation: generation, diff --git a/mobile/lib/shared/push/push_bootstrap.dart b/mobile/lib/shared/push/push_bootstrap.dart index 8cb405ce624..a43165a2ca0 100644 --- a/mobile/lib/shared/push/push_bootstrap.dart +++ b/mobile/lib/shared/push/push_bootstrap.dart @@ -270,8 +270,13 @@ class _BuzzPushLifecycle extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { useListenable(apnsDeviceToken); + useListenable(pushEndpointGrants); final publicationAttempt = useMemoized(BuzzPushAttemptGate.new); final tombstoneAttempt = useMemoized(BuzzPushAttemptGate.new); + final otherOriginsAttempt = useMemoized(BuzzPushAttemptGate.new); + final otherOriginsBusy = useRef(false); + final latestOtherOriginsAttempt = useRef(''); + final otherOriginsRetry = useState(0); final publicationRetry = useState(0); final tombstoneRetry = useState(0); final ( @@ -313,6 +318,7 @@ class _BuzzPushLifecycle extends HookConsumerWidget { () => () { publicationAttempt.dispose(); tombstoneAttempt.dispose(); + otherOriginsAttempt.dispose(); }, const [], ); @@ -377,6 +383,58 @@ class _BuzzPushLifecycle extends HookConsumerWidget { ); final token = apnsDeviceToken.value; + final nativeCleanupKey = [ + for (final grant in pushEndpointGrants.value) + '${grant.relayOrigin}|${grant.relayPubkey}|${grant.gatewayInstallationHandle}|' + '${grant.generation}|${grant.endpointEpoch}|${grant.endpointGrant.isEmpty}|${grant.pending}', + ].join(';'); + final allOriginsKey = + '$nativeCleanupKey|${[for (final value in communities) '${value.id}|${value.pushNotificationsEnabled}|' + '${buzzPushSubscriptionsFingerprint(value.pushSubscriptionState.desired)}'].join(';')}'; + latestOtherOriginsAttempt.value = allOriginsKey; + useEffect(() { + if (!Env.pushGatewayConfigured || + otherOriginsBusy.value || + !otherOriginsAttempt.tryBegin(allOriginsKey)) { + return null; + } + otherOriginsBusy.value = true; + unawaited(() async { + var succeeded = false; + try { + if (!ref.read(communityListProvider).hasValue) { + throw StateError('Push community storage is still loading.'); + } + final grants = await readBuzzPushEndpointGrants(); + if (!context.mounted) return; + await revocationOutbox.reconcileGatewayCleanup( + ref.read(communityListProvider).value!, + readGrants: () async => grants, + ); + succeeded = true; + } catch (error, stack) { + if (context.mounted) { + otherOriginsAttempt.failed( + allOriginsKey, + retry: () { + if (context.mounted) otherOriginsRetry.value += 1; + }, + ); + } + reportPushSetupError('gateway cleanup', error, stack); + } finally { + otherOriginsBusy.value = false; + if (succeeded && + context.mounted && + latestOtherOriginsAttempt.value != allOriginsKey) { + otherOriginsAttempt.complete(allOriginsKey); + otherOriginsRetry.value += 1; + } + } + }()); + return null; + }, [allOriginsKey, otherOriginsRetry.value]); + useEffect( () { if (!_ready(session, config, community, memberPubkey) || @@ -497,12 +555,49 @@ class _BuzzPushLifecycle extends HookConsumerWidget { config.baseUrl, ); validateBuzzPushChannelGrammar(descriptor, desired); - final grant = await enrollBuzzPush( - config.wsUrl, - Env.pushGatewayUrl, - communitiesForSnapshotRefresh: - ref.read(communityListProvider).value ?? [community], - ); + bool currentIntent() { + if (!ref.context.mounted) return false; + final current = ref + .read(communityListProvider) + .value + ?.where((value) => value.id == community.id) + .firstOrNull; + return current != null && + current.pushNotificationsEnabled && + current.nsec?.trim() == config.nsec && + current.relayUrl == community.relayUrl && + buzzPushSubscriptionsFingerprint( + current.pushSubscriptionState.desired, + ) == + buzzPushSubscriptionsFingerprint(desired); + } + + if (!currentIntent()) throw StateError('Push setup was superseded.'); + + late final BuzzPushEndpointGrant grant; + try { + grant = await enrollBuzzPush( + config.wsUrl, + Env.pushGatewayUrl, + communitiesForSnapshotRefresh: + ref.read(communityListProvider).value ?? [community], + ); + } catch (error, stack) { + try { + await readBuzzPushEndpointGrants(); + } catch (readError, readStack) { + reportPushSetupError('pending gateway cleanup', readError, readStack); + } + Error.throwWithStackTrace(error, stack); + } + if (!currentIntent()) { + if (ref.context.mounted && ref.read(communityListProvider).hasValue) { + await ref + .read(buzzPushLeaseRevocationOutboxProvider) + .reconcileGatewayCleanup(ref.read(communityListProvider).value!); + } + throw StateError('Push setup was superseded.'); + } // Relay lease replacement and gateway delegation are independent state // machines. Subscription changes advance only the kind-30350 generation; // the opaque grant remains reusable until its own authority changes. diff --git a/mobile/lib/shared/push/push_bridge.dart b/mobile/lib/shared/push/push_bridge.dart index dc11f0e5f71..69da14fc815 100644 --- a/mobile/lib/shared/push/push_bridge.dart +++ b/mobile/lib/shared/push/push_bridge.dart @@ -156,6 +156,9 @@ Future startBuzzPushRegistration() async { } class BuzzPushEndpointGrant { + final bool pending; + final String? gatewayInstallationHandle; + final String? appAttestKeyId; final String relayOrigin; final String relayPubkey; final String installationId; @@ -166,6 +169,9 @@ class BuzzPushEndpointGrant { final int expiresAt; const BuzzPushEndpointGrant({ + this.pending = false, + this.gatewayInstallationHandle, + this.appAttestKeyId, required this.relayOrigin, required this.relayPubkey, required this.installationId, @@ -176,9 +182,29 @@ class BuzzPushEndpointGrant { required this.expiresAt, }); + Map? get gatewayRevocationTarget => pending + ? { + 'gatewayUrl': Env.pushGatewayUrl, + 'relayOrigin': relayOrigin, + 'relayPubkey': relayPubkey, + 'generation': generation, + } + : gatewayInstallationHandle == null || appAttestKeyId == null + ? null + : { + 'gatewayUrl': Env.pushGatewayUrl, + 'installationHandle': gatewayInstallationHandle, + 'keyId': appAttestKeyId, + 'relayPubkey': relayPubkey, + 'generation': generation, + }; + factory BuzzPushEndpointGrant.fromMap(Map map) { final generation = map['generation'] as int; return BuzzPushEndpointGrant( + pending: map['pending'] == true, + gatewayInstallationHandle: map['gatewayInstallationHandle'] as String?, + appAttestKeyId: map['appAttestKeyId'] as String?, relayOrigin: map['relayOrigin'] as String, relayPubkey: map['relayPubkey'] as String, installationId: map['installationId'] as String, @@ -242,6 +268,11 @@ Future enrollBuzzPush( return grant; } +/// Revokes the exact gateway authority retained by the durable cleanup journal. +Future revokeBuzzPushDelegation(Map target) async { + await _channel.invokeMethod('revokePushDelegation', target); +} + /// Latest failure to export the community snapshot used by the iOS /// notification service extension. Snapshot export is push enrichment and must /// never gate authentication or community persistence. diff --git a/mobile/lib/shared/push/push_lease_revocation_outbox.dart b/mobile/lib/shared/push/push_lease_revocation_outbox.dart index 35f9c5ed454..b5a8307e61e 100644 --- a/mobile/lib/shared/push/push_lease_revocation_outbox.dart +++ b/mobile/lib/shared/push/push_lease_revocation_outbox.dart @@ -12,7 +12,9 @@ import 'package:nostr/nostr.dart' as nostr; import '../storage/secure_storage.dart'; import '../community/community.dart'; +import '../community/community_provider.dart'; import '../relay/signed_event_relay.dart'; +import '../relay/relay_provider.dart' show Env; import 'dev_push_lease.dart'; import 'push_bridge.dart'; @@ -49,6 +51,10 @@ class BuzzPushLeaseRevocationRecord { final int attemptCount; final int nextAttemptAt; + /// Exact gateway target retained until both direct revocation and relay cleanup succeed. + final Map? gatewayRevocation; + final bool gatewayOnly; + BuzzPushLeaseRevocationRecord({ required this.relayUrl, required this.relayOrigin, @@ -59,6 +65,8 @@ class BuzzPushLeaseRevocationRecord { required this.expiresAt, required this.attemptCount, required this.nextAttemptAt, + this.gatewayRevocation, + this.gatewayOnly = false, }) { if (canonicalBuzzPushRelayOrigin(relayUrl) != relayOrigin) { throw const FormatException( @@ -70,19 +78,48 @@ class BuzzPushLeaseRevocationRecord { 'Push revocation member pubkey must be exact lowercase hex.', ); } - final decoded = nostr.Nip19.decode(payload: nsec); - if (decoded.prefix != nostr.Nip19Prefix.nsec || - decoded.data.length != 64 || - derivePublicKeyHex(decoded.data) != memberPubkey) { - throw const FormatException( - 'Push revocation signing key does not match its member pubkey.', - ); + if (!gatewayOnly) { + final decoded = nostr.Nip19.decode(payload: nsec); + if (decoded.prefix != nostr.Nip19Prefix.nsec || + decoded.data.length != 64 || + derivePublicKeyHex(decoded.data) != memberPubkey) { + throw const FormatException( + 'Push revocation signing key does not match its member pubkey.', + ); + } } if (!RegExp(_installationIdPattern).hasMatch(installationId)) { throw const FormatException( 'Push revocation installation id must be exact lowercase hex.', ); } + if (gatewayOnly && gatewayRevocation == null) { + throw const FormatException('Gateway cleanup requires a target.'); + } + if (gatewayRevocation case final target?) { + const keys = { + 'gatewayUrl', + 'installationHandle', + 'keyId', + 'relayPubkey', + 'generation', + }; + final pendingKeys = { + 'gatewayUrl', + 'relayOrigin', + 'relayPubkey', + 'generation', + }; + final fields = target.containsKey('relayOrigin') ? pendingKeys : keys; + if (!setEquals(target.keys.toSet(), fields) || + fields + .where((key) => key != 'generation') + .any((key) => target[key] is! String) || + target['generation'] is! int || + (target['generation'] as int) <= 0) { + throw const FormatException('Invalid gateway revocation target.'); + } + } if (generation <= 0 || generation > _maxSafeJsonInteger) { throw const FormatException('Push revocation generation is invalid.'); } @@ -91,7 +128,9 @@ class BuzzPushLeaseRevocationRecord { } } - String get leaseAddress => '$memberPubkey|$relayOrigin|$installationId'; + String get leaseAddress => gatewayOnly + ? 'gateway|${gatewayRevocation?['gatewayUrl']}|$relayOrigin|$installationId|${gatewayRevocation?['relayPubkey']}|${gatewayRevocation?['installationHandle'] ?? 'pending'}' + : '$memberPubkey|$relayOrigin|$installationId'; BuzzPushLeaseRevocationRecord copyWith({ int? generation, @@ -108,6 +147,8 @@ class BuzzPushLeaseRevocationRecord { expiresAt: expiresAt ?? this.expiresAt, attemptCount: attemptCount ?? this.attemptCount, nextAttemptAt: nextAttemptAt ?? this.nextAttemptAt, + gatewayRevocation: gatewayRevocation, + gatewayOnly: gatewayOnly, ); Map toJson() => { @@ -121,6 +162,8 @@ class BuzzPushLeaseRevocationRecord { 'expiresAt': expiresAt, 'attemptCount': attemptCount, 'nextAttemptAt': nextAttemptAt, + if (gatewayRevocation != null) 'gatewayRevocation': gatewayRevocation, + if (gatewayOnly) 'gatewayOnly': true, }; factory BuzzPushLeaseRevocationRecord.fromJson(Map json) { @@ -136,7 +179,11 @@ class BuzzPushLeaseRevocationRecord { 'attemptCount', 'nextAttemptAt', }; - if (json.keys.toSet().difference(keys).isNotEmpty || + if (json.keys.toSet().difference({ + ...keys, + 'gatewayRevocation', + 'gatewayOnly', + }).isNotEmpty || keys.difference(json.keys.toSet()).isNotEmpty || json['version'] != 1 || json['relayUrl'] is! String || @@ -160,6 +207,10 @@ class BuzzPushLeaseRevocationRecord { expiresAt: json['expiresAt'] as int, attemptCount: json['attemptCount'] as int, nextAttemptAt: json['nextAttemptAt'] as int, + gatewayOnly: json['gatewayOnly'] == true, + gatewayRevocation: json['gatewayRevocation'] == null + ? null + : Map.from(json['gatewayRevocation'] as Map), ); } } @@ -275,6 +326,7 @@ class BuzzPushLeaseRevocationOutbox { Future enqueueCommunity( Community community, { Future> Function()? readGrants, + List remainingCommunities = const [], }) async { final state = community.pushSubscriptionState; final highestGeneration = @@ -282,7 +334,35 @@ class BuzzPushLeaseRevocationOutbox { if (highestGeneration == null || (!community.pushNotificationsEnabled && state.pendingTombstoneGeneration == null)) { - return false; + if (!Env.pushGatewayConfigured || + defaultTargetPlatform != TargetPlatform.iOS) { + return false; + } + // Journal cancellation even before native enrollment has saved its first + // record. The shared native lane cannot acknowledge while it is in flight. + final relayOrigin = canonicalBuzzPushRelayOrigin(community.relayUrl); + final seconds = now().millisecondsSinceEpoch ~/ 1000; + await enqueue( + BuzzPushLeaseRevocationRecord( + relayUrl: canonicalBuzzPushRelayHttpUrl(community.relayUrl), + relayOrigin: relayOrigin, + memberPubkey: '0' * 64, + nsec: '', + installationId: community.pushLeaseInstallationId ?? '0' * 32, + generation: 1, + expiresAt: seconds + 300, + attemptCount: 0, + nextAttemptAt: seconds, + gatewayOnly: true, + gatewayRevocation: { + 'gatewayUrl': Env.pushGatewayUrl, + 'relayOrigin': relayOrigin, + 'relayPubkey': '', + 'generation': 1, + }, + ), + ); + return true; } final nsec = community.nsec; if (nsec == null || nsec.isEmpty) { @@ -305,6 +385,21 @@ class BuzzPushLeaseRevocationOutbox { } final currentSeconds = now().millisecondsSinceEpoch ~/ 1000; final grant = matching.single; + final shared = remainingCommunities.any( + (other) => + other.id != community.id && + other.pushNotificationsEnabled && + grants.any( + (candidate) => + candidate.relayOrigin == + canonicalBuzzPushRelayOrigin(other.relayUrl) && + candidate.relayPubkey == grant.relayPubkey && + (grant.pending + ? candidate.relayOrigin == grant.relayOrigin + : candidate.gatewayInstallationHandle == + grant.gatewayInstallationHandle), + ), + ); if (grant.expiresAt <= currentSeconds) return false; if (highestGeneration + 2 > _maxSafeJsonInteger) { throw StateError('Push lease generation is exhausted.'); @@ -321,11 +416,57 @@ class BuzzPushLeaseRevocationOutbox { expiresAt: grant.expiresAt, attemptCount: 0, nextAttemptAt: currentSeconds, + gatewayRevocation: shared ? null : grant.gatewayRevocationTarget, ), ); return true; } + /// Reconciles disabled or removed origins against durable native authority, + /// including first enrollment canceled before a relay lease was published. + Future reconcileGatewayCleanup( + List communities, { + Future> Function()? readGrants, + }) async { + final grants = await (readGrants ?? readBuzzPushEndpointGrants)(); + for (final grant in grants) { + final target = grant.gatewayRevocationTarget; + if (target == null || (!grant.pending && grant.endpointGrant.isEmpty)) { + continue; + } + final shared = communities.any( + (community) => + community.pushNotificationsEnabled && + grants.any( + (candidate) => + candidate.relayOrigin == + canonicalBuzzPushRelayOrigin(community.relayUrl) && + candidate.relayPubkey == grant.relayPubkey && + (grant.pending + ? candidate.relayOrigin == grant.relayOrigin + : candidate.gatewayInstallationHandle == + grant.gatewayInstallationHandle), + ), + ); + if (shared) continue; + await enqueue( + BuzzPushLeaseRevocationRecord( + relayUrl: canonicalBuzzPushRelayHttpUrl(grant.relayOrigin), + relayOrigin: grant.relayOrigin, + memberPubkey: '0' * 64, + nsec: '', + installationId: grant.installationId, + generation: 1, + expiresAt: grant.expiresAt, + attemptCount: 0, + nextAttemptAt: now().millisecondsSinceEpoch ~/ 1000, + gatewayRevocation: target, + gatewayOnly: true, + ), + ); + } + } + Future start() async { if (_disposed) throw StateError('Push revocation outbox is disposed.'); if (_started) return trigger(); @@ -367,7 +508,11 @@ class BuzzPushLeaseRevocationOutbox { final currentSeconds = now().millisecondsSinceEpoch ~/ 1000; final records = await storage.loadAll(); final active = records - .where((record) => record.expiresAt > currentSeconds) + .where( + (record) => + record.expiresAt > currentSeconds || + record.gatewayRevocation != null, + ) .toList(); final due = active @@ -440,7 +585,11 @@ class BuzzPushLeaseRevocationOutbox { final currentSeconds = now().millisecondsSinceEpoch ~/ 1000; final records = await storage.loadAll(); final active = records - .where((record) => record.expiresAt > currentSeconds) + .where( + (record) => + record.expiresAt > currentSeconds || + record.gatewayRevocation != null, + ) .toList(); if (active.length != records.length) { await storage.replaceAll(active); @@ -449,7 +598,11 @@ class BuzzPushLeaseRevocationOutbox { return; } final wakeAt = active - .map((record) => min(record.nextAttemptAt, record.expiresAt)) + .map( + (record) => record.gatewayRevocation == null + ? min(record.nextAttemptAt, record.expiresAt) + : record.nextAttemptAt, + ) .reduce(min); final delay = Duration(seconds: max(0, wakeAt - currentSeconds)); _cancelWake = scheduleWake(delay, () { @@ -509,8 +662,18 @@ Uri _buzzPushRelayUri(String relayUrl) { } Future publishBuzzPushLeaseRevocation( - BuzzPushLeaseRevocationRecord record, -) async { + BuzzPushLeaseRevocationRecord record, { + bool revokeGateway = true, + Map? gatewayRevocation, +}) async { + if (revokeGateway && record.gatewayRevocation != null) { + final target = gatewayRevocation ?? record.gatewayRevocation!; + await revokeBuzzPushDelegation(target); + } + if (record.gatewayOnly || + record.expiresAt <= DateTime.now().millisecondsSinceEpoch ~/ 1000) { + return; + } final descriptor = await fetchBuzzPushLeaseDescriptor(record.relayUrl); if (descriptor.origin != record.relayOrigin) { throw StateError('Relay push origin changed while revocation was pending.'); @@ -546,7 +709,54 @@ final buzzPushLeaseRevocationOutboxProvider = Provider((ref) { final outbox = BuzzPushLeaseRevocationOutbox( storage: ref.read(buzzPushLeaseRevocationStorageProvider), - publisher: publishBuzzPushLeaseRevocation, + publisher: (record) async { + var target = record.gatewayRevocation; + var revokeGateway = target != null; + if (target != null) { + final grants = await readBuzzPushEndpointGrants(); + if (target['relayPubkey'] == '') { + final relayOrigin = target['relayOrigin']; + final known = grants.where( + (grant) => grant.relayOrigin == relayOrigin, + ); + if (known.length == 1) { + target = known.single.gatewayRevocationTarget ?? target; + } + } + final originalTarget = target; + final communities = + ref.read(communityListProvider).value ?? + await ref.read(communityStorageProvider).loadAll(); + // Recheck at execution: another community may have opted in since + // this cleanup was journaled. Sharing is installation-scoped. + revokeGateway = + originalTarget['relayPubkey'] == '' || + !communities + .where((community) => community.pushNotificationsEnabled) + .any((community) { + final matching = grants.where( + (grant) => + grant.relayOrigin == + canonicalBuzzPushRelayOrigin(community.relayUrl), + ); + return matching.any( + (grant) => + grant.relayPubkey == + originalTarget['relayPubkey'] && + (originalTarget.containsKey('installationHandle') + ? grant.gatewayInstallationHandle == + originalTarget['installationHandle'] + : grant.relayOrigin == + originalTarget['relayOrigin']), + ); + }); + } + await publishBuzzPushLeaseRevocation( + record, + revokeGateway: revokeGateway, + gatewayRevocation: target, + ); + }, ); ref.onDispose(outbox.dispose); return outbox; diff --git a/mobile/test/features/settings/notification_recovery_test.dart b/mobile/test/features/settings/notification_recovery_test.dart index 25cd70ecc15..1f9714efb06 100644 --- a/mobile/test/features/settings/notification_recovery_test.dart +++ b/mobile/test/features/settings/notification_recovery_test.dart @@ -13,6 +13,7 @@ import 'package:buzz/shared/relay/app_lifecycle_provider.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:package_info_plus/package_info_plus.dart'; @@ -30,6 +31,18 @@ void main() { addTearDown(tester.view.reset); debugDefaultTargetPlatformOverride = TargetPlatform.iOS; addTearDown(() => debugDefaultTargetPlatformOverride = null); + const nativePush = MethodChannel('buzz/push'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler( + nativePush, + (call) async => switch (call.method) { + 'endpointGrants' => [], + 'takePendingNotificationResponse' => null, + _ => throw StateError('Unexpected native call ${call.method}'), + }, + ); + addTearDown(() => messenger.setMockMethodCallHandler(nativePush, null)); PackageInfo.setMockInitialValues( appName: 'Buzz', packageName: 'buzz', diff --git a/mobile/test/features/settings/notification_toggle_test.dart b/mobile/test/features/settings/notification_toggle_test.dart index 84f78e536fc..0e284f076f1 100644 --- a/mobile/test/features/settings/notification_toggle_test.dart +++ b/mobile/test/features/settings/notification_toggle_test.dart @@ -97,7 +97,9 @@ void main() { (call) async => switch (call.method) { 'enrollPush' => grant, 'endpointGrants' => [grant], - 'startRegistration' || 'syncPushSnapshot' => null, + 'startRegistration' || + 'syncPushSnapshot' || + 'takePendingNotificationResponse' => null, _ => throw StateError('Unexpected native call ${call.method}'), }, ); diff --git a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart index 12eb9cfe25d..a7c6d250b83 100644 --- a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart +++ b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart @@ -1,15 +1,21 @@ import 'dart:async'; import 'package:buzz/shared/community/community.dart'; +import 'package:buzz/shared/community/community_provider.dart'; +import 'package:buzz/shared/community/community_storage.dart'; import 'package:buzz/shared/push/push_bridge.dart'; import 'package:buzz/shared/push/push_lease_revocation_outbox.dart'; import 'package:buzz/shared/push/push_subscription.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:nostr/nostr.dart' as nostr; import '../community/community_storage_test.dart'; void main() { + TestWidgetsFlutterBinding.ensureInitialized(); late FakeSecureStorage secure; late BuzzPushLeaseRevocationStorage storage; late _Clock clock; @@ -24,6 +30,178 @@ void main() { keys = nostr.Keys.generate(); }); + group('production cleanup publisher', () { + const channel = MethodChannel('buzz/push'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + setUp(() => debugDefaultTargetPlatformOverride = TargetPlatform.iOS); + tearDown(() { + messenger.setMockMethodCallHandler(channel, null); + debugDefaultTargetPlatformOverride = null; + pushEndpointGrants.value = []; + pushLeaseCleanupError.value = null; + }); + + for (final (siblingSigner, differentInstallation) in [ + (null, false), + ('c' * 64, false), + ('a' * 64, false), + ('a' * 64, true), + ]) { + test( + 'only a shared installation/signer retains authority: $siblingSigner/$differentInstallation', + () async { + final sibling = Community.create( + name: 'Unrelated or shared', + relayUrl: 'wss://other.example', + ); + final communities = CommunityStorage(secure: secure); + await communities.save(sibling); + final grant = _grant( + expiresAt: DateTime.now().millisecondsSinceEpoch ~/ 1000 + 3600, + ); + final grants = [ + grant, + if (siblingSigner != null) + BuzzPushEndpointGrant( + relayOrigin: 'wss://other.example', + relayPubkey: siblingSigner, + installationId: grant.installationId, + endpointGrant: 'opaque', + endpointHash: grant.endpointHash, + endpointEpoch: 1, + generation: 1, + expiresAt: grant.expiresAt, + gatewayInstallationHandle: differentInstallation + ? '44444444-4444-4444-8444-444444444444' + : grant.gatewayInstallationHandle, + appAttestKeyId: grant.appAttestKeyId, + ), + ]; + final revoked = []; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'endpointGrants') { + return [for (final value in grants) _nativeGrant(value)]; + } + if (call.method == 'revokePushDelegation') { + revoked.add(call.arguments); + return null; + } + throw StateError('Unexpected native call: ${call.method}'); + }); + final container = ProviderContainer( + overrides: [ + communityStorageProvider.overrideWithValue(communities), + communitySnapshotWriterProvider.overrideWithValue((_) async {}), + communityPushLeaseDeactivatorProvider.overrideWithValue( + (_, {generation}) async {}, + ), + buzzPushLeaseRevocationStorageProvider.overrideWithValue(storage), + ], + ); + addTearDown(container.dispose); + await container.read(communityListProvider.future); + final outbox = container.read(buzzPushLeaseRevocationOutboxProvider); + // A was removed before B was added or its signer was discovered. + await outbox.reconcileGatewayCleanup( + [], + readGrants: () async => [grant], + ); + expect(await storage.loadAll(), hasLength(1)); + await outbox.trigger(); + expect( + revoked, + siblingSigner == grant.relayPubkey && !differentInstallation + ? isEmpty + : [grant.gatewayRevocationTarget], + ); + expect(await storage.loadAll(), isEmpty); + final shared = + siblingSigner == grant.relayPubkey && !differentInstallation; + await outbox.reconcileGatewayCleanup([ + sibling, + ], readGrants: () async => grants); + expect(await storage.loadAll(), hasLength(shared ? 0 : 1)); + await storage.replaceAll([]); + final removed = + Community.create( + name: 'Removed', + relayUrl: grant.relayOrigin, + nsec: keys.nsec, + ).copyWith( + pushSubscriptionState: + const BuzzPushLeaseSubscriptionState.desired() + .withReservedGeneration(4), + ); + await outbox.enqueueCommunity( + removed, + readGrants: () async => grants, + remainingCommunities: [sibling], + ); + expect( + (await storage.loadAll()).single.gatewayRevocation, + shared ? isNull : grant.gatewayRevocationTarget, + ); + await storage.replaceAll([]); + await communities.save(removed); + container.invalidate(communityListProvider); + await container.read(communityListProvider.future); + revoked.clear(); + await container + .read(communityListProvider.notifier) + .setPushNotificationsEnabled(removed.id, false); + expect(revoked, shared ? isEmpty : [grant.gatewayRevocationTarget]); + }, + ); + } + + test( + 'native revocation failure retains the exact cleanup journal', + () async { + final grant = _grant( + expiresAt: DateTime.now().millisecondsSinceEpoch ~/ 1000 + 3600, + ); + final communities = CommunityStorage(secure: secure); + await communities.save( + Community.create( + name: 'New unrelated community', + relayUrl: 'wss://other.example', + ), + ); + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'endpointGrants') return [_nativeGrant(grant)]; + if (call.method == 'revokePushDelegation') { + throw PlatformException(code: 'enrollment_in_progress'); + } + throw StateError('Unexpected native call: ${call.method}'); + }); + final container = ProviderContainer( + overrides: [ + communityStorageProvider.overrideWithValue(communities), + communitySnapshotWriterProvider.overrideWithValue((_) async {}), + buzzPushLeaseRevocationStorageProvider.overrideWithValue(storage), + ], + ); + addTearDown(container.dispose); + await container.read(communityListProvider.future); + final outbox = container.read(buzzPushLeaseRevocationOutboxProvider); + await outbox.reconcileGatewayCleanup( + [], + readGrants: () async => [grant], + ); + await outbox.trigger(); + final pending = (await storage.loadAll()).single; + expect(pending.gatewayRevocation, grant.gatewayRevocationTarget); + expect(pending.attemptCount, 1); + expect( + pending.nextAttemptAt, + greaterThan(DateTime.now().millisecondsSinceEpoch ~/ 1000), + ); + }, + ); + }); + test('community removal journals one precise lease address', () async { final outbox = _outbox( storage: storage, @@ -58,6 +236,158 @@ void main() { expect(records.single.relayUrl, 'https://relay.example/'); }); + test( + 'gateway target survives failed cleanup and is omitted for shared signer', + () async { + final community = + Community.create( + name: 'First', + relayUrl: 'wss://relay.example', + nsec: keys.nsec, + ).copyWith( + pubkey: keys.public, + pushNotificationsEnabled: true, + pushSubscriptionState: + const BuzzPushLeaseSubscriptionState.desired() + .withReservedGeneration(4), + ); + final grant = _grant(expiresAt: clock.seconds + 3600); + final outbox = _outbox( + storage: storage, + clock: clock, + scheduler: scheduler, + publisher: (_) async => throw StateError('gateway response lost'), + ); + await outbox.enqueueCommunity(community, readGrants: () async => [grant]); + final before = (await storage.loadAll()).single.gatewayRevocation; + expect(before?['generation'], 1); + expect( + before?['installationHandle'], + '22222222-2222-4222-8222-222222222222', + ); + await outbox.trigger(); + expect((await storage.loadAll()).single.gatewayRevocation, before); + await storage.replaceAll([]); + final sibling = Community.create( + name: 'Second', + relayUrl: 'wss://relay.example', + nsec: keys.nsec, + ).copyWith(pushNotificationsEnabled: true); + await outbox.enqueueCommunity( + community, + readGrants: () async => [grant], + remainingCommunities: [sibling], + ); + expect((await storage.loadAll()).single.gatewayRevocation, isNull); + }, + ); + + test( + 'canceled first enrollment remains durable past its old expiry', + () async { + final community = Community.create( + name: 'Canceled', + relayUrl: 'wss://relay.example', + ).copyWith(pushNotificationsEnabled: false); + final pending = BuzzPushEndpointGrant( + pending: true, + relayOrigin: 'wss://relay.example', + relayPubkey: 'a' * 64, + installationId: '0' * 32, + endpointGrant: '', + endpointHash: 'b' * 64, + endpointEpoch: 1, + generation: 1, + expiresAt: clock.seconds + 1, + ); + var attempts = 0; + final outbox = _outbox( + storage: storage, + clock: clock, + scheduler: scheduler, + publisher: (_) async { + attempts += 1; + throw StateError('native enrollment still in flight'); + }, + ); + await outbox.reconcileGatewayCleanup([ + community, + ], readGrants: () async => [pending]); + final target = (await storage.loadAll()).single; + expect(target.gatewayOnly, isTrue); + expect(target.gatewayRevocation?['relayOrigin'], pending.relayOrigin); + expect(target.gatewayRevocation?['installationHandle'], isNull); + clock.seconds += 2; + await outbox.trigger(); + expect(attempts, 1); + expect(await storage.loadAll(), hasLength(1)); + await storage.replaceAll([]); + await outbox.reconcileGatewayCleanup([ + community.copyWith(pushNotificationsEnabled: true), + ], readGrants: () async => [pending]); + expect( + await storage.loadAll(), + isEmpty, + reason: 'an enabled sibling retains shared authority', + ); + }, + ); + + test( + 'gateway cleanup retains separate authorities after relay key rotation', + () async { + final outbox = _outbox( + storage: storage, + clock: clock, + scheduler: scheduler, + publisher: (_) async => throw StateError('offline'), + ); + final first = _grant(expiresAt: clock.seconds + 3600); + await outbox.reconcileGatewayCleanup([], readGrants: () async => [first]); + await outbox.trigger(); + expect((await storage.loadAll()).single.generation, 2); + final second = _grant( + expiresAt: clock.seconds + 3600, + relayPubkey: 'c' * 64, + ); + await outbox.reconcileGatewayCleanup( + [], + readGrants: () async => [second], + ); + final records = await storage.loadAll(); + expect(records, hasLength(2)); + expect( + records + .map((record) => record.gatewayRevocation?['relayPubkey']) + .toSet(), + {'a' * 64, 'c' * 64}, + ); + expect(records.last.generation, 1); + }, + ); + + test( + 'gateway version does not become the JSON-safe local retry counter', + () async { + final outbox = _outbox( + storage: storage, + clock: clock, + scheduler: scheduler, + publisher: (_) async {}, + ); + const maximum = 9223372036854775807; + await outbox.reconcileGatewayCleanup( + [], + readGrants: () async => [ + _grant(expiresAt: clock.seconds + 3600, generation: maximum), + ], + ); + final record = (await storage.loadAll()).single; + expect(record.generation, 1); + expect(record.gatewayRevocation?['generation'], maximum); + }, + ); + test('legacy community revokes its grant-addressed lease', () async { final outbox = _outbox( storage: storage, @@ -296,14 +626,20 @@ BuzzPushLeaseRevocationRecord _record({ nextAttemptAt: clock.seconds, ); -BuzzPushEndpointGrant _grant({required int expiresAt}) => BuzzPushEndpointGrant( +BuzzPushEndpointGrant _grant({ + required int expiresAt, + String? relayPubkey, + int generation = 1, +}) => BuzzPushEndpointGrant( + gatewayInstallationHandle: '22222222-2222-4222-8222-222222222222', + appAttestKeyId: 'installed-app-attest-key', relayOrigin: 'wss://relay.example', - relayPubkey: 'a' * 64, + relayPubkey: relayPubkey ?? 'a' * 64, installationId: '0' * 32, endpointGrant: 'opaque', endpointHash: 'b' * 64, endpointEpoch: 1, - generation: 1, + generation: generation, expiresAt: expiresAt, ); @@ -328,3 +664,16 @@ class _WakeScheduler { class _ScheduledWake { bool cancelled = false; } + +Map _nativeGrant(BuzzPushEndpointGrant grant) => { + 'relayOrigin': grant.relayOrigin, + 'relayPubkey': grant.relayPubkey, + 'installationId': grant.installationId, + 'endpointGrant': grant.endpointGrant, + 'endpointHash': grant.endpointHash, + 'endpointEpoch': grant.endpointEpoch, + 'generation': grant.generation, + 'expiresAt': grant.expiresAt, + 'gatewayInstallationHandle': grant.gatewayInstallationHandle, + 'appAttestKeyId': grant.appAttestKeyId, +}; diff --git a/mobile/test/shared/push/push_root_isolation_test.dart b/mobile/test/shared/push/push_root_isolation_test.dart index e8bcb78e8fe..771a0667cf5 100644 --- a/mobile/test/shared/push/push_root_isolation_test.dart +++ b/mobile/test/shared/push/push_root_isolation_test.dart @@ -19,6 +19,7 @@ import 'package:buzz/shared/push/dev_push_lease.dart'; import 'package:buzz/shared/push/push_bootstrap.dart'; import 'package:buzz/shared/push/push_bridge.dart'; import 'package:buzz/shared/push/push_subscription.dart'; +import 'package:buzz/shared/push/push_subscription_provider.dart'; import 'package:nostr/nostr.dart' as nostr; import 'package:buzz/shared/push/push_lease_revocation_outbox.dart'; import 'package:buzz/shared/push/push_relay_capability_provider.dart'; @@ -334,6 +335,134 @@ void main() { }, ); + testWidgets( + 'opt-out fences late native generation recovery and journals cleanup', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + final keys = nostr.Keys.generate(); + final community = + Community.create( + name: 'Canceled', + relayUrl: 'https://relay.example', + nsec: keys.nsec, + pubkey: keys.public, + ).copyWith( + pushSubscriptionState: BuzzPushLeaseSubscriptionState.desired( + desired: [ + BuzzPushSubscription( + filter: BuzzPushFilter(kinds: [9], pTags: [keys.public]), + notificationClass: 'default', + ), + ], + ), + ); + final storage = CommunityStorage(secure: FakeSecureStorage()); + await storage.save(community); + await storage.save( + Community.create(name: 'Unrelated', relayUrl: 'https://other.example'), + ); + await storage.saveActiveId(community.id); + final journal = BuzzPushLeaseRevocationStorage( + secure: FakeSecureStorage(), + ); + final enrollment = Completer>(); + var enrollments = 0; + final grant = { + 'relayOrigin': 'wss://relay.example', + 'relayPubkey': 'a' * 64, + 'installationId': '0' * 32, + 'endpointGrant': 'g2_recovered', + 'endpointHash': 'b' * 64, + 'endpointEpoch': 1, + 'generation': 4, + 'expiresAt': DateTime.now().millisecondsSinceEpoch ~/ 1000 + 3600, + 'gatewayInstallationHandle': '22222222-2222-4222-8222-222222222222', + 'appAttestKeyId': 'installed-key', + }; + const native = MethodChannel('buzz/push'); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(native, ( + call, + ) async { + switch (call.method) { + case 'endpointGrants': + return enrollment.isCompleted ? [grant] : []; + case 'enrollPush': + enrollments++; + return enrollment.future; + case 'revokePushDelegation': + throw PlatformException(code: 'push_management_busy_or_invalid'); + default: + return null; + } + }); + addTearDown(() { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + native, + null, + ); + apnsDeviceToken.value = null; + pushEndpointGrants.value = []; + pushLeaseCleanupError.value = null; + }); + apnsDeviceToken.value = 'token'; + await tester.pumpWidget( + ProviderScope( + retry: (_, _) => null, + overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + communityStorageProvider.overrideWithValue(storage), + communitySnapshotWriterProvider.overrideWithValue((_) async {}), + buzzPushLeaseRevocationStorageProvider.overrideWithValue(journal), + relaySessionProvider.overrideWith(_ConnectedSession.new), + pushSubscriptionSyncProvider.overrideWith((_) async => 0), + currentRelayPushDescriptorProvider.overrideWith( + (_) async => _descriptor, + ), + buzzPushDescriptorFetcherProvider.overrideWithValue( + (_) async => _descriptor, + ), + ], + child: const BuzzPushBootstrap(child: SizedBox()), + ), + ); + await tester.pump(); + await tester.pump(); + expect(enrollments, 1); + final container = ProviderScope.containerOf( + tester.element(find.byType(BuzzPushBootstrap)), + ); + await container + .read(communityListProvider.notifier) + .setPushNotificationsEnabled(community.id, false); + await tester.pump(); + // Native may safely recover a stale/lost issuance at generation 4 while + // its serialized cancellation is waiting. That result is not new consent. + enrollment.complete(grant); + await tester.pump(); + await tester.pump(); + final canceled = (await storage.loadAll()).firstWhere( + (value) => value.id == community.id, + ); + expect(canceled.pushNotificationsEnabled, isFalse); + expect(canceled.pushSubscriptionState.generationCursor, isNull); + final pending = await journal.loadAll(); + expect( + pending.any( + (record) => + record.gatewayRevocation?['generation'] == 4 && + record.gatewayRevocation?['installationHandle'] == + grant['gatewayInstallationHandle'], + ), + isTrue, + ); + expect(enrollments, 1); + await tester.pumpWidget(const SizedBox()); + debugDefaultTargetPlatformOverride = null; + }, + ); + testWidgets('cold-start native failure cannot prevent runApp', ( tester, ) async { @@ -411,6 +540,11 @@ class _Age extends AgeSignalNotifier { Future request() async {} } +class _ConnectedSession extends RelaySessionNotifier { + @override + SessionState build() => const SessionState(status: SessionStatus.connected); +} + class _Session extends RelaySessionNotifier { @override SessionState build() => From 01603c7ecb2348a01439d43f2b083444bbec4758 Mon Sep 17 00:00:00 2001 From: jm Date: Thu, 29 Oct 2026 21:17:41 +0000 Subject: [PATCH 2/7] fix(push): journal gateway and relay cleanup independently Signed-off-by: jm Co-authored-by: Codex --- .../shared/community/community_provider.dart | 67 +++--- .../push/push_lease_revocation_outbox.dart | 45 +++- .../community/community_provider_test.dart | 3 + .../test/shared/push/push_bootstrap_test.dart | 193 +++++++++++++++++- .../push_lease_revocation_outbox_test.dart | 178 +++++++++++++++- .../test/shared/push/push_relay_fixture.dart | 104 ++++++++++ 6 files changed, 528 insertions(+), 62 deletions(-) create mode 100644 mobile/test/shared/push/push_relay_fixture.dart diff --git a/mobile/lib/shared/community/community_provider.dart b/mobile/lib/shared/community/community_provider.dart index 6e28f3a78f8..e8dd46f3a22 100644 --- a/mobile/lib/shared/community/community_provider.dart +++ b/mobile/lib/shared/community/community_provider.dart @@ -118,6 +118,17 @@ final communityPushLeaseRevocationEnqueuerProvider = ); }); +/// Journals gateway opt-out independently of the community's relay tombstone. +final communityPushGatewayCleanupEnqueuerProvider = + Provider((ref) { + final outbox = ref.watch(buzzPushLeaseRevocationOutboxProvider); + return (community) => outbox.enqueueCommunity( + community, + gatewayOnly: true, + remainingCommunities: ref.read(communityListProvider).value ?? const [], + ); + }); + typedef CommunityPushLeaseRevocationTrigger = Future Function(); final communityPushLeaseRevocationTriggerProvider = @@ -535,17 +546,19 @@ class CommunityListNotifier extends AsyncNotifier> { pushNotificationsEnabled: enabled, pushSubscriptionState: pushState, ); - if (!enabled && pushState.pendingTombstoneGeneration == null) { - gatewayCleanupJournaled = await ref.read( - communityPushLeaseRevocationEnqueuerProvider, - )(updated); - } await storage.save(updated); final updatedList = [...current]..[index] = updated; state = AsyncData(updatedList); - await syncCommunitySnapshot(ref, updatedList); shouldDeactivate = !enabled && pushState.pendingTombstoneGeneration != null; + if (!enabled) { + // Save local opt-out first, then journal the exact gateway target before + // any native revoke can blank the inventory needed for recovery. + gatewayCleanupJournaled = await ref.read( + communityPushGatewayCleanupEnqueuerProvider, + )(updated); + } + await syncCommunitySnapshot(ref, updatedList); }); if (gatewayCleanupJournaled) { unawaited(ref.read(communityPushLeaseRevocationTriggerProvider)()); @@ -622,40 +635,14 @@ class CommunityListNotifier extends AsyncNotifier> { final generation = pendingGeneration; if (community == null || generation == null) return; try { - final grants = await readBuzzPushEndpointGrants(); - final matching = grants.where( - (grant) => - grant.relayOrigin == - canonicalBuzzPushRelayOrigin(community.relayUrl), - ); - if (matching.length == 1) { - final grant = matching.single; - final target = grant.gatewayRevocationTarget; - final current = - state.value ?? await ref.read(communityStorageProvider).loadAll(); - final pending = current.where((candidate) => candidate.id == id); - if (pending.isEmpty || - pending.single.pushNotificationsEnabled || - pending.single.pushSubscriptionState.pendingTombstoneGeneration != - generation) { - return; - } - final shared = current.any( - (other) => - other.id != id && - other.pushNotificationsEnabled && - grants.any( - (candidate) => - candidate.relayOrigin == - canonicalBuzzPushRelayOrigin(other.relayUrl) && - candidate.relayPubkey == grant.relayPubkey && - (grant.pending - ? candidate.relayOrigin == grant.relayOrigin - : candidate.gatewayInstallationHandle == - grant.gatewayInstallationHandle), - ), - ); - if (!shared && target != null) await revokeBuzzPushDelegation(target); + final current = + state.value ?? await ref.read(communityStorageProvider).loadAll(); + final pending = current.where((candidate) => candidate.id == id); + if (pending.isEmpty || + pending.single.pushNotificationsEnabled || + pending.single.pushSubscriptionState.pendingTombstoneGeneration != + generation) { + return; } await ref.read(communityPushLeaseDeactivatorProvider)( community, diff --git a/mobile/lib/shared/push/push_lease_revocation_outbox.dart b/mobile/lib/shared/push/push_lease_revocation_outbox.dart index b5a8307e61e..a3eb86eb712 100644 --- a/mobile/lib/shared/push/push_lease_revocation_outbox.dart +++ b/mobile/lib/shared/push/push_lease_revocation_outbox.dart @@ -51,7 +51,7 @@ class BuzzPushLeaseRevocationRecord { final int attemptCount; final int nextAttemptAt; - /// Exact gateway target retained until both direct revocation and relay cleanup succeed. + /// Exact gateway target retained until direct revocation succeeds. final Map? gatewayRevocation; final bool gatewayOnly; @@ -137,6 +137,8 @@ class BuzzPushLeaseRevocationRecord { int? expiresAt, int? attemptCount, int? nextAttemptAt, + bool? gatewayOnly, + bool omitGatewayRevocation = false, }) => BuzzPushLeaseRevocationRecord( relayUrl: relayUrl, relayOrigin: relayOrigin, @@ -147,8 +149,8 @@ class BuzzPushLeaseRevocationRecord { expiresAt: expiresAt ?? this.expiresAt, attemptCount: attemptCount ?? this.attemptCount, nextAttemptAt: nextAttemptAt ?? this.nextAttemptAt, - gatewayRevocation: gatewayRevocation, - gatewayOnly: gatewayOnly, + gatewayRevocation: omitGatewayRevocation ? null : gatewayRevocation, + gatewayOnly: gatewayOnly ?? this.gatewayOnly, ); Map toJson() => { @@ -309,14 +311,25 @@ class BuzzPushLeaseRevocationOutbox { Future enqueue(BuzzPushLeaseRevocationRecord record) async { await _serialize(() async { final records = await storage.loadAll(); - final index = records.indexWhere( - (candidate) => candidate.leaseAddress == record.leaseAddress, - ); - if (index >= 0) { - if (record.generation <= records[index].generation) return; - records[index] = record; - } else { - records.add(record); + // Save both authorities together before either attempt can invalidate + // native inventory. Each record then retains only its unfinished work. + final independent = [ + if (!record.gatewayOnly && record.gatewayRevocation != null) + record.copyWith(gatewayOnly: true), + record.gatewayOnly + ? record + : record.copyWith(omitGatewayRevocation: true), + ]; + for (final cleanup in independent) { + final index = records.indexWhere( + (candidate) => candidate.leaseAddress == cleanup.leaseAddress, + ); + if (index >= 0) { + if (cleanup.generation <= records[index].generation) continue; + records[index] = cleanup; + } else { + records.add(cleanup); + } } await storage.replaceAll(records); }); @@ -327,7 +340,13 @@ class BuzzPushLeaseRevocationOutbox { Community community, { Future> Function()? readGrants, List remainingCommunities = const [], + bool gatewayOnly = false, }) async { + if (gatewayOnly && + (!Env.pushGatewayConfigured || + defaultTargetPlatform != TargetPlatform.iOS)) { + return false; + } final state = community.pushSubscriptionState; final highestGeneration = state.generationCursor ?? state.acceptedGeneration; @@ -401,6 +420,9 @@ class BuzzPushLeaseRevocationOutbox { ), ); if (grant.expiresAt <= currentSeconds) return false; + if (gatewayOnly && (shared || grant.gatewayRevocationTarget == null)) { + return false; + } if (highestGeneration + 2 > _maxSafeJsonInteger) { throw StateError('Push lease generation is exhausted.'); } @@ -417,6 +439,7 @@ class BuzzPushLeaseRevocationOutbox { attemptCount: 0, nextAttemptAt: currentSeconds, gatewayRevocation: shared ? null : grant.gatewayRevocationTarget, + gatewayOnly: gatewayOnly, ), ); return true; diff --git a/mobile/test/shared/community/community_provider_test.dart b/mobile/test/shared/community/community_provider_test.dart index c4f56250c80..cc47b80fb0c 100644 --- a/mobile/test/shared/community/community_provider_test.dart +++ b/mobile/test/shared/community/community_provider_test.dart @@ -68,6 +68,9 @@ void main() { return true; }, ), + communityPushGatewayCleanupEnqueuerProvider.overrideWithValue( + (community) async => true, + ), communityPushLeaseRevocationTriggerProvider.overrideWithValue( revocationTrigger, ), diff --git a/mobile/test/shared/push/push_bootstrap_test.dart b/mobile/test/shared/push/push_bootstrap_test.dart index ee3b880a729..495169859a0 100644 --- a/mobile/test/shared/push/push_bootstrap_test.dart +++ b/mobile/test/shared/push/push_bootstrap_test.dart @@ -1,11 +1,194 @@ +import 'dart:async'; +import 'dart:convert'; import 'package:buzz/shared/push/dev_push_lease.dart'; import 'package:buzz/shared/community/community.dart'; +import 'package:buzz/shared/community/community_provider.dart'; +import 'package:buzz/shared/community/community_storage.dart'; import 'package:buzz/shared/push/push_bootstrap.dart'; +import 'package:buzz/shared/push/push_bridge.dart'; import 'package:buzz/shared/push/push_subscription.dart'; +import 'package:buzz/shared/push/push_subscription_provider.dart'; +import 'package:buzz/shared/push/push_lease_revocation_outbox.dart'; +import 'package:buzz/shared/push/push_relay_capability_provider.dart'; +import 'package:buzz/shared/relay/relay.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter/widgets.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:shared_preferences/shared_preferences.dart'; +import '../community/community_storage_test.dart' show FakeSecureStorage; void main() { + testWidgets( + 'gateway opt-out retries independently while relay stays disconnected across restart', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + final keys = nostr.Keys('1' * 64); + final relayKey = nostr.Keys('2' * 64).public; + final subscription = BuzzPushSubscription( + filter: BuzzPushFilter(kinds: [9], pTags: [keys.public]), + notificationClass: 'default', + ); + final community = + Community.create( + name: 'Team', + relayUrl: 'https://relay.example', + nsec: keys.nsec, + pubkey: keys.public, + ).copyWith( + pushSubscriptionState: BuzzPushLeaseSubscriptionState.desired( + desired: [subscription], + ).withAccepted(subscriptions: [subscription], generation: 7), + ); + final storage = CommunityStorage(secure: FakeSecureStorage()); + await storage.save(community); + final journal = BuzzPushLeaseRevocationStorage( + secure: FakeSecureStorage(), + ); + var grant = 'opaque-before-revoke'; + var calls = 0; + var nativeReads = 0; + var relayTombstones = 0; + var sessionDisconnected = true; + var failGateway = true; + const native = MethodChannel('buzz/push'); + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(native, (call) async { + if (call.method == 'endpointGrants') { + nativeReads++; + return [ + { + 'relayOrigin': 'wss://relay.example', + 'relayPubkey': relayKey, + 'installationId': '0' * 32, + 'endpointGrant': grant, + 'endpointHash': 'b' * 64, + 'endpointEpoch': 1, + 'generation': 3, + 'expiresAt': + DateTime.now().millisecondsSinceEpoch ~/ 1000 + 86400, + 'gatewayInstallationHandle': + '123e4567-e89b-42d3-a456-426614174000', + 'appAttestKeyId': base64Encode(List.filled(32, 7)), + }, + ]; + } + if (call.method == 'revokePushDelegation') { + calls++; + // This is the production Swift driver's durable pre-request mutation. + grant = ''; + if (failGateway) + throw PlatformException(code: 'transient_gateway_failure'); + } + return null; + }); + addTearDown(() { + messenger.setMockMethodCallHandler(native, null); + pushEndpointGrants.value = const []; + apnsDeviceToken.value = null; + }); + final overrides = [ + savedPrefsProvider.overrideWithValue(prefs), + communityStorageProvider.overrideWithValue(storage), + communitySnapshotWriterProvider.overrideWithValue((_) async {}), + buzzPushLeaseRevocationOutboxProvider.overrideWith((ref) { + final outbox = BuzzPushLeaseRevocationOutbox( + storage: journal, + publisher: publishBuzzPushLeaseRevocation, + now: tester.binding.clock.now, + jitter: () => 0, + ); + ref.onDispose(outbox.dispose); + return outbox; + }), + communityPushLeaseDeactivatorProvider.overrideWithValue(( + community, { + generation, + }) async { + relayTombstones++; + if (sessionDisconnected) throw StateError('relay offline'); + }), + ]; + final initial = ProviderContainer(overrides: overrides); + await initial.read(communityListProvider.future); + await initial + .read(communityListProvider.notifier) + .setPushNotificationsEnabled(community.id, false); + await initial.read(buzzPushLeaseRevocationOutboxProvider).trigger(); + expect(calls, 1); + expect(grant, isEmpty); + expect( + (await journal.loadAll()).single.gatewayRevocation?['generation'], + 3, + ); + expect( + (await storage.loadAll()) + .single + .pushSubscriptionState + .pendingTombstoneGeneration, + 8, + ); + expect(relayTombstones, 1); + initial.dispose(); + + failGateway = false; // gateway recovered; relay remains disconnected. + final disabled = (await storage.loadAll()).single; + final session = _ConnectedSession( + initialStatus: SessionStatus.disconnected, + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + ...overrides, + relaySessionProvider.overrideWith(() => session), + activeCommunityProvider.overrideWith((_) async => disabled), + currentRelayPushDescriptorProvider.overrideWith((_) async => null), + pushSubscriptionSyncProvider.overrideWith((_) async => 0), + ], + child: const BuzzPushBootstrap(child: SizedBox()), + ), + ); + for (var i = 0; i < 10; i++) { + await tester.pump(); + } + for (final seconds in [5, 30, 120]) { + await tester.pump(Duration(seconds: seconds)); + await tester.pump(); + } + expect(nativeReads, greaterThan(1)); // native inventory was reconciled. + expect(calls, 2); // Durable retry ran without a relay connection. + expect(await journal.loadAll(), isEmpty); + expect( + (await storage.loadAll()) + .single + .pushSubscriptionState + .pendingTombstoneGeneration, + 8, + ); + sessionDisconnected = false; + session.setStatus(SessionStatus.connected); + for (var i = 0; i < 12; i++) { + await tester.pump(); + } + expect(calls, 2); + expect(relayTombstones, 2); + expect( + (await storage.loadAll()) + .single + .pushSubscriptionState + .pendingTombstoneGeneration, + isNull, + ); + await tester.pumpWidget(const SizedBox.shrink()); + debugDefaultTargetPlatformOverride = null; + }, + ); + testWidgets('first opt-in starts registration without switching community', ( tester, ) async { @@ -299,3 +482,11 @@ BuzzPushLeaseDescriptor _descriptor({ ); String _hex(String character) => List.filled(64, character).join(); + +class _ConnectedSession extends RelaySessionNotifier { + _ConnectedSession({required this.initialStatus}); + final SessionStatus initialStatus; + @override + SessionState build() => SessionState(status: initialStatus); + void setStatus(SessionStatus value) => state = SessionState(status: value); +} diff --git a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart index a7c6d250b83..41cc40fbc22 100644 --- a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart +++ b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart @@ -1,4 +1,7 @@ import 'dart:async'; +import 'dart:io'; + +import 'push_relay_fixture.dart'; import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_provider.dart'; @@ -140,8 +143,10 @@ void main() { remainingCommunities: [sibling], ); expect( - (await storage.loadAll()).single.gatewayRevocation, - shared ? isNull : grant.gatewayRevocationTarget, + (await storage.loadAll()) + .where((record) => record.gatewayOnly) + .map((record) => record.gatewayRevocation), + shared ? isEmpty : [grant.gatewayRevocationTarget], ); await storage.replaceAll([]); await communities.save(removed); @@ -151,11 +156,154 @@ void main() { await container .read(communityListProvider.notifier) .setPushNotificationsEnabled(removed.id, false); + await outbox.trigger(); expect(revoked, shared ? isEmpty : [grant.gatewayRevocationTarget]); }, ); } + test( + 'opt-out reaches relay while gateway cleanup remains durable', + () async { + await HttpOverrides.runWithHttpOverrides(() async { + final relay = await PushRelayFixture.start(); + addTearDown(relay.close); + final communities = CommunityStorage(secure: secure); + final subscriptions = [ + BuzzPushSubscription( + filter: BuzzPushFilter(kinds: [9], pTags: [keys.public]), + notificationClass: 'default', + ), + ]; + final community = + Community.create( + name: 'Team', + relayUrl: relay.httpUrl, + nsec: keys.nsec, + pubkey: keys.public, + ).copyWith( + pushSubscriptionState: BuzzPushLeaseSubscriptionState.desired( + desired: subscriptions, + ).withAccepted(subscriptions: subscriptions, generation: 7), + ); + await communities.save(community); + final grant = _nativeGrant( + _grant( + expiresAt: DateTime.now().millisecondsSinceEpoch ~/ 1000 + 3600, + ), + )..['relayOrigin'] = relay.wsUrl; + var calls = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'endpointGrants') return [grant]; + if (call.method == 'revokePushDelegation') { + calls++; + grant['endpointGrant'] = ''; + throw PlatformException(code: 'app_attest_unavailable'); + } + return null; + }); + final container = ProviderContainer( + overrides: [ + communityStorageProvider.overrideWithValue(communities), + communitySnapshotWriterProvider.overrideWithValue((_) async {}), + buzzPushLeaseRevocationStorageProvider.overrideWithValue(storage), + ], + ); + await container.read(communityListProvider.future); + await container + .read(communityListProvider.notifier) + .setPushNotificationsEnabled(community.id, false); + await container.read(buzzPushLeaseRevocationOutboxProvider).trigger(); + expect(calls, 1); + expect(relay.leases.single['active'], isFalse); + expect(relay.leases.single['generation'], 8); + final disabled = (await communities.loadAll()).single; + expect(disabled.pushNotificationsEnabled, isFalse); + expect( + disabled.pushSubscriptionState.pendingTombstoneGeneration, + isNull, + ); + final pending = (await storage.loadAll()).single; + expect(pending.gatewayOnly, isTrue); + expect( + pending.gatewayRevocation?['installationHandle'], + grant['gatewayInstallationHandle'], + ); + container.dispose(); + }, DirectPushHttp()); + }, + ); + + for (final gatewayFails in [true, false]) { + test( + 'independent cleanup survives restart: gateway fails=$gatewayFails', + () async { + await HttpOverrides.runWithHttpOverrides(() async { + final relay = await PushRelayFixture.start( + failMetadata: !gatewayFails, + ); + addTearDown(relay.close); + var fail = true; + var calls = 0; + final grant = _grant( + expiresAt: DateTime.now().millisecondsSinceEpoch ~/ 1000 + 3600, + ); + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'revokePushDelegation') { + calls++; + expect(call.arguments, grant.gatewayRevocationTarget); + if (fail && gatewayFails) + throw PlatformException(code: 'app_attest_unavailable'); + } + return null; + }); + clock.seconds = DateTime.now().millisecondsSinceEpoch ~/ 1000; + BuzzPushLeaseRevocationOutbox makeOutbox() => _outbox( + storage: storage, + clock: clock, + scheduler: scheduler, + publisher: publishBuzzPushLeaseRevocation, + ); + var outbox = makeOutbox(); + await outbox.enqueue( + BuzzPushLeaseRevocationRecord( + relayUrl: relay.httpUrl, + relayOrigin: relay.wsUrl, + memberPubkey: keys.public, + nsec: keys.nsec, + installationId: '0' * 32, + generation: 8, + expiresAt: grant.expiresAt, + attemptCount: 0, + nextAttemptAt: clock.seconds, + gatewayRevocation: grant.gatewayRevocationTarget, + ), + ); + await outbox.trigger(); + outbox.dispose(); + outbox = makeOutbox(); + for (var retry = 0; retry < 2; retry++) { + clock.seconds += 300; + await outbox.trigger(); + } + expect(calls, gatewayFails ? 3 : 1); + expect(relay.leases.length, gatewayFails ? 1 : 0); + final unfinished = (await storage.loadAll()).single; + expect(unfinished.gatewayOnly, gatewayFails); + if (gatewayFails) expect(relay.leases.single['active'], isFalse); + fail = false; + relay.failMetadata = false; + clock.seconds += 300; + await outbox.trigger(); + expect(await storage.loadAll(), isEmpty); + expect(calls, gatewayFails ? 4 : 1); + expect(relay.leases.single['active'], isFalse); + outbox.dispose(); + }, DirectPushHttp()); + }, + ); + } + test( 'native revocation failure retains the exact cleanup journal', () async { @@ -226,14 +374,15 @@ void main() { await outbox.enqueueCommunity(community, readGrants: () async => [grant]); final records = await storage.loadAll(); - expect(records, hasLength(1)); + expect(records, hasLength(2)); + final relay = records.singleWhere((record) => !record.gatewayOnly); expect( - records.single.leaseAddress, + relay.leaseAddress, '${keys.public}|wss://relay.example|${community.pushLeaseInstallationId}', ); - expect(records.single.generation, 6); - expect(records.single.expiresAt, grant.expiresAt); - expect(records.single.relayUrl, 'https://relay.example/'); + expect(relay.generation, 6); + expect(relay.expiresAt, grant.expiresAt); + expect(relay.relayUrl, 'https://relay.example/'); }); test( @@ -259,14 +408,21 @@ void main() { publisher: (_) async => throw StateError('gateway response lost'), ); await outbox.enqueueCommunity(community, readGrants: () async => [grant]); - final before = (await storage.loadAll()).single.gatewayRevocation; + final before = (await storage.loadAll()) + .singleWhere((record) => record.gatewayOnly) + .gatewayRevocation; expect(before?['generation'], 1); expect( before?['installationHandle'], '22222222-2222-4222-8222-222222222222', ); await outbox.trigger(); - expect((await storage.loadAll()).single.gatewayRevocation, before); + expect( + (await storage.loadAll()) + .singleWhere((record) => record.gatewayOnly) + .gatewayRevocation, + before, + ); await storage.replaceAll([]); final sibling = Community.create( name: 'Second', @@ -411,7 +567,9 @@ void main() { await outbox.enqueueCommunity(community, readGrants: () async => [grant]); expect( - (await storage.loadAll()).single.leaseAddress, + (await storage.loadAll()) + .singleWhere((record) => !record.gatewayOnly) + .leaseAddress, '${keys.public}|wss://relay.example|${grant.installationId}', ); }); diff --git a/mobile/test/shared/push/push_relay_fixture.dart b/mobile/test/shared/push/push_relay_fixture.dart new file mode 100644 index 00000000000..6355f073055 --- /dev/null +++ b/mobile/test/shared/push/push_relay_fixture.dart @@ -0,0 +1,104 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:buzz/shared/crypto/nip44.dart'; +import 'package:nostr/nostr.dart' as nostr; + +final relayKeys = nostr.Keys('2' * 64); + +class DirectPushHttp extends HttpOverrides {} + +class PushRelayFixture { + PushRelayFixture(this.server, this.failMetadata); + final HttpServer server; + bool failMetadata; + final sockets = []; + final leases = >[]; + int nip11 = 0; + String get httpUrl => 'http://127.0.0.1:${server.port}'; + String get wsUrl => 'ws://127.0.0.1:${server.port}'; + static Future start({bool failMetadata = false}) async { + final r = PushRelayFixture( + await HttpServer.bind(InternetAddress.loopbackIPv4, 0), + failMetadata, + ); + r.server.listen(r.handle); + return r; + } + + Future handle(HttpRequest request) async { + if (!WebSocketTransformer.isUpgradeRequest(request)) { + nip11++; + request.response.statusCode = failMetadata ? 503 : 200; + request.response.headers.contentType = ContentType.json; + request.response.write( + jsonEncode( + failMetadata + ? {'error': 'fixture-unavailable'} + : { + 'supported_extensions': ['buzz-push-v1'], + 'push': { + 'origin': wsUrl, + 'keys': [ + { + 'id': 'fixture', + 'pubkey': relayKeys.public, + 'current': true, + }, + ], + 'push_kinds': [9, 40002, 45001, 45003], + 'h_grammar': 'uuid-lowercase', + 'class_support': { + 'apns': ['default'], + }, + 'limitation': { + 'max_lease_ttl': 2592000, + 'max_leases_per_pubkey': 16, + 'max_subscriptions_per_lease': 16, + 'max_kinds': 16, + 'max_authors': 20, + 'max_h': 50, + 'max_tag_values': 20, + 'max_ignore': 8, + 'max_content_len': 65536, + 'max_plaintext_len': 32768, + 'max_endpoint_len': 4096, + 'max_string_len': 512, + }, + }, + }, + ), + ); + await request.response.close(); + return; + } + final socket = await WebSocketTransformer.upgrade(request); + sockets.add(socket); + socket.listen((raw) { + final frame = jsonDecode(raw as String) as List; + final event = frame[1] as Map; + if (frame[0] == 'EVENT') { + final payload = + jsonDecode( + nip44Decrypt( + getConversationKey( + relayKeys.secret, + event['pubkey'] as String, + ), + event['content'] as String, + ), + ) + as Map; + leases.add(payload); + } + socket.add(jsonEncode(['OK', event['id'], true, 'accepted-fixture'])); + }); + socket.add(jsonEncode(['AUTH', 'local-fixture-challenge'])); + } + + Future close() async { + for (final s in sockets) { + await s.close(); + } + await server.close(force: true); + } +} From 1ffef0da2cf1dea66f923ead535a796f3981cd1c Mon Sep 17 00:00:00 2001 From: jm Date: Thu, 29 Oct 2026 21:18:23 +0000 Subject: [PATCH 3/7] test(push): satisfy regression test lint checks Signed-off-by: jm Co-authored-by: Codex --- mobile/test/shared/push/push_bootstrap_test.dart | 1 - mobile/test/shared/push/push_lease_revocation_outbox_test.dart | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mobile/test/shared/push/push_bootstrap_test.dart b/mobile/test/shared/push/push_bootstrap_test.dart index 495169859a0..4082a1b5cfc 100644 --- a/mobile/test/shared/push/push_bootstrap_test.dart +++ b/mobile/test/shared/push/push_bootstrap_test.dart @@ -1,4 +1,3 @@ -import 'dart:async'; import 'dart:convert'; import 'package:buzz/shared/push/dev_push_lease.dart'; import 'package:buzz/shared/community/community.dart'; diff --git a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart index 41cc40fbc22..412fe2f6628 100644 --- a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart +++ b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart @@ -252,8 +252,9 @@ void main() { if (call.method == 'revokePushDelegation') { calls++; expect(call.arguments, grant.gatewayRevocationTarget); - if (fail && gatewayFails) + if (fail && gatewayFails) { throw PlatformException(code: 'app_attest_unavailable'); + } } return null; }); From 256b986898372301124cdb719f31e990b3fd040f Mon Sep 17 00:00:00 2001 From: jm Date: Thu, 29 Oct 2026 21:25:11 +0000 Subject: [PATCH 4/7] fix(push): keep gateway cleanup independent of relay credentials Signed-off-by: jm Co-authored-by: Codex --- .../lib/shared/push/push_lease_revocation_outbox.dart | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/mobile/lib/shared/push/push_lease_revocation_outbox.dart b/mobile/lib/shared/push/push_lease_revocation_outbox.dart index a3eb86eb712..2a48d2cea8d 100644 --- a/mobile/lib/shared/push/push_lease_revocation_outbox.dart +++ b/mobile/lib/shared/push/push_lease_revocation_outbox.dart @@ -384,19 +384,22 @@ class BuzzPushLeaseRevocationOutbox { return true; } final nsec = community.nsec; - if (nsec == null || nsec.isEmpty) { + if (!gatewayOnly && (nsec == null || nsec.isEmpty)) { throw StateError( 'Push lease revocation requires a community signing key.', ); } - final decoded = nostr.Nip19.decode(payload: nsec); - final memberPubkey = community.pubkey ?? derivePublicKeyHex(decoded.data); + final memberPubkey = gatewayOnly + ? '0' * 64 + : community.pubkey ?? + derivePublicKeyHex(nostr.Nip19.decode(payload: nsec!).data); final relayUrl = canonicalBuzzPushRelayHttpUrl(community.relayUrl); final relayOrigin = canonicalBuzzPushRelayOrigin(relayUrl); final grants = await (readGrants ?? readBuzzPushEndpointGrants)(); final matching = grants .where((grant) => grant.relayOrigin == relayOrigin) .toList(); + if (gatewayOnly && matching.isEmpty) return false; if (matching.length != 1) { throw StateError( 'Expected exactly one endpoint grant for push lease revocation.', @@ -431,7 +434,7 @@ class BuzzPushLeaseRevocationOutbox { relayUrl: relayUrl, relayOrigin: relayOrigin, memberPubkey: memberPubkey, - nsec: nsec, + nsec: gatewayOnly ? '' : nsec!, installationId: community.pushLeaseInstallationId ?? grant.installationId, generation: highestGeneration + 2, From 60d08a9081eedfee9b3a151625bb2490c75adcd5 Mon Sep 17 00:00:00 2001 From: jm Date: Thu, 29 Oct 2026 22:05:19 +0000 Subject: [PATCH 5/7] test(push): brace gateway failure callback in PR5 Signed-off-by: jm Co-authored-by: Codex --- mobile/test/shared/push/push_bootstrap_test.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mobile/test/shared/push/push_bootstrap_test.dart b/mobile/test/shared/push/push_bootstrap_test.dart index 4082a1b5cfc..562227e81f5 100644 --- a/mobile/test/shared/push/push_bootstrap_test.dart +++ b/mobile/test/shared/push/push_bootstrap_test.dart @@ -81,8 +81,9 @@ void main() { calls++; // This is the production Swift driver's durable pre-request mutation. grant = ''; - if (failGateway) + if (failGateway) { throw PlatformException(code: 'transient_gateway_failure'); + } } return null; }); From 62a129e80da231b08d13a41c1ffeff0048f52389 Mon Sep 17 00:00:00 2001 From: jm Date: Thu, 5 Nov 2026 21:37:11 +0000 Subject: [PATCH 6/7] Bind relay auth in push revocation restart test Signed-off-by: jm Co-authored-by: Codex --- .../test/shared/push/push_lease_revocation_outbox_test.dart | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart index 44ebec80497..af07b6ad649 100644 --- a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart +++ b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart @@ -262,12 +262,15 @@ void main() { } return null; }); + final auth = _AssertingRelayAuth(); + addTearDown(auth.dispose); clock.seconds = DateTime.now().millisecondsSinceEpoch ~/ 1000; BuzzPushLeaseRevocationOutbox makeOutbox() => _outbox( storage: storage, clock: clock, scheduler: scheduler, - publisher: publishBuzzPushLeaseRevocation, + publisher: (record) => + publishBuzzPushLeaseRevocation(record, relayAuth: auth), ); var outbox = makeOutbox(); await outbox.enqueue( From 61d992d80558b8ca242dcbeda6ac194f0543e075 Mon Sep 17 00:00:00 2001 From: jm Date: Thu, 5 Nov 2026 22:10:16 +0000 Subject: [PATCH 7/7] Bind hosted auth in PR5 push bootstrap restart test Signed-off-by: jm Co-authored-by: Codex --- mobile/test/shared/push/push_bootstrap_test.dart | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/mobile/test/shared/push/push_bootstrap_test.dart b/mobile/test/shared/push/push_bootstrap_test.dart index 10ebcdef203..33cdf3a1adf 100644 --- a/mobile/test/shared/push/push_bootstrap_test.dart +++ b/mobile/test/shared/push/push_bootstrap_test.dart @@ -5,6 +5,8 @@ import 'package:buzz/shared/push/dev_push_lease.dart'; import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_provider.dart'; import 'package:buzz/shared/community/community_storage.dart'; +import 'package:buzz/shared/hosted/builderlab_account.dart'; +import 'package:buzz/shared/hosted/hosted_relay_auth.dart'; import 'package:buzz/shared/push/push_bootstrap.dart'; import 'package:buzz/shared/push/push_bridge.dart'; import 'package:buzz/shared/push/push_subscription.dart'; @@ -51,6 +53,8 @@ void main() { final journal = BuzzPushLeaseRevocationStorage( secure: FakeSecureStorage(), ); + final auth = HostedRelayAuth(BuilderlabAccountClient(), enabled: false); + addTearDown(auth.dispose); var grant = 'opaque-before-revoke'; var calls = 0; var nativeReads = 0; @@ -96,12 +100,16 @@ void main() { }); final overrides = [ savedPrefsProvider.overrideWithValue(prefs), + hostedRelayAuthProvider.overrideWithValue(auth), communityStorageProvider.overrideWithValue(storage), communitySnapshotWriterProvider.overrideWithValue((_) async {}), buzzPushLeaseRevocationOutboxProvider.overrideWith((ref) { final outbox = BuzzPushLeaseRevocationOutbox( storage: journal, - publisher: publishBuzzPushLeaseRevocation, + publisher: (record) => publishBuzzPushLeaseRevocation( + record, + relayAuth: ref.read(hostedRelayAuthProvider), + ), now: tester.binding.clock.now, jitter: () => 0, );