mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
Lets clients whose clocks are up to 120 s off sign in to NIP-FI communities and stay connected. **Relay** - NIP-42 AUTH and NIP-98 HTTP Auth accept `created_at` within ±120 s, using a shared `buzz_auth::TIMESTAMP_TOLERANCE_SECS`. This covers relay login, audio admission, bridge, admin, invites, NIP-FI policy and Git. - `DEFAULT_REPLAY_TTL_SECS` goes from 120 to 250 s: a 2 × 120 s window, plus 1 s for the inclusive whole-second bounds, plus a 9 s budget for the clock difference between relay pods. A compile-time assert checks the arithmetic. The 9 s is an operational assumption about NTP-synced pods, and the doc comment says so. No `deploy/` override exists. - Media (kind 24242): - Both modes accept `created_at` up to 120 s in the future and an `expiration` greater than `now − 120`. - Strict: the 120 s age limit and the 60 s lifetime cap. - Permissive: keeps its 3600 s age allowance and has no lifetime cap. - `buzz-auth` and `buzz-media` read the time through a `wall_now()` that tests can pin (a `#[cfg(test)]` thread-local), so boundary tests are exact. - Git transport: comments only. It still reuses one proof per session, so the reuse window now matches ±120 s. **CLI** - The desktop-provider lane asks the desktop app for the assertion every time and keeps no copy, so the desktop's cache owns each token's deadline. It looks the token up again after signing and sends that one, so a provider may hand out a new token on every call. - The direct-mint cache sets its deadline to `min(request_start + (exp − iat), receipt + (exp − local_now))`, on a monotonic clock. `request_start` is when the attempt that got the reply was sent, not the start of the retry loop. - An assertion with no local lifetime left is never returned or sent. The cache asks again, up to 3 times, then fails with an auth error that points at the computer's clock. An assertion without a readable `iat` is refused. `iat` may be fractional (a NumericDate); the lifetime is `max(0, floor(exp − iat))` whole seconds. **Cache reuse (CLI, Flutter, iOS):** each cached token records when it arrived on both the monotonic and the wall clock. It is reused only while `max(monotonic elapsed, wall elapsed)` since arrival is under its budget (`refresh point − receipt`, on the monotonic clock). A negative wall elapsed counts as 0. The monotonic clocks used here stop while the device sleeps, so the wall clock ends reuse after a sleep; setting the wall clock back can't stretch a token, because the monotonic bound still applies. **Mobile** - Flutter `HostedRelayAuth`: the same lifetime rule, on a monotonic clock, for async acquisition and for the synchronous `cachedHeaders` media path. A token with no local lifetime left is never sent: issuance is retried up to 3 times, then fails as `unavailable`. A token without a readable `iat` fails as `invalidResponse`. - Flutter refusal hint: the account client reads `Date` when a 403's headers arrive, before the body (`boundedHttpResponse` gains an `onHeaders` callback). The 403 stays `AccountFailure.denied` even if its body is then lost, late or too large. The hint is stored with the refusal it explains (`HostedRelayAuth.failureClockHint`), cleared when that community next gets a token or the account session changes, and left alone by other communities' issuance. The account client records a 403's hint only for the acquisition whose own request was refused (`BuilderlabAccountClient.observingRefusals`), so an unrelated account call, such as the organization key backup, never supplies a sign-in's hint. When the offset is over 115 s, the reconnect and organization banners add "Your device's clock looks about N minutes off, which can cause this. Check your date and time settings." - iOS `BuzzRelayAssertionIssuer`: the same lifetime rule, on `systemUptime`. An assertion without a readable `iat` is refused. - iOS push enrollment: a new grant's window starts 120 s in the past, so `not_before = now − 120` and `expires_at = now − 120 + lifetime`. A fast phone then neither signs a `not_before` the gateway hasn't reached nor goes over its 30-day maximum. A resumed journal resubmits the installation expiry it already attested, byte for byte. The delegation, which is signed fresh each time, expires at the earlier of that expiry and `not_before + lifetime`, so a journal written by an older client on a fast phone still gets a grant the gateway accepts. The saved grant records the delegation's expiry. - Flutter and iOS already sign a fresh proof with a `nonce` on every issuer attempt, so their retries needed no change. **Specs:** NIP-FA proof bounds (120 s old / 120 s future), plus NIP-FI Git (`±120s`), media freshness, the media read residual and the media trace row. `desktop/` is untouched. Not exercised live: Git clone/push, audio join and push delivery with a skewed client clock. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com>
348 lines
15 KiB
Swift
348 lines
15 KiB
Swift
import Foundation
|
|
import ImageIO
|
|
import Testing
|
|
|
|
@testable import BuzzPushKit
|
|
|
|
/// An assertion issued when the tests start, with a 300 s lifetime.
|
|
private let testAssertionIssuedAt = Int(Date().timeIntervalSince1970)
|
|
private let testAssertion: String = {
|
|
let claims = try! JSONSerialization.data(withJSONObject: [
|
|
"iat": testAssertionIssuedAt, "exp": testAssertionIssuedAt + 300,
|
|
])
|
|
let payload = claims.base64EncodedString()
|
|
.replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_")
|
|
.replacingOccurrences(of: "=", with: "")
|
|
return "e30.\(payload).c2ln"
|
|
}()
|
|
|
|
@Suite("Native notification avatar decoding")
|
|
struct BuzzNotificationAvatarLoaderTests {
|
|
@Test("Avatar proofs preserve IPv6 brackets and explicit ports")
|
|
func signedServerAuthority() throws {
|
|
let key = String(repeating: "0", count: 63) + "1"
|
|
let account = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
|
|
for authority in ["[::1]:3000", "[2001:db8::1]", "relay.example:443", "relay.example"] {
|
|
let url = try #require(URL(string: "https://\(authority)/media/avatar.png"))
|
|
let header = try BuzzNotificationAvatarLoader.authorization(url: url, key: key, account: account)
|
|
let data = try #require(Data(base64Encoded: String(header.dropFirst(6))))
|
|
let event = try JSONDecoder().decode(VerifiedNostrEvent.self, from: data)
|
|
#expect(event.tags.contains(["server", authority]))
|
|
#expect(event.kind == 24242)
|
|
#expect(event.hasValidIDAndSignature())
|
|
}
|
|
}
|
|
|
|
@Test("Relay media uses canonical hosts and default ports without trusting other origins")
|
|
func mediaOrigins() throws {
|
|
let hash = String(repeating: "a", count: 64)
|
|
for (relay, media, expected) in [
|
|
("wss://relay.example:443", "https://relay.example", true),
|
|
("wss://relay.example", "https://RELAY.EXAMPLE:443", true),
|
|
("ws://relay.example:80", "http://RELAY.EXAMPLE", true),
|
|
("wss://relay.example:8443", "https://relay.example:8443", true),
|
|
("wss://relay.example", "https://relay.example:8443", false),
|
|
("wss://relay.example", "http://relay.example", false),
|
|
("wss://relay.example", "https://other.example", false),
|
|
] {
|
|
let scope = try #require(
|
|
BuzzNotificationCacheScope(
|
|
community: PushLeaseCommunity(
|
|
id: "community", name: "Test", relayUrl: relay, pubkey: "account", policies: [],
|
|
notificationSessionID: "session")))
|
|
let url = try #require(URL(string: "\(media)/media/\(hash).png"))
|
|
#expect(
|
|
BuzzNotificationAvatarLoader.thumbnailURLs(url, scope: scope).map(\.lastPathComponent)
|
|
== (expected ? ["\(hash).thumb.webp", "\(hash).thumb.jpg"] : []))
|
|
}
|
|
}
|
|
|
|
@Test("Animated avatar selects the poster without fetching the animation")
|
|
func animatedPoster() throws {
|
|
let source =
|
|
"https://images.example/poster.png#buzz-anim=https%3A%2F%2Fimages.example%2Fanimation.apng"
|
|
#expect(
|
|
BuzzNotificationAvatarLoader.posterURL(source)?.absoluteString
|
|
== "https://images.example/poster.png")
|
|
#expect(BuzzNotificationAvatarLoader.posterURL("file:///private/avatar.png") == nil)
|
|
}
|
|
|
|
@Test("Raster decoder produces a bounded PNG and rejects non-image data")
|
|
func raster() throws {
|
|
let bytes = try #require(
|
|
Data(
|
|
base64Encoded:
|
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX1sAAAAASUVORK5CYII="
|
|
))
|
|
let png = try BuzzNotificationAvatarLoader.decode(bytes)
|
|
let source = try #require(CGImageSourceCreateWithData(png as CFData, nil))
|
|
let properties = try #require(
|
|
CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any])
|
|
#expect(properties[kCGImagePropertyPixelWidth] as? Int == 1)
|
|
#expect(properties[kCGImagePropertyPixelHeight] as? Int == 1)
|
|
#expect(png.count <= BuzzNotificationCache.maximumAvatarBytes)
|
|
#expect(throws: BuzzNotificationCacheError.self) {
|
|
try BuzzNotificationAvatarLoader.decode(Data("not an image".utf8))
|
|
}
|
|
}
|
|
|
|
@Test("A scope revoked while the assertion is issued never starts the signed download")
|
|
func scopeRevokedDuringAssertionIssuance() async throws {
|
|
let key = String(repeating: "0", count: 63) + "1"
|
|
let account = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
|
|
let scope = try #require(
|
|
BuzzNotificationCacheScope(
|
|
community: PushLeaseCommunity(
|
|
id: "community", name: "Test", relayUrl: "wss://relay.org.example", pubkey: account,
|
|
policies: [], notificationSessionID: "session")))
|
|
let configuration = URLSessionConfiguration.ephemeral
|
|
configuration.protocolClasses = [AssertionIssuanceStub.self]
|
|
let state = AvatarScopeState()
|
|
AssertionIssuanceStub.onRequest = { state.revoke() }
|
|
defer { AssertionIssuanceStub.onRequest = nil }
|
|
let issuer = BuzzRelayAssertionIssuer(
|
|
session: URLSession(configuration: configuration),
|
|
loadSession: {
|
|
BuzzOrganizationSession(
|
|
origin: "https://identity.org.example", credential: "session-credential",
|
|
relayHosts: ["relay.org.example"])
|
|
})
|
|
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
|
|
UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: directory) }
|
|
let loader = BuzzNotificationAvatarLoader(
|
|
directory: directory, privateKey: { _ in key }, isCurrent: { _ in state.isCurrent },
|
|
assertionIssuer: issuer)
|
|
loader.startDownload = { _, _, _, completion in
|
|
state.recordDownload()
|
|
completion(.failure(URLError(.cancelled)))
|
|
}
|
|
|
|
let result = await withCheckedContinuation { continuation in
|
|
loader.load(
|
|
source: "https://relay.org.example/media/\(String(repeating: "a", count: 64)).png",
|
|
scope: scope
|
|
) { continuation.resume(returning: $0) }
|
|
}
|
|
|
|
guard case .failure(BuzzNotificationCacheError.revoked) = result else {
|
|
Issue.record("Expected a revoked failure, got \(result)")
|
|
return
|
|
}
|
|
#expect(state.downloads == 0)
|
|
}
|
|
|
|
@Test("An organization relay avatar is fetched with the issued assertion")
|
|
func relayAvatarCarriesAssertion() async throws {
|
|
let key = String(repeating: "0", count: 63) + "1"
|
|
let account = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
|
|
let scope = try #require(
|
|
BuzzNotificationCacheScope(
|
|
community: PushLeaseCommunity(
|
|
id: "community", name: "Test", relayUrl: "wss://relay.org.example", pubkey: account,
|
|
policies: [], notificationSessionID: "session")))
|
|
let configuration = URLSessionConfiguration.ephemeral
|
|
configuration.protocolClasses = [AssertionIssuanceStub.self]
|
|
let issuer = BuzzRelayAssertionIssuer(
|
|
session: URLSession(configuration: configuration),
|
|
loadSession: {
|
|
BuzzOrganizationSession(
|
|
origin: "https://identity.org.example", credential: "session-credential",
|
|
relayHosts: ["relay.org.example"])
|
|
})
|
|
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
|
|
UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: directory) }
|
|
let loader = BuzzNotificationAvatarLoader(
|
|
directory: directory, privateKey: { _ in key }, isCurrent: { _ in true },
|
|
assertionIssuer: issuer)
|
|
let requests = AvatarRequests()
|
|
loader.startDownload = { request, _, _, completion in
|
|
requests.record(request)
|
|
completion(.failure(URLError(.cancelled)))
|
|
}
|
|
|
|
_ = await withCheckedContinuation { continuation in
|
|
loader.load(
|
|
source: "https://relay.org.example/media/\(String(repeating: "a", count: 64)).png",
|
|
scope: scope
|
|
) { continuation.resume(returning: $0) }
|
|
}
|
|
|
|
let request = try #require(requests.first)
|
|
#expect(
|
|
request.value(forHTTPHeaderField: "Nostr-Federated-Identity")
|
|
== "Bearer \(testAssertion)")
|
|
#expect(request.value(forHTTPHeaderField: "Authorization") != nil)
|
|
}
|
|
|
|
@Test("A hosted relay avatar is fetched without an assertion until the relay challenges")
|
|
func hostedAvatarAnswersChallenge() async throws {
|
|
let key = String(repeating: "0", count: 63) + "1"
|
|
let account = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
|
|
let scope = try #require(
|
|
BuzzNotificationCacheScope(
|
|
community: PushLeaseCommunity(
|
|
id: "community", name: "Test", relayUrl: "wss://team.communities.example",
|
|
pubkey: account, policies: [], notificationSessionID: "session")))
|
|
let configuration = URLSessionConfiguration.ephemeral
|
|
configuration.protocolClasses = [HostedIssuanceStub.self]
|
|
let issuer = BuzzRelayAssertionIssuer(
|
|
session: URLSession(configuration: configuration), loadSession: { nil },
|
|
loadHostedSession: {
|
|
BuzzOrganizationSession(
|
|
origin: "https://app.example", credential: "hosted-credential", relayHosts: [],
|
|
relayDomains: ["communities.example"], communityDomain: "communities.example")
|
|
})
|
|
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
|
|
UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: directory) }
|
|
let loader = BuzzNotificationAvatarLoader(
|
|
directory: directory, privateKey: { _ in key }, isCurrent: { _ in true },
|
|
assertionIssuer: issuer)
|
|
let requests = AvatarRequests()
|
|
loader.startDownload = { request, _, _, completion in
|
|
requests.record(request)
|
|
let challenged = request.value(forHTTPHeaderField: "Nostr-Federated-Identity") == nil
|
|
completion(.failure(challenged ? BuzzNotificationDownload.Failure.challenged : URLError(.cancelled)))
|
|
}
|
|
|
|
_ = await withCheckedContinuation { continuation in
|
|
loader.load(
|
|
source: "https://team.communities.example/media/\(String(repeating: "a", count: 64)).png",
|
|
scope: scope
|
|
) { continuation.resume(returning: $0) }
|
|
}
|
|
|
|
#expect(requests.all.map { $0.value(forHTTPHeaderField: "Nostr-Federated-Identity") }
|
|
== [nil, "Bearer \(testAssertion)"])
|
|
#expect(requests.all.allSatisfy { $0.value(forHTTPHeaderField: "Authorization") != nil })
|
|
}
|
|
|
|
@Test("An avatar fetched with an assertion from a replaced organization session is refused")
|
|
func replacedOrganizationSessionRefusesAvatar() async throws {
|
|
let key = String(repeating: "0", count: 63) + "1"
|
|
let account = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
|
|
let scope = try #require(
|
|
BuzzNotificationCacheScope(
|
|
community: PushLeaseCommunity(
|
|
id: "community", name: "Test", relayUrl: "wss://relay.org.example", pubkey: account,
|
|
policies: [], notificationSessionID: "session")))
|
|
let configuration = URLSessionConfiguration.ephemeral
|
|
configuration.protocolClasses = [AssertionIssuanceStub.self]
|
|
let sessions = OrganizationSessions()
|
|
let issuer = BuzzRelayAssertionIssuer(
|
|
session: URLSession(configuration: configuration), loadSession: { sessions.current })
|
|
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
|
|
UUID().uuidString)
|
|
defer { try? FileManager.default.removeItem(at: directory) }
|
|
let loader = BuzzNotificationAvatarLoader(
|
|
directory: directory, privateKey: { _ in key }, isCurrent: { _ in true },
|
|
assertionIssuer: issuer)
|
|
let png = try #require(
|
|
Data(
|
|
base64Encoded:
|
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX1sAAAAASUVORK5CYII="
|
|
))
|
|
loader.startDownload = { _, _, _, completion in
|
|
// The member signs in again while the avatar is in flight; the community is unchanged.
|
|
sessions.replace()
|
|
completion(.success(png))
|
|
}
|
|
|
|
let result = await withCheckedContinuation { continuation in
|
|
loader.load(
|
|
source: "https://relay.org.example/media/\(String(repeating: "a", count: 64)).png",
|
|
scope: scope
|
|
) { continuation.resume(returning: $0) }
|
|
}
|
|
|
|
guard case .failure(BuzzNotificationCacheError.revoked) = result else {
|
|
Issue.record("Expected a revoked failure, got \(result)")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
private final class AvatarRequests: @unchecked Sendable {
|
|
private let lock = NSLock()
|
|
private var requests: [URLRequest] = []
|
|
|
|
var first: URLRequest? { lock.withLock { requests.first } }
|
|
var all: [URLRequest] { lock.withLock { requests } }
|
|
func record(_ request: URLRequest) { lock.withLock { requests.append(request) } }
|
|
}
|
|
|
|
private final class OrganizationSessions: @unchecked Sendable {
|
|
private let lock = NSLock()
|
|
private var credential = "session-credential"
|
|
|
|
var current: BuzzOrganizationSession {
|
|
lock.withLock {
|
|
BuzzOrganizationSession(
|
|
origin: "https://identity.org.example", credential: credential,
|
|
relayHosts: ["relay.org.example"])
|
|
}
|
|
}
|
|
func replace() { lock.withLock { credential = "replacement-credential" } }
|
|
}
|
|
|
|
private final class AvatarScopeState: @unchecked Sendable {
|
|
private let lock = NSLock()
|
|
private var current = true
|
|
private var started = 0
|
|
|
|
var isCurrent: Bool { lock.withLock { current } }
|
|
var downloads: Int { lock.withLock { started } }
|
|
func revoke() { lock.withLock { current = false } }
|
|
func recordDownload() { lock.withLock { started += 1 } }
|
|
}
|
|
|
|
/// Answers the organization's assertion issuer, running `onRequest` while issuance is in flight.
|
|
private final class HostedIssuanceStub: URLProtocol, @unchecked Sendable {
|
|
override class func canInit(with request: URLRequest) -> Bool { true }
|
|
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
|
|
|
override func startLoading() {
|
|
let account = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
|
|
let value: [String: Any] =
|
|
request.url?.path == "/api/goose/v1/buzz/nostr-identities/current"
|
|
? ["identity": ["pubkey_hex": account]]
|
|
: [
|
|
"assertion": testAssertion, "nostr_pubkey": account,
|
|
"expires_at": testAssertionIssuedAt + 300,
|
|
]
|
|
let body = try! JSONSerialization.data(withJSONObject: value)
|
|
let response = HTTPURLResponse(
|
|
url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
|
|
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
|
client?.urlProtocol(self, didLoad: body)
|
|
client?.urlProtocolDidFinishLoading(self)
|
|
}
|
|
|
|
override func stopLoading() {}
|
|
}
|
|
|
|
private final class AssertionIssuanceStub: URLProtocol, @unchecked Sendable {
|
|
nonisolated(unsafe) static var onRequest: (() -> Void)?
|
|
|
|
override class func canInit(with request: URLRequest) -> Bool { true }
|
|
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
|
|
|
override func startLoading() {
|
|
Self.onRequest?()
|
|
let body = try! JSONSerialization.data(withJSONObject: [
|
|
"assertion": testAssertion,
|
|
"nostr_pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
|
|
"expires_at": testAssertionIssuedAt + 300,
|
|
])
|
|
let response = HTTPURLResponse(
|
|
url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
|
|
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
|
client?.urlProtocol(self, didLoad: body)
|
|
client?.urlProtocolDidFinishLoading(self)
|
|
}
|
|
|
|
override func stopLoading() {}
|
|
}
|