diff --git a/Documentation/Compatibility/FixtureSources.md b/Documentation/Compatibility/FixtureSources.md index f32678e..abae042 100644 --- a/Documentation/Compatibility/FixtureSources.md +++ b/Documentation/Compatibility/FixtureSources.md @@ -64,3 +64,24 @@ is not committed as golden data. See the repository [fixture license policy](../Planning/FixtureLicensePolicy.md) and [vector inventory](VectorInventory.md) for the source boundary and approved families. + +## Recorded TypeScript auth vectors + +The BRC-103 and BRC-104 vectors in +`Tests/BSVAuthTests/BRC103/TypeScriptAuthVectors.swift` and the collation +digests in `Tests/BSVAuthTests/Certificates/LocaleCompareOrderTests.swift` are +outputs recorded from running permissively licensed source. They are not copied +upstream fixtures and are not under the conformance fixture root, so they have no +manifest fragment. Their provenance: + +| Item | Value | +| --- | --- | +| Source | `ts-stack` repository, `packages/sdk`, `@bsv/sdk` 4.1.1 | +| Revision | `3b1abc5691c0848eb00eaf5e8f018e8a7a26d5f1` | +| License | Apache-2.0, from relicensing commit `4760b26d0` (2026-11-11), an ancestor of the revision; NOTICE "Copyright 2020-2026 BSV Association" | +| Generator | `gen.ts`, `det.ts`, `toswift.py` and `collate-vec.ts` in [TypeScriptAuthVectors.md](TypeScriptAuthVectors.md), run with Bun 1.4.4; the collation output was also checked with Node 22.23.4 | +| Inputs | Chosen in this repository: private keys 3, 7 and 11, a SHA-256 counter random stream, certificate fields and request targets | +| Transformation | Program output written verbatim into Swift string literals by `toswift.py`; no TypeScript source text is copied | + +Regenerate them only from the pinned revision, and record a new revision here +when they change. diff --git a/Documentation/Compatibility/GoSDK-v1.3.3-Defects.md b/Documentation/Compatibility/GoSDK-v1.3.3-Defects.md index df4d98f..dd44cb7 100644 --- a/Documentation/Compatibility/GoSDK-v1.3.3-Defects.md +++ b/Documentation/Compatibility/GoSDK-v1.3.3-Defects.md @@ -1075,9 +1075,11 @@ Suggested correction: store one bounded pending request on the session, compare the exact response with that request, and clear the request only after successful signature and certificate validation. -Swift handling: `PeerAuthenticator` stores one pending request per session, -rejects unsolicited or mismatched responses, and clears the request only after -successful response-signature verification. +Swift handling: `PeerAuthenticator` keeps up to 16 open requests per session +and direction, as `@bsv/sdk` 4.1.1 does (`Peer.ts:474-478`). After the +response signature verifies, it binds the response to the oldest open request +it fits, in the order of `Peer.ts:1236-1241`, rejects unsolicited or +mismatched responses, and clears that request. ### GO-063: The requested-certificate HTTP header is not signed @@ -1096,7 +1098,10 @@ Suggested correction: include a canonical hash of the requested-certificate set in the signed payload, or send a signed BRC-103 certificate-request message. -Swift handling: the HTTP frame codec rejects this header. Callers use the +Swift handling: `@bsv/sdk` 4.1.1 sends and reads the same unsigned header, so +the HTTP frame codec reads and writes it for interoperability (COMP-059). +`PeerAuthenticator` does not act on a requested set in a general message, as +`Peer.processGeneralMessage` does not. Callers that need a request use the signed BRC-103 certificate-request message. ### GO-064: Storage resolution does not bind advertisements to the requested UHRP identifier diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index 0c0d497..85dae89 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -48,7 +48,7 @@ behind the general rule. | COMP-038 | Go wallet request structs encode zero-value artifacts: an omitted or JSON `null` counterparty means an operation-specific default, and an identity-key request may carry `protocolID: [0, ""]`. Treating every `null` as absence would also hide malformed known fields. | Swift accepts missing or `null` counterparty only at the flattened request field and maps it to that operation's `.self` or `.anyone` default. It accepts the exact zero protocol tuple only with `identityKey: true` and no contradictory fields. Canonical output emits the explicit counterparty or only `identityKey: true`; `null` for other known fields is rejected. | This imports Go-generated requests without making the typed JSON model broadly nullable or preserving meaningless zero fields. Tests cover each operation's default, canonical re-encoding, the exact identity artifact, contradictions, and rejected known-field nulls. | | COMP-039 | Go auto-detects Extended Format from the bytes following a transaction version, which makes a valid raw zero-input transaction whose locktime begins with the marker byte sequence ambiguous. BRC-128 prose also shows one extra zero while its table and Go use the six-byte `00 00 00 00 00 EF` marker. | Swift requires callers to select `.raw` or `.extended`, emits and accepts the six-byte marker, and never auto-detects. Extended source amounts remain the eight-byte values selected by COMP-003. | Explicit selection preserves every raw transaction byte string and transaction ID while retaining canonical Go-compatible Extended Format. Tests cover the raw collision, literal marker mismatch/truncation, eight-byte amounts, canonical and permissive CompactSize policies, and bidirectional pinned-Go encoding. | | COMP-040 | An ARC POST can reach the provider before the client receives or validates its response. Official ARC submission success requires `status`, `title`, `timestamp`, `txid`, and `txStatus`. Status lookup success requires `timestamp`, `txid`, and `txStatus`, but it does not require `status` or `title`. A redirect, oversized response, malformed semantic field, or wrong transaction ID does not prove rejection. | Swift never retries an ARC POST. It validates operation-specific fields without removing control or format characters from semantic values. It returns explicit rejection only for a valid matching ARC rejection or a documented ARC validation status. Every other response failure after POST begins returns `uncertainDelivery` with the local transaction ID and a typed cause. | This prevents unsafe automatic resubmission and prevents malformed text from becoming a valid status or proof field. Tests cover preflight failure with zero POSTs, cancellation, timeout, transport loss, redirects, response limits, malformed responses, wrong transaction IDs, official response shapes, semantic-field injection, and explicit rejection. | -| COMP-041 | BRC-52 and Go use display-order revocation transaction IDs. Go also accepts or produces some values that do not satisfy one strict bounded certificate policy. JSON object keys use Unicode string equality, while the binary certificate orders field names by raw UTF-8 bytes. | Swift uses display-order revocation transaction IDs, canonical Base64, canonical CompactSize, strict complete DER, low-S verification, raw UTF-8 field-name order when writing (any order with no repeated name when reading, because TypeScript writes `localeCompare` order; COMP-048), and explicit size limits. It rejects byte-distinct field names that are canonically equivalent in Unicode so JSON output cannot silently replace a signed field. Certificate verification is cryptographic only. The caller must check the revocation output before it trusts a certificate. | Canonical values stay interoperable. Strict parsing prevents ambiguous fields, trailing data, hidden signature bytes, and lossy JSON conversion. Tests cover binary and JSON boundaries, Unicode-equivalent names, field order, signature binding, field encryption, verifier projection, all-or-nothing failure, and secret redaction. | +| COMP-041 | BRC-52 and Go use display-order revocation transaction IDs. Go also accepts or produces some values that do not satisfy one strict bounded certificate policy. JSON object keys use Unicode string equality. The Go SDK orders binary certificate fields by raw UTF-8 bytes; `@bsv/sdk` 4.1.1 signs and verifies them in JavaScript `localeCompare` order (`Certificate.ts:290`), so a certificate with field names such as `Zip` and `age` signed by one fails to verify in the other. | Swift uses display-order revocation transaction IDs, canonical Base64, canonical CompactSize, strict complete DER, low-S verification, and explicit size limits. `CertificateEngine.issue` signs the fields in `localeCompare` order, using the ICU root collation that Node and Bun use, which `LocaleCompareOrder` reproduces exactly for printable ASCII. `CertificateEngine.issue` refuses field names outside printable ASCII with `CertificateFieldNameError.nonASCII`, because ICU orders accented letters among ASCII ones and ignores control characters, so the order TypeScript verifies could not be predicted. BRC-103 exchange and `CertificateEngine` accept a signature over either the `localeCompare` order or the UTF-8 byte order. The `BSVWallet` binary codec writes raw UTF-8 field-name order and reads fields in any order with no repeated name (COMP-048); `Certificate.verifySignature` still uses byte order. It rejects byte-distinct field names that are canonically equivalent in Unicode so JSON output cannot silently replace a signed field. Certificate verification is cryptographic only. The caller must check the revocation output before it trusts a certificate. | Canonical values stay interoperable with both SDKs; certificates Swift issues verify in TypeScript, and Go and earlier Swift certificates still verify. Strict parsing prevents ambiguous fields, trailing data, hidden signature bytes, and lossy JSON conversion. Tests cover binary and JSON boundaries, Unicode-equivalent names, the order against Bun for all printable ASCII pairs, a TypeScript-signed mixed-case certificate, both signature orders, signature binding, field encryption, verifier projection, all-or-nothing failure, secret redaction, and refusal of non-ASCII names. Certificates with non-ASCII names signed elsewhere are still verified in both orders, and TypeScript hosts with a non-English default locale may order names differently. | | COMP-042 | Go BIP-276 accepts a broader prefix domain and re-encodes parsed values before checksum comparison. Its BRC-307 enriched-inscription path omits the enriched suffix, and its specific-ordinal helper has unsafe range artifacts. | Swift emits and requires canonical lowercase BIP-276 text with a restricted lowercase prefix. Swift emits the BRC-307 enriched `OP_RETURN` suffix and rejects invalid input indexes, satoshi ranges, missing source data, and arithmetic overflow before transaction mutation. | The Swift rules preserve canonical protocol output and prevent ambiguous text or partial transaction changes. Tests cover every size boundary, checksum, prefix deviation, push boundary, ordinal boundary, atomic failure, and pinned-Go canonical BIP-276 behavior. | | COMP-043 | Go and TypeScript place Bitcoin Signed Message, ECIES, BIP-32, and BIP-39 in explicit compatibility packages, while they differ on raw Base58 placement. | Swift exposes the four common families only through the opt-in `BSVCompat` product, outside the modern `BSV` umbrella. Raw Base58 remains a bounded primitive in `BSVCore`; Address, WIF, Base58Check, BRC-42, BRC-94, and BRC-140 remain in `BSVKeys`. | This preserves the common package boundary without declaring a primitive utility obsolete where the reference SDKs disagree. Structure and compile tests verify module ownership and prevent accidental umbrella re-export. | | COMP-044 | Go places wallet-independent PushDrop construction, decoding, and transaction signing in one package. The Swift target graph cannot place transaction signing in `BSVScript` without a dependency cycle. | Swift keeps wallet-independent PushDrop construction and decoding in `BSVScript`. It keeps transaction signing in `BSVTransaction`. | The split prevents dependency cycles and preserves Go and BRC behavior. Unit and pinned-Go tests cover construction, decoding, and transaction signing across the module boundary. | @@ -59,15 +59,15 @@ behind the general rule. | COMP-049 | Pinned Go transaction JSON gives `hex` priority and ignores inconsistent expanded fields. Without `hex`, it discards inputs and outputs. It accepts unknown and duplicate keys, missing component fields, short or uppercase input transaction IDs, and unsafe `uint64` JSON numbers. Raw empty collections marshal as `null`. | Swift requires one complete bounded object. It rejects unknown and duplicate keys, invalid UTF-8, noncanonical hex and IDs, trailing values, and integers above 9,007,199,254,740,991. The transaction ID and every expanded field must match the raw transaction in `hex`. It emits canonical `null` empty collections and accepts `null` or `[]` as empty. | Canonical compact documents remain byte-compatible in both directions. Construction metadata is not part of this raw-transaction JSON format. Persistent pinned-Go tests record the shared format and the lossy Go differences. | | COMP-050 | Go wallet-wire processors return malformed requests as transport errors and pass the originator to each wallet method; `@bsv/sdk` 4.1.1 answers every failure in-band. | Swift provides bounded transport-neutral processors and transceivers with a required originator authorizer. Every processor failure, including unknown calls and malformed requests, is an error frame with the TypeScript message. | A TypeScript transceiver must see an error frame, not a dead transport, and must be able to fall back after the call-29 probe. See [COMP-050](Rulings/COMP-050-Wallet-Wire-Substrates.md). | | COMP-051 | Go's interpreter debugger stores mutable callback lists and clones mutable VM state; its declared rewind option is unimplemented. | Swift uses an opt-in bounded immutable `Sendable` event stream, redacts descriptions/reflection, and omits rewind. | Preserves deterministic lifecycle observability without exposing mutable execution state or creating callback races. | -| COMP-052 | Pinned Go auth accepts variable nonce lengths, can lose random-source failures, authenticates an unsigned initial request, and does not enforce the expected peer identity. BRC-103 uses version `0.1`, while some BRC-104 material shows `1.0`. | Swift emits and accepts BRC-103 version `0.1`, accepts 32-byte nonces and the exact 48-byte Go form, propagates random failures, binds the expected peer, and authenticates a responder only after a signed general message. The transport-neutral BRC-104 payload has no separate version field. | Canonical shared messages and payloads remain interoperable. Strict JSON, low-S DER, replay checks, cancellation, session limits, and payload limits prevent the pinned defects and ambiguous input from entering session state. | +| COMP-052 | Pinned Go auth accepts variable nonce lengths, can lose random-source failures, authenticates an unsigned initial request, and does not enforce the expected peer identity. BRC-103 uses version `0.1`, while some BRC-104 material shows `1.0`. `@bsv/sdk` 4.1.1 requires 48-byte session nonces and signs an empty body as -1. | Swift emits and accepts BRC-103 version `0.1`, creates 48-byte session nonces and 32-byte message nonces, accepts 32- and 48-byte peer session nonces, propagates random failures, binds the expected peer, and authenticates a responder only after a signed general or certificate message. BRC-104 payloads sign an absent or empty body as -1 and use TypeScript content-type normalisation and limits. Signed headers are sorted in `localeCompare` order (`AuthFetch.ts:740`), every `x-bsv-auth` name is left unsigned, and signed values must be printable ASCII without leading or trailing spaces. Swift refuses to build or accept a status outside 200 to 599, a method that is not 1 to 32 uppercase token characters, or a path and query over 8192 characters, as `AuthFetch` and the middleware do. | Interoperates with `@bsv/sdk` 4.1.1 in both directions and keeps canonical Go messages. Strict JSON, low-S DER, replay checks, cancellation, session limits, and payload limits prevent the pinned defects and ambiguous input from entering session state. | | COMP-053 | Go combines overlay values with HTTP facilitators, mutable resolver defaults, wallet-backed admin tokens, and `any`-typed lookup values. | `BSVOverlay` provides only bounded SHIP/SLAP values and transport-neutral async facilitator protocols with typed byte payloads. Topic and service names follow the `@bsv/sdk` 4.1.1 grammar, and lookup outputs carry the optional TS `context` and `txid`. | Preserves useful Go vocabulary without accepting unbounded data, hidden network policy, or mutable or erased result state. | | COMP-054 | Pinned Go identity creates fallback wallets and concrete network broadcasters, discards a disclosure verifier secret, emits raw key bytes as display text, and exports an accepting verifier. TypeScript 4.1.1 and `tm_identity` require `[1,"identity"]` and the fixed "anyone" verifier. | `BSVIdentity` requires typed wallet, broadcaster, and bounded limits; proves to the "anyone" verifier; locks under `[1,"identity"]` by default; emits canonical compressed-key hex; verifies certificates; and checks the proved keyring exactly. | Produces tokens TypeScript overlay hosts admit, without copying unsafe capability and encoding defects. | | COMP-055 | Pinned Go registry combines mutable clients, factory setters, default network state, wallet orchestration, HTTP overlay discovery, and an open definition interface. TypeScript 4.1.1 tokens carry an operator signature and use level-1 protocols. | `BSVRegistry` provides bounded immutable definition values, the TypeScript signed 7/7/8-field PushDrop codec with operator key linkage, typed records and queries, plus narrow `Sendable` lookup and publisher boundaries. | Reads and writes the tokens TypeScript hosts admit without hidden transport, wallet orchestration, persistence, mutable state, or erased values. | | COMP-056 | Pinned Go KVStore combines PushDrop token encoding with wallet actions, BEEF state resolution, encryption, mutable local state, and undocumented output ordering. Go writes one field; TypeScript 4.1.1 `LocalKVStore` requires two (value and signature). | `BSVKVStore` provides bounded immutable two-field signed tokens and locators in the lock-before layout, with wallet signing and owner-key checks. | Matches the token TypeScript reads without claiming storage, ordering, encryption, persistence, or transport semantics. | | COMP-057 | Pinned Go storage combines UHRP value conversion with unbounded overlay resolution, downloader HTTP, authenticated upload APIs, mutable HTTP clients, and type-erased service data. | `BSVStorage` provides bounded UHRP identifiers, content values, signed host-advertisement decoding, and a narrow `Sendable` content-provider boundary. | Preserves the UHRP Base58Check and SHA-256 format and the TypeScript advertisement layout without embedding HTTP policy, discovery, wallet authority, persistence, or erased response state. | | COMP-058 | Pinned Go treats an overlay administration token as a mutable wallet template, accepts surplus or malformed data fields, and does not verify its appended signature before discovery uses it. | `BSVOverlay` decodes only bounded, exact signed `beforeCompatibility` PushDrop advertisements and verifies the signature against the locking key, which must be the identity's BRC-42 SHIP or SLAP child as in `@bsv/sdk` 4.1.1. URI, field-size, and DER rules also match TS. Wallet construction and spending remain separate. | Preserves signed SHIP/SLAP advertisement data without importing wallet orchestration, default resolvers, HTTP policy, or mutable factories. | -| COMP-059 | Pinned Go joins BRC-104 HTTP framing to concrete clients, callback state, unauthenticated fallback, and automatic payment. | Swift provides a bounded transport-neutral HTTP frame codec for signed general messages. It requires canonical authentication headers and exact request-ID correlation. | Preserves the authenticated HTTP wire fields without selecting endpoint, retry, fallback, payment, or persistence policy. The unsigned requested-certificate header remains rejected; signed exchange uses COMP-060. | -| COMP-060 | Pinned Go certificate exchange does not enforce requested field or type completeness, does not correlate a response with one pending request, and carries an unsigned requested-certificate HTTP header. | Swift provides bounded typed post-authentication certificate requests and responses. It signs canonical request or response JSON, correlates one exact pending request, and requires separate BRC-52 certificate validation. The HTTP header remains rejected. | Canonical signed BRC-103 messages remain compatible. Swift does not accept missing disclosures, unsolicited responses, or unsigned HTTP certificate requests. | +| COMP-059 | Pinned Go joins BRC-104 HTTP framing to concrete clients, callback state, unauthenticated fallback, and automatic payment. `@bsv/sdk` 4.1.1 `AuthFetch` omits `x-bsv-auth-message-type` on requests. | Swift provides a bounded transport-neutral HTTP frame codec for signed general messages. It requires canonical authentication headers and exact request-ID correlation. The request message-type header is optional and must be `general` when present. `x-bsv-auth-requested-certificates` is read on requests and responses, up to 256 KiB, as the JSON of a requested set, and written for a general message that carries one. | Accepts TypeScript `AuthFetch` requests without selecting endpoint, retry, fallback, payment, or persistence policy. The requested-certificate header is unsigned; `PeerAuthenticator` does not act on it, as `Peer.processGeneralMessage` does not, and signed exchange uses COMP-060. | +| COMP-060 | Pinned Go certificate exchange does not enforce requested field or type completeness, does not correlate a response with one pending request, and carries an unsigned requested-certificate HTTP header. `@bsv/sdk` 4.1.1 signs certificate JSON in member order, requires `initialNonce`, sends policies in the handshake from either side, keeps several requests open, and answers with any allowed subset. | Swift keeps up to 16 open requests per direction, with the requests a peer has sent sharing one byte budget and no repeats. A response settles the oldest certificateRequest it fits, or the handshake policy if none fits, and also the handshake policy when its certificates fit it, as `Peer.ts:1236-1247` does; `makeCertificateResponse(answering:)` can name the request on the sending side, and an empty response declines the oldest. A refused request uses up its nonce; refusing a repeat is Swift's own rule, and `withdrawCertificateRequest` lets a sender stop waiting. It signs the JSON it writes, verifies received JSON in received order with `JSON.stringify` escaping, sends and checks `initialNonce`, and returns handshake policies as certificate requests. `beginAuthentication(requesting:)` sends a policy in initialRequest and `PeerAuthenticator(certificatesToRequest:)` sends one in every initialResponse, which `AuthFetch` answers on its own. Certificates a peer includes in initialResponse are checked against the policy and returned as a certificate response, and are ignored when none was sent. A requested set with no certifiers asks for nothing. `AuthCertificateExchange.validate` requires every requested type and field; `validateSubset` accepts a nonempty subset as `validateCertificates.ts` does; both fail on no certificates. Errors name no side, and their detailed causes go to the `BSVAuth` log. | Certificate exchange works with `@bsv/sdk` 4.1.1 in both directions, including a Swift server asking a TypeScript `AuthFetch` client for certificates. Swift does not accept unsolicited responses, unrequested certifiers, types or fields, or unsigned HTTP certificate requests. initialResponse certificates are not covered by its signature, so callers validate them with `AuthCertificateExchange`, as `Peer.ts:960-982` does. | | COMP-061 | Pinned Go overlay HTTP and policy use unbounded response reads, unsafe binary counts and indexes, default trackers, unbounded fan-out, and scheduler-dependent result order. | Swift places bounded HTTPS facilitators in `BSVNetwork` and deterministic resolver and one-shot broadcaster policy in `BSVOverlay`. All hosts and limits are explicit, discovery verifies signed tokens, and failed submission has uncertain delivery. The wire formats (aggregated answers, JSON outputs, camelCase STEAK, comma-separated topics, off-chain values, any 2xx) and per-host topics follow `@bsv/sdk` 4.1.1 hosts. | Preserves canonical SHIP and SLAP requests and results without hidden network policy, unsafe retry, unbounded work, or nondeterministic aggregation. | | COMP-062 | Pinned Go provides one concrete UHRP downloader with internal resolver, tracker, and HTTP policy. | Swift keeps UHRP values in `BSVStorage` and places the injected resolver and bounded HTTPS downloader in `BSVNetwork`. It authenticates the signed six-field TypeScript advertisement, binds it to the requested hash, sorts hosts, makes one GET per host, and verifies the SHA-256 result. | Preserves the TypeScript `ls_uhrp` query and advertisement layout without hidden trackers, cleartext hosts, unbounded bodies, automatic retry, or mutable network policy. | | COMP-063 | BRC-157 composes BIP-39, BIP-32, and BRC-140 without storage, transport, or a concrete wallet implementation. Go and TypeScript expose the constituent behavior from their SDK packages. | Swift places the composed entropy-backup and hardened-profile API in opt-in `BSVCompat`, which already owns BIP-39 and BIP-32 and depends on `BSVKeys` for BRC-140. It remains outside the modern `BSV` umbrella. | Keeps the reusable backup primitive in the SDK while preserving the explicit compatibility boundary required by BIP-39 and BIP-32. Toolbox wallets may consume it without owning or duplicating the primitive. | diff --git a/Documentation/Compatibility/Rulings/COMP-052-BRC-103-104-Core.md b/Documentation/Compatibility/Rulings/COMP-052-BRC-103-104-Core.md index 3c0dc47..1228f1a 100644 --- a/Documentation/Compatibility/Rulings/COMP-052-BRC-103-104-Core.md +++ b/Documentation/Compatibility/Rulings/COMP-052-BRC-103-104-Core.md @@ -14,25 +14,46 @@ COMP-060 covers signed certificate exchange. ## Decision Swift emits BRC-103 version `0.1`. It rejects unknown versions. The strict JSON -codec rejects duplicate and unknown object members before Foundation decodes -the document. It requires canonical compressed public keys, canonical Base64 -nonces, complete low-S DER signatures, and explicit JSON and payload limits. +codec rejects duplicate and unknown object members, invalid UTF-8, lone +surrogates and excessive nesting before Foundation decodes the document. It +requires canonical compressed public keys, canonical Base64 nonces, complete +low-S DER signatures, and explicit JSON and payload limits. Swift writes the +message JSON itself, so certificate data on the wire is byte-identical to the +text it signs (COMP-060). The peer authenticator uses an injected wallet, secure random source, and clock-based session timeout. It binds an expected peer identity, rejects nonce reuse and message replay, limits sessions and accepted messages, and checks cancellation around each wallet call. A responder remains unauthenticated -until it verifies the first signed general message. +until it verifies the first signed general, certificate-request or +certificate-response message from the initiator. -Swift accepts 32-byte protocol nonces and the exact 48-byte Go nonce form. It -generates 32-byte nonces and propagates random-source failures. It does not -accept the other variable nonce lengths that the pinned Go verifier accepts. +Every session nonce Swift creates, as initiator or responder, is 48 random +bytes in canonical padded Base64 (64 characters). Message nonces are 32 bytes. +Swift accepts 32-byte and 48-byte session nonces from peers and propagates +random-source failures. It does not accept the other variable nonce lengths +that the pinned Go verifier accepts. The BRC-104 codec is transport-neutral. It binds a 32-byte request identifier to the method, path, optional query, selected headers, body, or response status. It uses canonical CompactSize values and explicit payload and header limits. -It excludes all `x-bsv-auth-*` headers from the signed payload, rejects -duplicate headers, and sorts selected header names by lowercase UTF-8 bytes. +It excludes every header whose name starts with `x-bsv-auth` from the signed +payload, as `AuthFetch.ts:727` does, rejects duplicate headers, and sorts the +lowercase selected header names in `localeCompare` order (`AuthFetch.ts:740`). +That order differs from the Go SDK's UTF-8 byte order only where names differ +at a `_`: `localeCompare` puts `x-bsv-a_b` before `x-bsv-a-b`, `x-bsv-a1` and +`x-bsv-ab`, and byte order puts it after them. A signed header value must be +printable ASCII without leading or trailing spaces, because `fetch` trims +values and reads them as Latin-1 before a TypeScript client rebuilds the +payload; Swift refuses other values rather than sign bytes the peer will not +see. + +An absent or empty body is written as -1, never 0, in requests and responses. +When a client encodes a POST, PUT, PATCH or DELETE request with an absent body +and a `content-type` containing `application/json`, it signs and sends `{}`. +An empty body stays empty. A server rebuilding a received request never adds +`{}`. A `multipart/form-data` content type is signed whole, with its boundary; +any other content type is cut at the first `;` and trimmed. ## Go SDK defects @@ -47,3 +68,36 @@ The separate Go SDK defect report records the related pinned defects: Swift does not reproduce these defects. Shared messages other than requested certificate sets remain interoperable through the pinned Go oracle. COMP-060 records the requested-certificate wire incompatibility. + +## Changes for `@bsv/sdk` 4.1.1 + +TypeScript `@bsv/sdk` 4.1.1 is the reference peer. Where this ruling and that +SDK disagreed on the wire, Swift now follows the SDK: + +- A responder created 32-byte session nonces. TypeScript requires exactly 48 + bytes for `initialNonce` and `yourNonce` (`AuthMessageValidation.ts:391-428`) + and rejected every Swift initialResponse. +- A responder became authenticated only on a general message. TypeScript marks + the peer authenticated on any verified certificate request, certificate + response or general message (`Peer.ts:1092`, `Peer.ts:1227`, `Peer.ts:1317`). +- An empty body was written as 0. TypeScript writes and expects -1 in both + directions (`clients/AuthFetch.ts:762-770`, + `transports/SimplifiedFetchTransport.ts:314-321`, + `auth-express-middleware/src/index.ts:2112-2117`). The client `{}` default + applies only to an absent body, as in `clients/AuthFetch.ts:755-760`. +- `content-type` was cut at `;` without trimming, also for multipart. + TypeScript uses `authenticatedContentType` (`utils/paymentTransport.ts:84-90`). +- Default limits were below what TypeScript sends. They now match: 16 MiB + messages (`AuthMessageValidation.ts:8`), payloads of 16 MiB plus 512 KiB + (`clients/AuthFetch.ts:147`), 100 certificates, certifiers and types + (`AuthMessageValidation.ts:12-14`), and 512 headers, 1 KiB names, 32 KiB + values and 256 KiB in total, with 256 KiB for `x-bsv-payment` + (`transports/SimplifiedFetchTransport.ts:25-28`, `:655-661`). BRC-103 signs + each general payload through the wallet, so `WalletCryptoLimits` defaults to + the same 16 MiB plus 512 KiB (`WalletCryptoLimits.defaultPayloadByteCount`, + which `AuthLimits.defaultPayloadBytes` is); the TypeScript `ProtoWallet` has + no bound. + +`Tests/BSVAuthTests/BRC103/TypeScriptInteropTests.swift` replays TypeScript +messages from `TypeScriptAuthVectors.md` and checks Swift messages against a +live TypeScript peer. diff --git a/Documentation/Compatibility/Rulings/COMP-059-BRC-104-HTTP-Framing.md b/Documentation/Compatibility/Rulings/COMP-059-BRC-104-HTTP-Framing.md index 9869bdd..98ff777 100644 --- a/Documentation/Compatibility/Rulings/COMP-059-BRC-104-HTTP-Framing.md +++ b/Documentation/Compatibility/Rulings/COMP-059-BRC-104-HTTP-Framing.md @@ -8,7 +8,19 @@ transport and payment policies that a framing codec cannot select safely. general messages. The codec uses the seven BRC-104 authentication headers. It requires canonical header values, one value for each authentication header, complete request-ID correlation, valid HTTP component text, and explicit -resource limits. It rejects the requested-certificate header because that +resource limits. + +`x-bsv-auth-message-type` is optional on requests. `AuthFetch` sends only the +other six headers (`transports/SimplifiedFetchTransport.ts:189-194`) and the +TypeScript middleware assumes `general` +(`auth-express-middleware/src/index.ts:361-366`). When the header is present it +must be `general`. Swift still sends it; TypeScript ignores it. A received +request is rebuilt without the client JSON body default, and an empty body is +signed as -1 (COMP-052). + +The default framing limits allow 1024 headers, 1 KiB names, 256 KiB values and +1 MiB of headers in total, so a frame that carries the largest TypeScript +signed headers (COMP-052) and the authentication headers fits. It rejects the requested-certificate header because that header is not part of the signed payload. Callers use the signed BRC-103 certificate-request message from COMP-060. diff --git a/Documentation/Compatibility/Rulings/COMP-060-BRC-103-Certificate-Exchange.md b/Documentation/Compatibility/Rulings/COMP-060-BRC-103-Certificate-Exchange.md index bad5de1..0707a9f 100644 --- a/Documentation/Compatibility/Rulings/COMP-060-BRC-103-Certificate-Exchange.md +++ b/Documentation/Compatibility/Rulings/COMP-060-BRC-103-Certificate-Exchange.md @@ -2,21 +2,116 @@ ## Decision -`BSVAuth` supports signed certificate-request and certificate-response messages -after peer authentication. A request contains a nonempty bounded set of -certifiers, certificate types, and required disclosure fields. A response must -match the exact pending request. +`BSVAuth` supports signed certificate-request and certificate-response messages. +A request contains a bounded set of certifiers and a bounded map of +certificate types to field names. The certifier set, the map and each field +list may be empty, as in `@bsv/sdk` 4.1.1 (`AuthMessageValidation.ts:122`, +`:134-136`). A request with no certifiers asks for nothing: Swift sends it +without awaiting an answer, and a received one authenticates the sender and +needs no answer (`Peer.ts:1097-1100`). -`PeerAuthenticator` verifies the peer message signature and correlates one -response with one pending request. This verification does not establish -certificate trust. The caller must use `AuthCertificateExchange.validate` to -verify each BRC-52 certificate, bind the subject to the peer, decrypt every -requested field, and apply its own trust and revocation policy. +A response is an allowlist answer to an open request: each certificate must +name the responder as subject, have a requested certifier and type, and reveal +a nonempty subset of that type's fields. A response may contain no +certificates (`Peer.ts:359-389`, `Peer.ts:1117`). + +Certificate messages carry the sender's session nonce in `initialNonce` +(`AuthMessageValidation.ts:404`, `:415`). Swift sends it and requires it to +equal the session nonce it holds for the peer. + +### Open requests + +Each direction of a session may have up to 16 open certificateRequests at +once, as `Peer.ts:474-478` keeps one per request nonce, besides a handshake +policy. A seventeenth request, sent or received, fails with +`AuthError.resourceLimit` and leaves the session open. The open requests a +peer has sent are also charged together against +`AuthLimits.maximumCertificateAggregateBytes` (33 bytes per certifier, and +32 per type plus its field names), so one authenticated peer can make a +session hold no more than one request may hold. A received request identical +to one already open fails with `AuthError.unexpectedMessage`; this rule is +Swift's own, since `@bsv/sdk` keeps one entry per request nonce and accepts +identical requests. A refused request still uses up its nonce and counts +against `maximumMessages`, as `Peer.ts:1088-1092` claims the nonce before it +acts, so it cannot be replayed. The peer sends nothing back when it refuses a +request, so a Swift sender keeps it open until the caller calls +`withdrawCertificateRequest(_:using:)`, which `@bsv/sdk` does itself when +sending fails (`Peer.ts:480-485`). + +A response does not name the request it answers. As in `Peer.ts:1202-1227`, +its signature is verified and its nonce claimed before anything else, +including the refusal of a response when nothing is open. It then settles +the oldest certificateRequest it fits, or the handshake policy if none fits +(`Peer.ts:1236-1240`, `:1245`). When it carries certificates that also fit +the handshake policy, it settles that policy too, as `Peer.ts:1247` marks the +handshake requirement met whether or not a request matched, and Swift +returns one certificate-response action for each request settled. The +sending side settles the same requests. An empty response declines the +oldest open request in the same order and nothing else, where `@bsv/sdk` +leaves its requests open (`Peer.ts:1229`); a TypeScript `Peer` without +certificates sends one empty response per request (`Peer.ts:1117`), so the two +stay in step. +`makeCertificateResponse(_:using:answering:)` can name the request being +answered on the sending side only: the peer still settles the first of its +own requests the certificates fit. A response that fits no open request, or +arrives when none is open, is refused. + +### Handshake policies + +A certificate policy in a received `initialRequest` or `initialResponse` is +returned as a certificate-request action (`Peer.ts:644-650`, `Peer.ts:866-875`). +A handshake policy without certifiers means no request. The peer may answer a +handshake request before the other side sends its first signed message. A +policy in `initialRequest` is unsigned, so answer it only with wallet-proved +keyrings, which are encrypted to the claimed identity. + +Swift sends a policy in the same places. `beginAuthentication(requesting:)` +puts one in `initialRequest`. `PeerAuthenticator(certificatesToRequest:)` sets +a policy that a responder puts in every `initialResponse` and that an +initiator uses when `beginAuthentication` names none. A TypeScript `AuthFetch` +client answers a responder policy on its own with a `certificateResponse` +(`AuthFetch.ts:496-511`); Swift returns that as a certificate-response action. +Certificates a peer includes in `initialResponse` are checked against the +policy Swift sent and returned as a certificate response, and are ignored when +none was sent. They are not covered by any signature (`Peer.ts:960-982`). + +`@bsv/sdk` holds general messages until its handshake policy is answered +(`Peer.ts:1326-1328`). Swift delivers them; holding them is caller policy. + +### Validation + +`PeerAuthenticator` verifies the peer message signature and correlates each +response with one open request. This does not establish certificate trust. +The caller validates the certificates with `AuthCertificateExchange`: + +- `validate` requires every requested type and every requested field of each + certificate. It fails when given no certificates. +- `validateSubset` accepts what `validateCertificates` in `@bsv/sdk` accepts + (`validateCertificates.ts:23-29`): a nonempty subset of the requested fields + for each certificate, with requested types allowed to be missing. Like + `validateCertificates.ts:74`, it fails when given no certificates. The + caller decides whether what was disclosed is enough. + +Both verify each BRC-52 signature, bind the subject to the peer, decrypt every +revealed field, and fail as a whole when any certificate fails. The caller +still applies its own trust and revocation policy. The wallet preparation helper lists certificates and proves exactly the requested fields for the verifier. It fails unless it can satisfy every requested certificate type. +### Errors + +Errors stay short and name no side, so the same text fits Swift as client or +server. The detailed cause of a refused message or certificate, such as the +underlying `BRC104Error`, JSON or certificate decoding error, or which +certificate failed which check, is written to the system log on Apple +platforms through `os.Logger` with subsystem `dev.opl.swift-sdk` and category +`BSVAuth`. The reasons `BSVAuth` writes hold no certificate field value, +keyring, nonce or signature. An underlying error defined by this SDK is logged +in full; any other, such as one from a caller's wallet, is public by type only +and its description is marked private. + ## Compatibility Canonical certificate responses reencode through Go SDK v1.3.3. Requested @@ -28,18 +123,50 @@ adapter for semantic comparison. Production Swift does not accept the uppercase aliases. Swift requires canonical padded Base64, lowercase compressed-key and DER hex, -unique certifiers and fields, complete JSON consumption, exact request -matching, low-S signatures, and explicit resource limits. +unique certifiers and fields, complete JSON consumption, low-S signatures, and +explicit resource limits. -Swift does not accept certificate data in the initial handshake. It uses the -signed post-authentication messages because the current `PeerAuthenticator` -does not contain certificate trust policy. +The signed text is the JSON the sender wrote, in its member order +(`Peer.ts:453`, `Peer.ts:1142`). Swift verifies a received request over +`JSON.stringify` of the received value (`Peer.ts:1070`). It verifies a received +response over each certificate rebuilt in the order `type`, `serialNumber`, +`subject`, `certifier`, `revocationOutpoint`, `fields`, `signature`, `keyring`, +with `fields` and `keyring` in received order (`Peer.ts:341-357`, +`Peer.ts:1205`). Strings are escaped as `JSON.stringify` escapes them: `"`, +`\`, the short escapes for backspace, tab, line feed, form feed and carriage +return, and other control characters as lowercase `\u00xx`. `&`, `<`, `>`, +U+2028 and U+2029 are not escaped. When Swift sends, it writes certificate +types, fields and keyring entries in UTF-8 byte order, with array-index names +first as JavaScript orders them, and puts the same bytes on the wire. -The BRC-104 requested-certificate HTTP header remains unavailable. The Go -transport does not bind that header to the signed general-message payload. A -caller must use the signed BRC-103 certificate-request message. +The BRC-104 `x-bsv-auth-requested-certificates` header is read and written +(COMP-059) but not acted on, as `Peer.processGeneralMessage` does not act on +it. Neither the Go nor the TypeScript transport binds that header to the +signed general-message payload, so a caller asks with the signed BRC-103 +certificate-request message or a handshake policy. ## Exclusions This ruling does not add a concrete HTTP or WebSocket transport, AuthFetch, automatic payment, persistent trust policy, or chain-aware revocation lookup. + +## Changes for `@bsv/sdk` 4.1.1 + +The earlier form of this ruling required an exact response to an exact +request, signed byte-sorted JSON while writing the wire with Foundation +`.sortedKeys`, escaped `&`, `<`, `>`, U+2028 and U+2029, omitted +`initialNonce`, and rejected certificate policies in the handshake. Each of +these broke certificate exchange with TypeScript in one direction or both: + +- TypeScript signs and verifies JSON in member order, so a TypeScript request + or response that was not byte-sorted failed in Swift. +- On Linux, Foundation `.sortedKeys` orders `aWlp…` before `Z2dn…`; byte order + is the reverse. A Swift request with such types failed in TypeScript. + `TypeScriptInteropTests.foundationSortedKeysOrder` records this. +- TypeScript rejects certificate messages without `initialNonce`. +- TypeScript answers a request with any allowed subset, including none. +- TypeScript keeps several requests open and sends a responder policy in + `initialResponse`, which `AuthFetch` answers on its own. + +`TypeScriptAuthVectors.md` lists the vectors and the check of Swift messages +against a live TypeScript peer. diff --git a/Documentation/Compatibility/TypeScriptAuthVectors.md b/Documentation/Compatibility/TypeScriptAuthVectors.md new file mode 100644 index 0000000..d725edc --- /dev/null +++ b/Documentation/Compatibility/TypeScriptAuthVectors.md @@ -0,0 +1,619 @@ +# TypeScript `@bsv/sdk` 4.1.1 authentication vectors + +`Tests/BSVAuthTests/BRC103/TypeScriptAuthVectors.swift` holds BRC-103 and +BRC-104 messages produced by executing `@bsv/sdk` 4.1.1 (`packages/sdk` in the +`ts-stack` repository at `3b1abc5691c0848eb00eaf5e8f018e8a7a26d5f1`). The +inputs (keys 3, 7 and 11, certificate fields, nonces from a fixed random +stream) are chosen here. The file contains program output only: no TypeScript +source text or upstream fixture is copied. `TypeScriptInteropTests` replays the +messages against this SDK. COMP-041, COMP-052, COMP-059 and COMP-060 record the +rulings they check. + +## Provenance and license + +`ts-stack` was relicensed under the Apache License 2.0 in commit `4760b26d0` +("Relicense under Apache License 2.0 (#1560)", 2026-11-11), an ancestor of the +pinned commit. `packages/sdk/package.json` at that commit declares version +4.1.1 and license `Apache-2.0`; its NOTICE reads "Copyright 2020-2026 BSV +Association". The vectors are recorded from running that source with the +generator below, under the fixture policy in +[FixtureSources.md](FixtureSources.md#recorded-typescript-auth-vectors) and +[VectorInventory.md](VectorInventory.md#recorded-typescript-auth-vectors). + +`LocaleCompareOrderTests` holds SHA-256 digests and sorted lists printed by +`collate-vec.ts` under Bun 1.4.4 and Node 22.23.4 (ICU, locale `en-US`). Both +runtimes printed the same output. + +The vectors cover: + +- a `Peer` initialResponse to a Swift initialRequest, with a 48-byte session + nonce and a handshake certificate policy; +- a `Peer` certificateResponse whose `fields` are in issue order and whose + `keyring` is in reveal order, with the field name `a&b`; +- a `Peer` certificateRequest whose types are not in byte order; +- the `AuthFetch` handshake body and the six headers of its bodyless GET; +- `AuthFetch.serializeRequest` payloads for the JSON `{}` default, an empty + body, a `content-type` with spaces and parameters, `multipart/form-data`, and + signed headers whose `localeCompare` order differs from byte order; +- a `Peer` with no listener answering a Swift initialRequest that carries a + certificate policy, with its wallet's certificate inside initialResponse; + the certificate has the fields `Zip`, `age`, `a-b` and `a_b`; +- a `Peer` initiator's initialRequest and a certificateRequest with no + certifiers; +- a certificate signed by `Certificate.sign` with mixed-case and punctuated + field names, and its unsigned binary. +- an `AuthFetch` client with a certificate in its wallet answering the + certificate policy in a Swift server's initialResponse: its initialRequest, + the initialResponse the Swift server signs, the certificateResponse + `AuthFetch` posts on its own (fields `Zip` and `age` revealed, `name` + withheld), and the headers of the GET that follows. + +## Regenerating + +Run the scripts below with Bun from one directory. `TS_SDK` names the +`packages/sdk` directory of the pinned checkout. `det.ts` replaces +`crypto.getRandomValues` with a SHA-256 counter stream, so every run gives the +same nonces. + +```sh +export TS_SDK=/path/to/ts-stack/packages/sdk +bun run gen.ts > vectors.json +python3 toswift.py vectors.json Tests/BSVAuthTests/BRC103/TypeScriptAuthVectors.swift +``` + +`collate-vec.ts` needs no SDK. Its output is compared by hand with the values +in `LocaleCompareOrderTests`; under Node it runs as +`node --experimental-strip-types` on a `.mts` copy. + +```sh +bun run collate-vec.ts +``` + +## Checking Swift messages with TypeScript + +`TypeScriptInteropTests.swiftMessagesForTypeScript` writes the messages this SDK +sends in the first two sessions when `BSV_TS_INTEROP_DUMP` names an output file. +`verify.ts` reproduces each TypeScript session from the fixed random stream and +feeds those messages to a live `Peer` and `AuthFetch`. It checks that `Peer` +verifies the Swift certificate response, validates its certificate, verifies the +certificate request and delivers the general message, and that `AuthFetch` +accepts the Swift initialResponse and a signed 204 response with an empty body. + +```sh +BSV_TS_INTEROP_DUMP=$PWD/swift-dump.json swift test --filter TypeScriptInterop +bun run verify.ts swift-dump.json vectors.json +``` + +The Swift certificate in that session has the field names `Zip`, `age`, `email` +and `a&b`, which `localeCompare` and byte order sort differently. +`Certificate.verify` in TypeScript accepts it because this SDK signs certificate +fields in `localeCompare` order (COMP-041). + +## `det.ts` + +```ts +// Deterministic randomness for reproducible vectors: a SHA-256 counter stream. +import { createHash } from 'node:crypto' +let seed = 0 +let counter = 0 +export function resetRandom (s: number): void { seed = s; counter = 0 } +const fill = (arr: Uint8Array): Uint8Array => { + let offset = 0 + while (offset < arr.length) { + const block = createHash('sha256').update(`bsv-auth-vectors:${seed}:${counter++}`).digest() + const n = Math.min(block.length, arr.length - offset) + arr.set(block.subarray(0, n), offset) + offset += n + } + return arr +} +Object.defineProperty(globalThis.crypto, 'getRandomValues', { value: fill, configurable: true, writable: true }) +``` + +## `gen.ts` + +```ts +// Generates BRC-103/104 interop vectors from the live @bsv/sdk 4.1.1 source. +import { resetRandom } from './det.ts' +const { + PrivateKey, ProtoWallet, Peer, AuthFetch, MasterCertificate, VerifiableCertificate, Certificate, Utils +} = await import(`${process.env.TS_SDK}/mod.ts`) + +const b64 = (bytes: number[]) => Utils.toBase64(bytes) +const fill = (v: number, n: number) => new Array(n).fill(v) +const key = (n: number) => new PrivateKey(n) +const tsKey = key(3); const swiftKey = key(7); const certifierKey = key(11) +const tsWallet = new ProtoWallet(tsKey) +const swiftWallet = new ProtoWallet(swiftKey) +const certifierWallet = new ProtoWallet(certifierKey) +const T = tsKey.toPublicKey().toString() +const S = swiftKey.toPublicKey().toString() +const C = certifierKey.toPublicKey().toString() +const out: Record = { tsIdentity: T, swiftIdentity: S, certifier: C } + +// ---------------- Scenario 1: Swift initiator <-> TS Peer responder ---------------- +{ + resetRandom(1) + const sent: any[] = [] + let onData: (m: any) => Promise = async () => {} + const transport = { + send: async (m: any) => { sent.push(JSON.stringify(m)) }, + onData: async (cb: any) => { onData = cb } + } + const handshakeType = b64(fill(0x51, 32)) + const server = new Peer(tsWallet, transport, { certifiers: [C], types: { [handshakeType]: ['email'] } }) + await server.ready + + // Swift deterministic random: call k of the client returns bytes 0x40 + k. + const swiftSessionNonce = b64(fill(0x41, 48)) + await onData({ version: '0.1', messageType: 'initialRequest', identityKey: S, initialNonce: swiftSessionNonce }) + out.initialResponse = sent.shift() + const tsSessionNonce = JSON.parse(out.initialResponse as string).initialNonce as string + + // Certificate issued by the certifier to the TS peer, fields inserted out of byte order. + const certType = b64(fill(0x61, 32)) + const serial = b64(fill(0x62, 32)) + const plaintext: Record = { userName: 'Alice', profilePhoto: 'https://example.test/p.png', 'a&b': 'x>y' } + const master = await MasterCertificate.issueCertificateForSubject( + certifierWallet, T, plaintext, certType, async () => '00'.repeat(32) + '.0', serial) + const keyring = await MasterCertificate.createKeyringForVerifier( + tsWallet, C, S, master.fields, ['profilePhoto', 'a&b', 'userName'], master.masterKeyring, serial) + const vc = new VerifiableCertificate(master.type, master.serialNumber, master.subject, master.certifier, + master.revocationOutpoint, master.fields, keyring, master.signature) + out.certificateFieldOrder = Object.keys(master.fields) + out.certificateKeyringOrder = Object.keys(keyring) + out.certificatePlaintext = plaintext + + server.listenForCertificatesRequested(async (sender: string) => { + await server.sendCertificateResponse(sender, [vc]) + }) + + // The Swift client's certificateRequest, built exactly as Swift writes it (call 3 -> 0x43). + const swiftRequest = { certifiers: [C], types: { [certType]: ['userName', 'profilePhoto', 'a&b'] } } + const requestNonce = b64(fill(0x43, 32)) + const { signature } = await swiftWallet.createSignature({ + data: Utils.toArray(JSON.stringify(swiftRequest), 'utf8'), + protocolID: [2, 'auth message signature'], + keyID: `${requestNonce} ${tsSessionNonce}`, + counterparty: T + }) + await onData({ + version: '0.1', messageType: 'certificateRequest', identityKey: S, nonce: requestNonce, + initialNonce: swiftSessionNonce, yourNonce: tsSessionNonce, requestedCertificates: swiftRequest, signature + }) + out.certificateResponse = sent.shift() + + // TS-originated certificate request with types inserted B then A (A < B in bytes). + const typeA = b64(fill(0x01, 32)); const typeB = b64(fill(0x02, 32)) + await server.requestCertificates({ certifiers: [C], types: { [typeB]: ['name', 'email'], [typeA]: ['x'] } }, S) + out.certificateRequest = sent.shift() + out.leftover = sent.length +} + +// ---------------- Scenario 2: TS AuthFetch client -> Swift server ---------------- +{ + resetRandom(2) + const captured: any[] = [] + const serverNonce = b64(fill(0x61, 48)) // Swift server call 1 -> 0x61 + const fetchMock = async (url: string, init: any) => { + const headers: Record = {} + new Headers(init.headers).forEach((v, k) => { headers[k] = v }) + let body: number[] | null = null + if (init.body != null) { + body = typeof init.body === 'string' ? Utils.toArray(init.body, 'utf8') : Array.from(init.body as Uint8Array) + } + captured.push({ url, method: init.method, headers, body: body == null ? null : Utils.toUTF8(body) }) + if (url.endsWith('/.well-known/auth')) { + const request = JSON.parse(Utils.toUTF8(body!)) + const clientNonce = request.initialNonce + const { signature } = await swiftWallet.createSignature({ + data: [...Utils.toArray(clientNonce, 'base64'), ...Utils.toArray(serverNonce, 'base64')], + protocolID: [2, 'auth message signature'], + keyID: `${clientNonce} ${serverNonce}`, + counterparty: request.identityKey + }) + const response = { + version: '0.1', messageType: 'initialResponse', identityKey: S, nonce: serverNonce, + initialNonce: serverNonce, yourNonce: clientNonce, signature + } + return new Response(JSON.stringify(response), { status: 200, headers: { 'content-type': 'application/json' } }) + } + throw new Error('captured') + } + const client = new AuthFetch(tsWallet, undefined, undefined, undefined, {}, fetchMock as any) + try { await client.fetch('https://swift.example/a', { method: 'GET' }) } catch (e) { out.getError = String(e) } + out.authFetch = captured + + // AuthFetch request serialization vectors (clients/AuthFetch.ts:784-818). + const id = fill(0x07, 32) + const ser = async (method: string, headers: Record, body: any, url: string) => + Utils.toHex((await (client as any).serializeRequest(method, headers, body, new URL(url), id)).toArray()) + out.serialized = { + getNoBody: await ser('GET', {}, undefined, 'https://h.example/a'), + postJsonDefault: await ser('POST', { 'content-type': 'application/json' }, undefined, 'https://h.example/v1/items'), + postEmptyString: await ser('POST', { 'content-type': 'application/json' }, '', 'https://h.example/v1/items'), + contentTypeSpaces: await ser('POST', { 'content-type': 'application/json ; charset=utf-8' }, '{"a":1}', 'https://h.example/v1/items?x=1'), + multipart: await ser('POST', { 'content-type': 'multipart/form-data; boundary=abc123' }, 'part', 'https://h.example/upload'), + } +} + +// ---------------- Scenario 3: certificate policy in the handshake, empty requests, ordering ---------------- +{ + resetRandom(3) + // 3a. Swift initiator sends its policy in initialRequest; a TS Peer with no listener answers + // with certificates from its wallet inside initialResponse (Peer.ts:836-849, 872). + const certType = b64(fill(0x71, 32)) + const serial = b64(fill(0x72, 32)) + const plaintext: Record = { Zip: '90210', age: '30', 'a-b': 'dash', a_b: 'underscore' } + const master = await MasterCertificate.issueCertificateForSubject( + certifierWallet, T, plaintext, certType, async () => '00'.repeat(32) + '.0', serial) + out.handshakeCertificateFieldOrder = Object.keys(master.fields) + class CertWallet extends ProtoWallet { + async listCertificates () { + return { + totalCertificates: 1, + certificates: [{ + type: master.type, serialNumber: master.serialNumber, subject: master.subject, + certifier: master.certifier, revocationOutpoint: master.revocationOutpoint, + fields: master.fields, signature: master.signature + }] + } + } + async proveCertificate (args: any) { + return { + keyringForVerifier: await MasterCertificate.createKeyringForVerifier( + tsWallet, C, args.verifier, master.fields, args.fieldsToReveal, master.masterKeyring, serial) + } + } + } + const sent: any[] = [] + let onData: (m: any) => Promise = async () => {} + const transport = { + send: async (m: any) => { sent.push(JSON.stringify(m)) }, + onData: async (cb: any) => { onData = cb } + } + const responder = new Peer(new CertWallet(tsKey), transport) + await responder.ready + const swiftPolicy = { certifiers: [C], types: { [certType]: ['Zip', 'age', 'a_b'] } } + out.handshakePolicy = swiftPolicy + out.handshakePlaintext = plaintext + await onData({ + version: '0.1', messageType: 'initialRequest', identityKey: S, + initialNonce: b64(fill(0x41, 48)), requestedCertificates: swiftPolicy + }) + out.initialResponseWithCertificates = sent.shift() + out.leftover3a = sent.length + + // 3b. TS initiator; Swift responder nonce is 48 bytes of 0x61. After the handshake the TS + // peer sends a certificateRequest with no certifiers (Peer.ts:430-490). + const sent2: any[] = [] + let onData2: (m: any) => Promise = async () => {} + const serverNonce = b64(fill(0x61, 48)) + const transport2 = { + send: async (m: any) => { + sent2.push(JSON.stringify(m)) + if (m.messageType === 'initialRequest') { + const { signature } = await swiftWallet.createSignature({ + data: [...Utils.toArray(m.initialNonce, 'base64'), ...Utils.toArray(serverNonce, 'base64')], + protocolID: [2, 'auth message signature'], + keyID: `${m.initialNonce} ${serverNonce}`, + counterparty: T + }) + void onData2({ + version: '0.1', messageType: 'initialResponse', identityKey: S, + initialNonce: serverNonce, yourNonce: m.initialNonce, signature + }) + } + }, + onData: async (cb: any) => { onData2 = cb } + } + const initiator = new Peer(tsWallet, transport2) + await initiator.ready + await initiator.requestCertificates({ certifiers: [], types: {} }, S) + out.emptyRequestInitialRequest = sent2.shift() + out.emptyCertificateRequest = sent2.shift() + out.leftover3b = sent2.length + + // 3c. A certificate signed by Certificate.sign with mixed-case and punctuated field names. + const cert = new Certificate( + b64(fill(0x81, 32)), b64(fill(0x82, 32)), T, C, '00'.repeat(32) + '.0', + { Zip: b64([1]), age: b64([2]), 'a-b': b64([3]), a_b: b64([4]), Email: b64([5]), email: b64([6]) }) + await cert.sign(certifierWallet) + out.mixedCaseCertificate = JSON.stringify({ + type: cert.type, serialNumber: cert.serialNumber, subject: cert.subject, certifier: cert.certifier, + revocationOutpoint: cert.revocationOutpoint, fields: cert.fields, signature: cert.signature + }) + out.mixedCaseCertificatePreimage = Utils.toHex(cert.toBinary(false)) + out.mixedCaseCertificateVerifies = await cert.verify() + + // 3d. Signed header order in AuthFetch.serializeRequest (AuthFetch.ts:740). + const client = new AuthFetch(tsWallet) + out.serializedHeaderOrder = Utils.toHex((await (client as any).serializeRequest('POST', { + 'x-bsv-zeta': '1', 'x-bsv-ab': '2', 'x-bsv-a-b': '3', 'x-bsv-a_b': '4', 'x-bsv-a.b': '5', + 'X-BSV-Upper': '6', 'content-type': 'application/json' + }, '{}', new URL('https://h.example/h'), fill(0x07, 32))).toArray()) +} + +// ---------------- Scenario 4: Swift server policy answered by a TS AuthFetch client ---------------- +{ + resetRandom(4) + const certType = b64(fill(0x91, 32)) + const serial = b64(fill(0x92, 32)) + const plaintext: Record = { Zip: '73301', age: '41', name: 'Bob' } + const master = await MasterCertificate.issueCertificateForSubject( + certifierWallet, T, plaintext, certType, async () => '00'.repeat(32) + '.0', serial) + class CertWallet extends ProtoWallet { + async listCertificates () { + return { + totalCertificates: 1, + certificates: [{ + type: master.type, serialNumber: master.serialNumber, subject: master.subject, + certifier: master.certifier, revocationOutpoint: master.revocationOutpoint, + fields: master.fields, signature: master.signature + }] + } + } + async proveCertificate (args: any) { + return { + keyringForVerifier: await MasterCertificate.createKeyringForVerifier( + tsWallet, C, args.verifier, master.fields, args.fieldsToReveal, master.masterKeyring, serial) + } + } + } + const serverPolicy = { certifiers: [C], types: { [certType]: ['Zip', 'age'] } } + out.serverPolicy = serverPolicy + out.serverPolicyPlaintext = plaintext + const serverNonce = b64(fill(0x61, 48)) + const captured: any[] = [] + const fetchMock = async (url: string, init: any) => { + const headers: Record = {} + new Headers(init.headers).forEach((v, k) => { headers[k] = v }) + let body: number[] | null = null + if (init.body != null) { + body = typeof init.body === 'string' ? Utils.toArray(init.body, 'utf8') : Array.from(init.body as Uint8Array) + } + captured.push({ url, method: init.method, headers, body: body == null ? null : Utils.toUTF8(body) }) + if (url.endsWith('/.well-known/auth')) { + const request = JSON.parse(Utils.toUTF8(body!)) + if (request.messageType !== 'initialRequest') return new Response(null, { status: 204 }) + const clientNonce = request.initialNonce + const { signature } = await swiftWallet.createSignature({ + data: [...Utils.toArray(clientNonce, 'base64'), ...Utils.toArray(serverNonce, 'base64')], + protocolID: [2, 'auth message signature'], + keyID: `${clientNonce} ${serverNonce}`, + counterparty: request.identityKey + }) + const response = { + version: '0.1', messageType: 'initialResponse', identityKey: S, nonce: serverNonce, + initialNonce: serverNonce, yourNonce: clientNonce, signature, requestedCertificates: serverPolicy + } + out.serverPolicyInitialResponse = JSON.stringify(response) + return new Response(JSON.stringify(response), { status: 200, headers: { 'content-type': 'application/json' } }) + } + throw new Error('captured') + } + const client = new AuthFetch(new CertWallet(tsKey), undefined, undefined, undefined, {}, fetchMock as any) + try { await client.fetch('https://swift.example/b', { method: 'GET' }) } catch (e) { out.policyGetError = String(e) } + out.policyAuthFetch = captured +} + +console.log(JSON.stringify(out, null, 1)) +``` + +## `verify.ts` + +```ts +// Feeds the messages the Swift SDK wrote (BSV_TS_INTEROP_DUMP) to a live +// @bsv/sdk 4.1.1 Peer and AuthFetch, in the sessions gen.ts recorded. +import { resetRandom } from './det.ts' +const { PrivateKey, ProtoWallet, Peer, AuthFetch, Utils } = await import(`${process.env.TS_SDK}/mod.ts`) +import { readFileSync } from 'node:fs' + +const dump = JSON.parse(readFileSync(process.argv[2], 'utf8')) +const vectors = JSON.parse(readFileSync(process.argv[3], 'utf8')) +const b64 = (bytes: number[]) => Utils.toBase64(bytes) +const fill = (v: number, n: number) => new Array(n).fill(v) +const tsWallet = new ProtoWallet(new PrivateKey(3)) +const S = new PrivateKey(7).toPublicKey().toString() +const C = new PrivateKey(11).toPublicKey().toString() +const check = (ok: boolean, what: string) => { if (!ok) throw new Error('FAILED: ' + what); console.log('ok ' + what) } + +{ + resetRandom(1) + const sent: string[] = [] + let onData: (m: any) => Promise = async () => {} + const transport = { send: async (m: any) => { sent.push(JSON.stringify(m)) }, onData: async (cb: any) => { onData = cb } } + const handshakeType = b64(fill(0x51, 32)) + const peer = new Peer(tsWallet, transport, { certifiers: [C], types: { [handshakeType]: ['email'] } }) + await peer.ready + await onData({ version: '0.1', messageType: 'initialRequest', identityKey: S, initialNonce: b64(fill(0x41, 48)) }) + check(sent.shift() === vectors.initialResponse, 'Peer replays the recorded initialResponse') + + const received: any = {} + peer.listenForCertificatesReceived(async (sender: string, certs: any[]) => { + received.certificates = await Promise.all(certs.map(async c => ({ type: c.type, fields: await c.decryptFields(tsWallet) }))) + received.sender = sender + }) + peer.listenForCertificatesRequested(async (sender: string, request: any) => { received.request = request }) + peer.listenForGeneralMessages(async (sender: string, payload: number[]) => { received.general = Utils.toUTF8(payload) }) + + await onData(JSON.parse(dump.clientCertificateResponse)) + check(received.sender === S, 'Peer verifies the Swift certificateResponse signature') + check(received.certificates?.length === 1 && received.certificates[0].type === handshakeType && + JSON.stringify(received.certificates[0].fields) === JSON.stringify({ email: 'swift@example.test' }), + 'Peer validates the Swift certificate and decrypts the revealed field') + await onData(JSON.parse(dump.clientCertificateRequest)) + check(received.request != null && Object.keys(received.request.types).length === 3, + 'Peer verifies the Swift certificateRequest signature') + await onData(JSON.parse(dump.clientGeneral)) + check(received.general === 'hello from swift', 'Peer delivers the Swift general message') + check(sent.length === 0, 'Peer sent nothing else') +} + +{ + resetRandom(2) + let request: any + const fetchMock = async (url: string, init: any) => { + if (url.endsWith('/.well-known/auth')) { + return new Response(dump.serverInitialResponse, { status: 200, headers: { 'content-type': 'application/json' } }) + } + const headers: Record = {} + new Headers(init.headers).forEach((v, k) => { headers[k] = v }) + request = { url, headers } + return new Response(null, { status: dump.serverResponse.status, headers: dump.serverResponse.headers }) + } + const client = new AuthFetch(tsWallet, undefined, undefined, undefined, {}, fetchMock as any) + const response = await client.fetch('https://swift.example/a', { method: 'GET' }) + check(JSON.stringify(request.headers) === JSON.stringify(vectors.authFetch[1].headers), + 'AuthFetch accepts the Swift initialResponse and replays the recorded GET') + check(response.status === 204 && (await response.text()) === '', + 'AuthFetch verifies the Swift server 204 response with an empty body') +} +console.log('all Swift messages accepted by @bsv/sdk 4.1.1') +``` + +## `toswift.py` + +```python +import json, sys +v=json.load(open(sys.argv[1])) +def raw(s): + assert '"#' not in s + return '#"' + s + '"#' +get=v['authFetch'][1] +assert get['body'] is None and len(get['headers'])==6 +hs=sorted(get['headers'].items()) +L=[] +L.append('// Vectors produced by running the `@bsv/sdk` 4.1.1 source (ts-stack origin/main') +L.append('// 3b1abc569) with the generator in Documentation/Compatibility/TypeScriptAuthVectors.md.') +L.append('// Keys are the scalars 3 (TypeScript peer), 7 (Swift peer) and 11 (certifier). Strings are') +L.append('// the exact `JSON.stringify` wire text the TypeScript transports send. Do not edit by hand.') +L.append('enum TypeScriptAuthVectors {') +L.append(f' static let typeScriptIdentity = "{v["tsIdentity"]}"') +L.append(f' static let swiftIdentity = "{v["swiftIdentity"]}"') +L.append(f' static let certifier = "{v["certifier"]}"') +L.append('') +L.append(' /// `Peer.processInitialRequest` answering a Swift initialRequest whose nonce is 48 bytes of') +L.append(' /// 0x41, with a handshake certificate policy (`Peer.ts:866-875`).') +L.append(f' static let initialResponse =\n {raw(v["initialResponse"])}') +L.append('') +L.append(' /// `Peer.sendCertificateResponse` (`Peer.ts:1129-1171`) answering the Swift request for') +L.append(' /// `certificateFields`. Fields are in issue order, the keyring in reveal order.') +L.append(f' static let certificateResponse =\n {raw(v["certificateResponse"])}') +L.append('') +L.append(' /// `Peer.requestCertificates` (`Peer.ts:430-490`) with types inserted 0x02… then 0x01….') +L.append(f' static let certificateRequest =\n {raw(v["certificateRequest"])}') +L.append('') +L.append(' /// The certificate type the Swift peer requested and its plaintext fields.') +L.append(' static let certificateType = [UInt8](repeating: 0x61, count: 32)') +L.append(' static let certificateFields: [(name: String, value: String)] = [') +for k,val in v['certificatePlaintext'].items(): + L.append(f' ({json.dumps(k)}, {json.dumps(val)}),') +L.append(' ]') +L.append('') +L.append(' /// `SimplifiedFetchTransport` handshake body sent by `AuthFetch` to a server whose session') +L.append(' /// nonce is 48 bytes of 0x61.') +L.append(f' static let authFetchInitialRequest =\n {raw(v["authFetch"][0]["body"])}') +L.append('') +L.append(' /// The HTTP request `AuthFetch.fetch(url, { method: "GET" })` then sends for') +L.append(' /// `https://swift.example/a` (`SimplifiedFetchTransport.ts:189-194`).') +L.append(f' static let authFetchMethod = "{get["method"]}"') +L.append(' static let authFetchPath = "/a"') +L.append(' static let authFetchHeaders: [(name: String, value: String)] = [') +for k,val in hs: + L.append(f' ("{k}", "{val}"),') +L.append(' ]') +L.append('') +L.append(' /// `AuthFetch.serializeRequest` (`clients/AuthFetch.ts:784-818`) with request ID 32×0x07.') +for k,val in v['serialized'].items(): + L.append(f' static let serialized{k[0].upper()+k[1:]} =\n "{val}"') + +L.append('') +L.append(' /// `Peer.processInitialRequest` with no listener answering a Swift initialRequest (nonce') +L.append(' /// 48 bytes of 0x41) that carries `handshakePolicy`: the wallet\'s certificate is included') +L.append(' /// in initialResponse (`Peer.ts:836-849`, `Peer.ts:872`). The certificate was issued by') +L.append(' /// `MasterCertificate.issueCertificateForSubject` with `handshakeFields` in this order.') +L.append(f' static let initialResponseWithCertificates =\n {raw(v["initialResponseWithCertificates"])}') +L.append(' static let handshakeCertificateType = [UInt8](repeating: 0x71, count: 32)') +L.append(' static let handshakeRequestedFields = [' + ', '.join(json.dumps(f) for f in list(v['handshakePolicy']['types'].values())[0]) + ']') +L.append(' static let handshakeFields: [(name: String, value: String)] = [') +for k,val in v['handshakePlaintext'].items(): + L.append(f' ({json.dumps(k)}, {json.dumps(val)}),') +L.append(' ]') +L.append('') +L.append(' /// A TS `Peer` initiator\'s initialRequest to a Swift responder whose nonce is 48 bytes of') +L.append(' /// 0x61, then `Peer.requestCertificates({ certifiers: [], types: {} })`.') +L.append(f' static let emptyRequestInitialRequest =\n {raw(v["emptyRequestInitialRequest"])}') +L.append(f' static let emptyCertificateRequest =\n {raw(v["emptyCertificateRequest"])}') +L.append('') +L.append(' /// A certificate signed by `Certificate.sign` (`Certificate.ts:464-485`) with field names') +L.append(' /// that `localeCompare` and byte order sort differently, and its unsigned binary') +L.append(' /// (`Certificate.ts:290`).') +L.append(f' static let mixedCaseCertificate =\n {raw(v["mixedCaseCertificate"])}') +L.append(f' static let mixedCaseCertificatePreimage =\n "{v["mixedCaseCertificatePreimage"]}"') +L.append('') +L.append(' /// `AuthFetch.serializeRequest` with headers sorted by `localeCompare` (`AuthFetch.ts:740`).') +L.append(f' static let serializedHeaderOrder =\n "{v["serializedHeaderOrder"]}"') +pf=v['policyAuthFetch'] +assert len(pf)==3 and pf[2]['body'] is None and len(pf[2]['headers'])==6 +L.append('') +L.append(' /// A TS `AuthFetch` client whose wallet holds a certificate, against a Swift server') +L.append(' /// (nonce 48 bytes of 0x61) whose policy is `serverPolicyFields` of') +L.append(' /// `serverPolicyCertificateType`: its handshake body, the initialResponse the server') +L.append(' /// was expected to send, the certificateResponse `AuthFetch` then posted on its own') +L.append(' /// (`clients/AuthFetch.ts:496-511`), and the headers of the GET it sent next.') +L.append(f' static let policyInitialRequest =\n {raw(pf[0]["body"])}') +L.append(f' static let policyInitialResponse =\n {raw(v["serverPolicyInitialResponse"])}') +L.append(f' static let policyCertificateResponse =\n {raw(pf[1]["body"])}') +L.append(' static let policyGetPath = "/b"') +L.append(' static let policyGetHeaders: [(name: String, value: String)] = [') +for k,val in sorted(pf[2]['headers'].items()): + L.append(f' ("{k}", "{val}"),') +L.append(' ]') +L.append(' static let serverPolicyCertificateType = [UInt8](repeating: 0x91, count: 32)') +L.append(' static let serverPolicyFields = [' + ', '.join(json.dumps(f) for f in list(v['serverPolicy']['types'].values())[0]) + ']') +L.append(' static let serverPolicyPlaintext: [(name: String, value: String)] = [') +for k,val in v['serverPolicyPlaintext'].items(): + L.append(f' ({json.dumps(k)}, {json.dumps(val)}),') +L.append(' ]') +L.append('}') +open(sys.argv[2],'w').write('\n'.join(L)+'\n') +``` + +## `collate-vec.ts` + +```ts +import { createHash } from 'node:crypto' +const cmp = (a: string, b: string) => a.localeCompare(b) +const hash = (xs: string[]) => createHash('sha256').update(xs.join('\n'), 'utf8').digest('hex') +const printable: string[] = [] +for (let c = 0x20; c <= 0x7e; c++) printable.push(String.fromCharCode(c)) +console.log('ascii', JSON.stringify([...printable].sort(cmp).join(''))) +const pairs: string[] = [] +let ties = 0 +for (const a of printable) for (const b of printable) pairs.push(a + b) +for (let i = 0; i < pairs.length; i++) for (let j = i + 1; j < pairs.length; j++) if (cmp(pairs[i], pairs[j]) === 0) ties++ +console.log('pairs', pairs.length, 'ties', ties, hash([...pairs].sort(cmp))) +const alpha = ' !-._09aAzZ' +const triples: string[] = [] +for (const a of alpha) for (const b of alpha) for (const c of alpha) triples.push(a + b + c) +console.log('triples', triples.length, hash([...triples].sort(cmp))) +// LCG strings, length 1..8 over printable ASCII +let x = 1 +const next = () => { x = (Math.imul(x, 1103515245) + 12345) >>> 0 & 0x7fffffff; return x } +const randoms: string[] = [] +for (let i = 0; i < 4000; i++) { + const len = 1 + (next() % 8) + let s = '' + for (let k = 0; k < len; k++) s += printable[next() % 95] + randoms.push(s) +} +const uniq = [...new Set(randoms)] +let rties = 0 +const rs = [...uniq].sort(cmp) +for (let i = 0; i + 1 < rs.length; i++) if (cmp(rs[i], rs[i + 1]) === 0) rties++ +console.log('randoms', uniq.length, 'adjacent ties', rties, hash(rs), JSON.stringify(randoms.slice(0, 3))) +console.log('names', JSON.stringify(['Zip', 'age', 'a_b', 'a-b', 'ab', 'a b', 'A', 'a', 'aB', 'Ab', 'a1', 'a10', 'a2', 'x-bsv-a_b', 'x-bsv-ab', 'x-bsv-a-b', 'x-bsv-Z', 'x-bsv-z', 'email', 'Email', 'first_name', 'firstName', 'first-name'].sort(cmp))) +console.log('headers', JSON.stringify(['x-bsv-zeta', 'x-bsv-a-b', 'x-bsv-a_b', 'x-bsv-ab', 'x-bsv-a.b', 'x-bsv-a1', 'authorization', 'content-type'].sort(cmp))) +console.log(process.versions.bun, Intl.Collator().resolvedOptions().locale) +``` diff --git a/Documentation/Compatibility/VectorInventory.md b/Documentation/Compatibility/VectorInventory.md index c0f612c..5afb317 100644 --- a/Documentation/Compatibility/VectorInventory.md +++ b/Documentation/Compatibility/VectorInventory.md @@ -45,6 +45,16 @@ Wycheproof provenance recorded by the selected dependencies identifies Apache 2.0 and upstream commits. Copy source JSON, not generated headers, and preserve the dependency NOTICE information. +## Recorded TypeScript auth vectors + +| Family | Committed source | License | Notes | +| --- | --- | --- | --- | +| BRC-103/104 wire messages and BRC-104 payloads | Output of `@bsv/sdk` 4.1.1 at `ts-stack` `3b1abc5691c0848eb00eaf5e8f018e8a7a26d5f1`, recorded by the generator in [TypeScriptAuthVectors.md](TypeScriptAuthVectors.md) | Apache-2.0 (relicensed in `4760b26d0`, 2026-11-11) | `TypeScriptAuthVectors.swift`: handshake, certificate request and response, handshake certificates in initialResponse, empty-certifier request, mixed-case certificate signature and preimage, `AuthFetch` headers and serialized payloads, and an `AuthFetch` certificateResponse answering a Swift server's initialResponse policy. Live checks of Swift output in TypeScript run from the same scripts and are not committed. | +| `localeCompare` order | Output of `collate-vec.ts` under Bun 1.4.4 and Node 22.23.4 (ICU `en-US`) | Independently authored script; runtime output only | `LocaleCompareOrderTests.swift`: printable ASCII order, SHA-256 of all 9025 two-character strings, 1331 three-character strings and 4000 pseudo-random strings, and named examples. | + +See [FixtureSources.md](FixtureSources.md#recorded-typescript-auth-vectors) for +the provenance record. + ## Go-only behavior sources These are queried through the pinned oracle and are never copied: diff --git a/Sources/BSVAuth/AuthLog.swift b/Sources/BSVAuth/AuthLog.swift new file mode 100644 index 0000000..7ca4cf2 --- /dev/null +++ b/Sources/BSVAuth/AuthLog.swift @@ -0,0 +1,115 @@ +import Foundation +#if canImport(os) +import os +#endif + +/// The authentication log: subsystem `dev.opl.swift-sdk`, category `BSVAuth`. +/// +/// When a detailed error is reported to the caller as a shorter one, such as +/// a `BRC104Error` reported as `BRC104HTTPFramingError.invalidFrame`, the +/// detailed error is written here with its type and case. The reasons this +/// module writes hold no nonce, signature, payload, header value, certificate +/// field or key, and are public in the system log. +/// +/// An underlying error whose type this SDK defines is public too. Its cases +/// carry counts, sizes, names this SDK chose, and some carry the input text +/// that failed to parse, such as an unknown enum value or JSON key; none is +/// known to carry a key or a certificate field value. Any other underlying +/// error, such as one thrown by a caller's wallet, is public only by type: +/// its description is marked private, so whatever that code put in it does +/// not reach a shared log in clear. +package enum AuthLog { + package static let subsystem = "dev.opl.swift-sdk" + package static let category = "BSVAuth" + + /// One line about an underlying error, split where the privacy marker + /// changes: `detail` is private when `detailIsPrivate` is set. + package struct Entry: Sendable, Equatable { + package let prefix: String + package let detail: String + package let suffix: String + package let detailIsPrivate: Bool + + /// The line as a reader of the system log without private data sees it. + package var publicText: String { + prefix + (detailIsPrivate ? "" : detail) + suffix + } + } + + /// Receives each line as well as the system log, for tests. + @TaskLocal package static var observer: (@Sendable (String) -> Void)? + + /// Receives each underlying-error entry as it is passed to `os.Logger`, for tests. + @TaskLocal package static var entryObserver: (@Sendable (Entry) -> Void)? + + package static func error(_ message: String) { + observer?(message) + #if canImport(os) + Logger(subsystem: subsystem, category: category).error("\(message, privacy: .public)") + #endif + } + + /// Records the detailed error behind a shorter one the caller receives. + package static func reported( + _ operation: String, + _ underlying: any Error, + as reported: Reported + ) { + observer?(line(operation, underlying, as: reported)) + let entry = entry(operation, underlying, as: reported) + entryObserver?(entry) + #if canImport(os) + let logger = Logger(subsystem: subsystem, category: category) + if entry.detailIsPrivate { + logger.error( + "\(entry.prefix, privacy: .public)\(entry.detail, privacy: .private)\(entry.suffix, privacy: .public)" + ) + } else { + logger.error( + "\(entry.prefix, privacy: .public)\(entry.detail, privacy: .public)\(entry.suffix, privacy: .public)" + ) + } + #endif + } + + package static func entry( + _ operation: String, + _ underlying: any Error, + as reported: Reported + ) -> Entry { + Entry( + prefix: "\(operation): \(type(of: underlying)): ", + detail: String(reflecting: underlying), + suffix: "; reported as \(String(reflecting: reported))", + detailIsPrivate: !isSDKError(underlying)) + } + + /// Whether `error` is a type this SDK defines. + package static func isSDKError(_ error: any Error) -> Bool { + let module = String(reflecting: type(of: error)).prefix { $0 != "." } + return sdkModules.contains(String(module)) + } + + private static let sdkModules: Set = [ + "BSVAuth", "BSVCore", "BSVCrypto", "BSVKeys", "BSVMessage", "BSVScript", + "BSVTransaction", "BSVWallet", + ] + + /// Records why a check failed when the caller receives only `reported`. + package static func rejected( + _ operation: String, + _ reason: String, + as reported: Reported + ) { + error("\(operation): \(reason); reported as \(String(reflecting: reported))") + } + + package static func line( + _ operation: String, + _ underlying: any Error, + as reported: Reported + ) -> String { + let entry = entry(operation, underlying, as: reported) + return entry.prefix + entry.detail + entry.suffix + } +} diff --git a/Sources/BSVAuth/BRC103/AuthCertificateExchange.swift b/Sources/BSVAuth/BRC103/AuthCertificateExchange.swift index 1433cae..e1de3f1 100644 --- a/Sources/BSVAuth/BRC103/AuthCertificateExchange.swift +++ b/Sources/BSVAuth/BRC103/AuthCertificateExchange.swift @@ -44,12 +44,15 @@ public enum AuthCertificateExchange { else { continue } do { - guard try await certificate.verifySignature(limits: limits.certificateLimits) else { + guard try await certificate.verifySignatureInEitherFieldOrder(limits: limits.certificateLimits) else { throw AuthError.certificateValidationFailed } } catch is CancellationError { throw CancellationError() } catch { + AuthLog.reported( + "AuthCertificateExchange.prepare signature", error, + as: AuthError.certificateValidationFailed) throw AuthError.certificateValidationFailed } try Task.checkCancellation() @@ -65,6 +68,10 @@ public enum AuthCertificateExchange { ) try Task.checkCancellation() guard Set(proof.keyringForVerifier.keys) == Set(fields) else { + AuthLog.rejected( + "AuthCertificateExchange.prepare", + "the wallet proof does not reveal exactly the requested fields", + as: AuthError.certificateValidationFailed) throw AuthError.certificateValidationFailed } let verifiable = try VerifiableCertificate( @@ -84,6 +91,10 @@ public enum AuthCertificateExchange { } guard foundTypes == Set(request.certificateTypes.keys), !result.isEmpty else { + AuthLog.rejected( + "AuthCertificateExchange.prepare", + "the wallet holds \(foundTypes.count) of \(request.certificateTypes.count) requested types", + as: AuthError.certificateValidationFailed) throw AuthError.certificateValidationFailed } return result @@ -91,6 +102,10 @@ public enum AuthCertificateExchange { /// Verifies certificate signatures, request matching, subject binding, and /// every disclosed field. The result is all-or-nothing. + /// + /// Every requested type must be present and every certificate must + /// reveal every requested field of its type. Use `validateSubset` to + /// accept any allowed subset, as `@bsv/sdk` does. public static func validate( _ certificates: [VerifiableCertificate], from peer: PublicKey, @@ -98,23 +113,80 @@ public enum AuthCertificateExchange { using wallet: any CertificateWallet, limits: AuthLimits = .standard ) async throws -> [AuthValidatedCertificate] { - guard !certificates.isEmpty, - certificates.count <= limits.maximumCertificateCount - else { throw AuthError.certificateValidationFailed } + try await validate( + certificates, from: peer, requested: request, using: wallet, limits: limits, + complete: true) + } + + /// Verifies certificates that answer a request as an allowlist, as + /// `validateCertificates` in `@bsv/sdk` does (`validateCertificates.ts:23-29`). + /// + /// Each certificate must be signed by a requested certifier, be of a + /// requested type, name `peer` as subject, and reveal a nonempty subset of + /// that type's requested fields, all of which must decrypt. Types and + /// fields that were requested but not supplied are allowed: the result + /// holds exactly what was disclosed, and the caller decides whether that + /// is enough. No certificates fails, as `validateCertificates.ts:74` + /// does, so a returned value always holds at least one certificate. Any + /// certificate that fails makes the whole call fail. + public static func validateSubset( + _ certificates: [VerifiableCertificate], + from peer: PublicKey, + requested request: AuthRequestedCertificateSet, + using wallet: any CertificateWallet, + limits: AuthLimits = .standard + ) async throws -> [AuthValidatedCertificate] { + try await validate( + certificates, from: peer, requested: request, using: wallet, limits: limits, + complete: false) + } + + private static func validate( + _ certificates: [VerifiableCertificate], + from peer: PublicKey, + requested request: AuthRequestedCertificateSet, + using wallet: any CertificateWallet, + limits: AuthLimits, + complete: Bool + ) async throws -> [AuthValidatedCertificate] { + let operation = complete ? "AuthCertificateExchange.validate" : "AuthCertificateExchange.validateSubset" + func reject(_ reason: String) -> AuthError { + AuthLog.rejected(operation, reason, as: AuthError.certificateValidationFailed) + return AuthError.certificateValidationFailed + } + guard !certificates.isEmpty else { throw reject("no certificates") } + guard certificates.count <= limits.maximumCertificateCount else { + throw reject("\(certificates.count) certificates exceed the limit") + } var aggregate = 0 var foundTypes = Set() var result: [AuthValidatedCertificate] = [] result.reserveCapacity(certificates.count) - for verifiable in certificates { + for (position, verifiable) in certificates.enumerated() { try Task.checkCancellation() let certificate = verifiable.certificate - guard certificate.subject == peer, - request.certifiers.contains(certificate.certifier), - let fields = request.certificateTypes[certificate.type], - Set(verifiable.keyring.entries.keys) == Set(fields) - else { throw AuthError.certificateValidationFailed } + guard certificate.subject == peer else { + throw reject("certificate \(position) names another subject") + } + guard request.certifiers.contains(certificate.certifier) else { + throw reject("certificate \(position) has a certifier that was not requested") + } + guard let fields = request.certificateTypes[certificate.type] else { + throw reject("certificate \(position) has a type that was not requested") + } + let revealed = Set(verifiable.keyring.entries.keys) + if complete { + guard revealed == Set(fields) else { + throw reject("certificate \(position) does not reveal exactly the requested fields") + } + } else { + guard !revealed.isEmpty, revealed.isSubset(of: Set(fields)) else { + throw reject( + "certificate \(position) reveals no field or a field that was not requested") + } + } try addEnvelopeSize( verifiable, @@ -131,11 +203,14 @@ public enum AuthCertificateExchange { } catch is CancellationError { throw CancellationError() } catch { + AuthLog.reported( + "\(operation) certificate \(position)", error, + as: AuthError.certificateValidationFailed) throw AuthError.certificateValidationFailed } try Task.checkCancellation() - guard Set(plaintext.keys) == Set(fields) else { - throw AuthError.certificateValidationFailed + guard Set(plaintext.keys) == revealed else { + throw reject("certificate \(position) decrypted to other fields than it reveals") } result.append( AuthValidatedCertificate( @@ -146,8 +221,8 @@ public enum AuthCertificateExchange { foundTypes.insert(certificate.type) } - guard foundTypes == Set(request.certificateTypes.keys) else { - throw AuthError.certificateValidationFailed + guard !complete || foundTypes == Set(request.certificateTypes.keys) else { + throw reject("\(request.certificateTypes.count - foundTypes.count) requested types are missing") } return result } diff --git a/Sources/BSVAuth/BRC103/AuthCertificateJSON.swift b/Sources/BSVAuth/BRC103/AuthCertificateJSON.swift index 03977b3..fd290f0 100644 --- a/Sources/BSVAuth/BRC103/AuthCertificateJSON.swift +++ b/Sources/BSVAuth/BRC103/AuthCertificateJSON.swift @@ -1,7 +1,21 @@ import BSVCore import BSVWallet +/// The JSON text that BRC-103 certificate messages sign. +/// +/// `@bsv/sdk` 4.1.1 signs `JSON.stringify(requestedCertificates)` and +/// `JSON.stringify(certificates)` (`Peer.ts:453`, `Peer.ts:1142`) and verifies +/// `JSON.stringify` of the received objects (`Peer.ts:1070`, `Peer.ts:1205`). +/// The signed text therefore follows the sender's member order and +/// `JSON.stringify` escaping. This SDK writes the wire JSON from the same bytes +/// it signs, so a TypeScript verifier reproduces them exactly. enum AuthCertificateJSON { + /// Member order of a certificate rebuilt by `Peer.ts:341-357`. + static let certificateMemberOrder = [ + "type", "serialNumber", "subject", "certifier", "revocationOutpoint", "fields", + "signature", "keyring", + ] + static func request( _ request: AuthRequestedCertificateSet, limits: AuthLimits @@ -11,27 +25,26 @@ enum AuthCertificateJSON { certificateTypes: request.certificateTypes, limits: limits ) - var writer = AuthCertificateJSONWriter(maximumByteCount: maximumJSONBytes(limits)) + var writer = AuthJSONWriter(maximumByteCount: maximumJSONBytes(limits)) try writer.append(#"{"certifiers":["#) for index in request.certifiers.indices { if index > 0 { try writer.append(",") } - try writer.appendJSONString(Hex.encode(request.certifiers[index].compressedBytes)) + try writer.appendString(Hex.encode(request.certifiers[index].compressedBytes)) } try writer.append(#"],"types":{"#) - let types = request.certificateTypes.keys.sorted { - $0.base64.utf8.lexicographicallyPrecedes($1.base64.utf8) - } - for index in types.indices { + var typesByText: [String: [CertificateFieldName]] = [:] + for (type, fields) in request.certificateTypes { typesByText[type.base64] = fields } + let names = AuthJSONWriter.canonicalOrder(Array(typesByText.keys)) + for index in names.indices { if index > 0 { try writer.append(",") } - let type = types[index] - try writer.appendJSONString(type.base64) + try writer.appendString(names[index]) try writer.append(":[") - guard let fields = request.certificateTypes[type] else { + guard let fields = typesByText[names[index]] else { throw AuthError.invalidCertificateRequest } for fieldIndex in fields.indices { if fieldIndex > 0 { try writer.append(",") } - try writer.appendJSONString(fields[fieldIndex].value) + try writer.appendString(fields[fieldIndex].value) } try writer.append("]") } @@ -43,9 +56,9 @@ enum AuthCertificateJSON { _ certificates: [VerifiableCertificate], limits: AuthLimits ) throws -> [UInt8] { - guard !certificates.isEmpty, - certificates.count <= limits.maximumCertificateCount - else { throw AuthError.certificateValidationFailed } + guard certificates.count <= limits.maximumCertificateCount else { + throw AuthError.certificateValidationFailed + } var aggregate = 0 for verifiable in certificates { @@ -57,7 +70,7 @@ enum AuthCertificateJSON { aggregate = next } - var writer = AuthCertificateJSONWriter(maximumByteCount: maximumJSONBytes(limits)) + var writer = AuthJSONWriter(maximumByteCount: maximumJSONBytes(limits)) try writer.append("[") for index in certificates.indices { if index > 0 { try writer.append(",") } @@ -67,9 +80,47 @@ enum AuthCertificateJSON { return writer.bytes } + /// `JSON.stringify` of a received `requestedCertificates` value, as + /// `Peer.ts:1070` computes it. + static func receivedRequest(_ value: AuthJSONValue, limits: AuthLimits) throws -> [UInt8] { + var writer = AuthJSONWriter(maximumByteCount: maximumJSONBytes(limits)) + try writer.appendValue(value) + return writer.bytes + } + + /// `JSON.stringify` of received certificates after `Peer.ts:341-357` + /// rebuilds each one in `certificateMemberOrder`. `fields` and `keyring` + /// keep their received member order. + static func receivedResponse(_ value: AuthJSONValue, limits: AuthLimits) throws -> [UInt8] { + guard case .array(let certificates) = value else { + throw AuthError.certificateValidationFailed + } + var writer = AuthJSONWriter(maximumByteCount: maximumJSONBytes(limits)) + try writer.append("[") + for index in certificates.indices { + if index > 0 { try writer.append(",") } + guard case .object(let members) = certificates[index] else { + throw AuthError.certificateValidationFailed + } + try writer.append("{") + var written = 0 + for name in certificateMemberOrder { + guard let member = members.first(where: { $0.key == name }) else { continue } + if written > 0 { try writer.append(",") } + try writer.appendString(name) + try writer.append(":") + try writer.appendValue(member.value) + written += 1 + } + try writer.append("}") + } + try writer.append("]") + return writer.bytes + } + private static func append( _ verifiable: VerifiableCertificate, - to writer: inout AuthCertificateJSONWriter, + to writer: inout AuthJSONWriter, limits: AuthLimits ) throws { let certificate = verifiable.certificate @@ -79,19 +130,19 @@ enum AuthCertificateJSON { else { throw AuthError.certificateValidationFailed } try writer.append(#"{"type":"#) - try writer.appendJSONString(certificate.type.base64) + try writer.appendString(certificate.type.base64) try writer.append(#","serialNumber":"#) - try writer.appendJSONString(certificate.serialNumber.base64) + try writer.appendString(certificate.serialNumber.base64) try writer.append(#","subject":"#) - try writer.appendJSONString(Hex.encode(certificate.subject.compressedBytes)) + try writer.appendString(Hex.encode(certificate.subject.compressedBytes)) try writer.append(#","certifier":"#) - try writer.appendJSONString(Hex.encode(certificate.certifier.compressedBytes)) + try writer.appendString(Hex.encode(certificate.certifier.compressedBytes)) try writer.append(#","revocationOutpoint":"#) - try writer.appendJSONString(certificate.revocationOutpoint.description) + try writer.appendString(certificate.revocationOutpoint.description) try writer.append(#","fields":{"#) try appendMap(certificate.fields, to: &writer) { $0.base64 } try writer.append(#"},"signature":"#) - try writer.appendJSONString(Hex.encode(signature.derBytes)) + try writer.appendString(Hex.encode(signature.derBytes)) try writer.append(#","keyring":{"#) try appendMap(verifiable.keyring.entries, to: &writer) { $0.base64 } try writer.append("}}") @@ -99,17 +150,19 @@ enum AuthCertificateJSON { private static func appendMap( _ values: [CertificateFieldName: Value], - to writer: inout AuthCertificateJSONWriter, + to writer: inout AuthJSONWriter, value: (Value) -> String ) throws { - let names = values.keys.sorted() + var byText: [String: Value] = [:] + for (name, item) in values { byText[name.value] = item } + guard byText.count == values.count else { throw AuthError.invalidMessage } + let names = AuthJSONWriter.canonicalOrder(Array(byText.keys)) for index in names.indices { if index > 0 { try writer.append(",") } - let name = names[index] - guard let item = values[name] else { throw AuthError.invalidMessage } - try writer.appendJSONString(name.value) + guard let item = byText[names[index]] else { throw AuthError.invalidMessage } + try writer.appendString(names[index]) try writer.append(":") - try writer.appendJSONString(value(item)) + try writer.appendString(value(item)) } } @@ -117,55 +170,3 @@ enum AuthCertificateJSON { min(limits.maximumJSONBytes, limits.maximumCertificateAggregateBytes) } } - -private struct AuthCertificateJSONWriter { - private(set) var bytes: [UInt8] = [] - private let maximumByteCount: Int - - init(maximumByteCount: Int) { - self.maximumByteCount = maximumByteCount - bytes.reserveCapacity(min(maximumByteCount, 4_096)) - } - - mutating func append(_ text: String) throws { - try append(Array(text.utf8)) - } - - mutating func appendJSONString(_ text: String) throws { - try append([0x22]) - for scalar in text.unicodeScalars { - switch scalar.value { - case 0x08: try append(#"\b"#) - case 0x09: try append(#"\t"#) - case 0x0a: try append(#"\n"#) - case 0x0c: try append(#"\f"#) - case 0x0d: try append(#"\r"#) - case 0x22: try append(#"\""#) - case 0x5c: try append(#"\\"#) - case 0x00...0x07, 0x0b, 0x0e...0x1f, 0x26, 0x3c, 0x3e, 0x2028, 0x2029: - try appendUnicodeEscape(scalar.value) - default: - try append(Array(String(scalar).utf8)) - } - } - try append([0x22]) - } - - private mutating func appendUnicodeEscape(_ value: UInt32) throws { - let digits = Array("0123456789abcdef".utf8) - guard value <= 0xffff else { throw AuthError.invalidMessage } - try append([ - 0x5c, 0x75, - digits[Int((value >> 12) & 0x0f)], - digits[Int((value >> 8) & 0x0f)], - digits[Int((value >> 4) & 0x0f)], - digits[Int(value & 0x0f)], - ]) - } - - private mutating func append(_ value: [UInt8]) throws { - let (next, overflow) = bytes.count.addingReportingOverflow(value.count) - guard !overflow, next <= maximumByteCount else { throw AuthError.resourceLimit } - bytes.append(contentsOf: value) - } -} diff --git a/Sources/BSVAuth/BRC103/AuthJSON.swift b/Sources/BSVAuth/BRC103/AuthJSON.swift new file mode 100644 index 0000000..c8abf87 --- /dev/null +++ b/Sources/BSVAuth/BRC103/AuthJSON.swift @@ -0,0 +1,408 @@ +/// A JSON value that keeps object members in the order they arrived. +/// +/// Certificate request and response signatures cover `JSON.stringify` output of +/// the received objects (`Peer.ts:1070`, `Peer.ts:1205` in `@bsv/sdk` 4.1.1). +/// `JSON.stringify` writes members in insertion order, so a verifier must keep +/// the order the sender used. Foundation's `JSONSerialization` does not. +indirect enum AuthJSONValue: Equatable { + case null + case bool(Bool) + case number(String) + case string(String) + case array([AuthJSONValue]) + case object([AuthJSONMember]) + + subscript(key: String) -> AuthJSONValue? { + guard case .object(let members) = self else { return nil } + return members.first { $0.key == key }?.value + } +} + +struct AuthJSONMember: Equatable { + let key: String + let value: AuthJSONValue +} + +/// Strict JSON parser for BRC-103 envelopes. +/// +/// It rejects duplicate object keys (compared after unescaping), invalid UTF-8, +/// lone surrogate escapes, control characters, excessive nesting, and trailing +/// data. Only the top-level members named in `retaining` are materialized; the +/// rest is validated and skipped so large payload arrays are not copied twice. +struct AuthJSONParser { + static let maximumNestingDepth = 64 + + private let bytes: [UInt8] + private var offset = 0 + + private init(bytes: [UInt8]) { self.bytes = bytes } + + /// Validates a complete envelope and returns the retained top-level members. + static func parseEnvelope( + _ bytes: [UInt8], + retaining names: Set + ) throws -> [String: AuthJSONValue] { + var parser = Self(bytes: bytes) + try parser.skipWhitespace() + guard parser.peek() == 0x7b else { throw AuthError.invalidMessage } + var retained: [String: AuthJSONValue] = [:] + try parser.parseObject(depth: 1, build: false) { key, parser, depth in + if names.contains(key) { + retained[key] = try parser.parseValue(depth: depth, build: true) + } else { + _ = try parser.parseValue(depth: depth, build: false) + } + } + try parser.skipWhitespace() + guard parser.offset == bytes.count else { throw AuthError.invalidMessage } + return retained + } + + /// Parses one complete JSON document into an ordered tree. + static func parse(_ bytes: [UInt8]) throws -> AuthJSONValue { + var parser = Self(bytes: bytes) + try parser.skipWhitespace() + guard let value = try parser.parseValue(depth: 0, build: true) else { + throw AuthError.invalidMessage + } + try parser.skipWhitespace() + guard parser.offset == bytes.count else { throw AuthError.invalidMessage } + return value + } + + private mutating func parseValue(depth: Int, build: Bool) throws -> AuthJSONValue? { + guard depth <= Self.maximumNestingDepth, let byte = peek() else { + throw AuthError.invalidMessage + } + switch byte { + case 0x7b: + var members: [AuthJSONMember] = [] + try parseObject(depth: depth + 1, build: build) { key, parser, depth in + let value = try parser.parseValue(depth: depth, build: build) + if build, let value { members.append(.init(key: key, value: value)) } + } + return build ? .object(members) : nil + case 0x5b: + return try parseArray(depth: depth + 1, build: build) + case 0x22: + let text = try parseString() + return build ? .string(text) : nil + case 0x74: + try consumeLiteral("true") + return .bool(true) + case 0x66: + try consumeLiteral("false") + return .bool(false) + case 0x6e: + try consumeLiteral("null") + return .null + case 0x2d, 0x30...0x39: + let start = offset + try parseNumber() + return build ? .number(String(decoding: bytes[start.. Void + ) throws { + guard depth <= Self.maximumNestingDepth else { throw AuthError.invalidMessage } + try consume(0x7b) + try skipWhitespace() + if consumeIfPresent(0x7d) { return } + var names = Set() + while true { + guard peek() == 0x22 else { throw AuthError.invalidMessage } + let key = try parseString() + guard names.insert(key).inserted else { throw AuthError.invalidMessage } + try skipWhitespace() + try consume(0x3a) + try skipWhitespace() + try member(key, &self, depth) + try skipWhitespace() + if consumeIfPresent(0x7d) { return } + try consume(0x2c) + try skipWhitespace() + } + } + + private mutating func parseArray(depth: Int, build: Bool) throws -> AuthJSONValue? { + guard depth <= Self.maximumNestingDepth else { throw AuthError.invalidMessage } + try consume(0x5b) + try skipWhitespace() + var values: [AuthJSONValue] = [] + if consumeIfPresent(0x5d) { return build ? .array(values) : nil } + while true { + let value = try parseValue(depth: depth, build: build) + if build, let value { values.append(value) } + try skipWhitespace() + if consumeIfPresent(0x5d) { return build ? .array(values) : nil } + try consume(0x2c) + try skipWhitespace() + } + } + + private mutating func parseString() throws -> String { + try consume(0x22) + var scalars = String.UnicodeScalarView() + var run = offset + func flush(_ end: Int) throws { + guard run < end else { return } + var iterator = bytes[run.. Unicode.Scalar { + guard let escaped = peek() else { throw AuthError.invalidMessage } + offset += 1 + switch escaped { + case 0x22: return "\"" + case 0x5c: return "\\" + case 0x2f: return "/" + case 0x62: return "\u{08}" + case 0x66: return "\u{0c}" + case 0x6e: return "\n" + case 0x72: return "\r" + case 0x74: return "\t" + case 0x75: + let first = try parseHex4() + if (0xd800...0xdbff).contains(first) { + guard consumeIfPresent(0x5c), consumeIfPresent(0x75) else { + throw AuthError.invalidMessage + } + let second = try parseHex4() + guard (0xdc00...0xdfff).contains(second) else { throw AuthError.invalidMessage } + let value = 0x10000 + ((first - 0xd800) << 10) + (second - 0xdc00) + guard let scalar = Unicode.Scalar(value) else { throw AuthError.invalidMessage } + return scalar + } + guard let scalar = Unicode.Scalar(first) else { throw AuthError.invalidMessage } + return scalar + default: + throw AuthError.invalidMessage + } + } + + private mutating func parseHex4() throws -> UInt32 { + guard bytes.count - offset >= 4 else { throw AuthError.invalidMessage } + var value: UInt32 = 0 + for _ in 0..<4 { + let byte = bytes[offset] + let digit: UInt32 + switch byte { + case 0x30...0x39: digit = UInt32(byte - 0x30) + case 0x41...0x46: digit = UInt32(byte - 0x41 + 10) + case 0x61...0x66: digit = UInt32(byte - 0x61 + 10) + default: throw AuthError.invalidMessage + } + value = value << 4 | digit + offset += 1 + } + return value + } + + private mutating func parseNumber() throws { + _ = consumeIfPresent(0x2d) + guard let first = peek() else { throw AuthError.invalidMessage } + if first == 0x30 { + offset += 1 + if let next = peek(), isDigit(next) { throw AuthError.invalidMessage } + } else { + guard (0x31...0x39).contains(first) else { throw AuthError.invalidMessage } + skipDigits() + } + if consumeIfPresent(0x2e) { + guard let next = peek(), isDigit(next) else { throw AuthError.invalidMessage } + skipDigits() + } + if let next = peek(), next == 0x65 || next == 0x45 { + offset += 1 + if let sign = peek(), sign == 0x2b || sign == 0x2d { offset += 1 } + guard let digit = peek(), isDigit(digit) else { throw AuthError.invalidMessage } + skipDigits() + } + } + + private mutating func skipDigits() { + while let byte = peek(), isDigit(byte) { offset += 1 } + } + + private mutating func consumeLiteral(_ literal: StaticString) throws { + let expected = Array(String(describing: literal).utf8) + guard bytes.count - offset >= expected.count, + bytes[offset..<(offset + expected.count)].elementsEqual(expected) + else { throw AuthError.invalidMessage } + offset += expected.count + } + + private mutating func skipWhitespace() throws { + while let byte = peek(), byte == 0x20 || byte == 0x09 || byte == 0x0a || byte == 0x0d { + offset += 1 + } + } + + private mutating func consume(_ expected: UInt8) throws { + guard consumeIfPresent(expected) else { throw AuthError.invalidMessage } + } + + private mutating func consumeIfPresent(_ expected: UInt8) -> Bool { + guard peek() == expected else { return false } + offset += 1 + return true + } + + private func peek() -> UInt8? { offset < bytes.count ? bytes[offset] : nil } + + private func isDigit(_ byte: UInt8) -> Bool { (0x30...0x39).contains(byte) } +} + +/// Writes JSON exactly as ECMAScript `JSON.stringify` does for strings, +/// arrays and plain objects. +/// +/// - Object members follow ECMAScript property order: array-index keys first in +/// ascending numeric order, then the other keys in insertion order. This is +/// the order a TypeScript peer sees after `JSON.parse`. +/// - Strings escape only `"`, `\`, `\b`, `\t`, `\n`, `\f`, `\r` and the other +/// C0 controls (as lowercase `\u00xx`). `/`, `&`, `<`, `>`, U+2028 and U+2029 +/// are written as they are. +struct AuthJSONWriter { + private(set) var bytes: [UInt8] = [] + private let maximumByteCount: Int + + init(maximumByteCount: Int) { + self.maximumByteCount = maximumByteCount + bytes.reserveCapacity(min(maximumByteCount, 4_096)) + } + + mutating func append(_ text: String) throws { + try append(Array(text.utf8)) + } + + mutating func append(_ value: [UInt8]) throws { + let (next, overflow) = bytes.count.addingReportingOverflow(value.count) + guard !overflow, next <= maximumByteCount else { throw AuthError.resourceLimit } + bytes.append(contentsOf: value) + } + + mutating func appendString(_ text: String) throws { + try append([0x22]) + var run: [UInt8] = [] + for scalar in text.unicodeScalars { + let escape: String? + switch scalar.value { + case 0x08: escape = #"\b"# + case 0x09: escape = #"\t"# + case 0x0a: escape = #"\n"# + case 0x0c: escape = #"\f"# + case 0x0d: escape = #"\r"# + case 0x22: escape = #"\""# + case 0x5c: escape = #"\\"# + case 0x00...0x1f: + let digits = Array("0123456789abcdef") + escape = "\\u00" + String(digits[Int(scalar.value >> 4)]) + + String(digits[Int(scalar.value & 0x0f)]) + default: escape = nil + } + if let escape { + run.append(contentsOf: escape.utf8) + } else { + run.append(contentsOf: String(scalar).utf8) + } + } + try append(run) + try append([0x22]) + } + + /// Writes `value` as `JSON.stringify(JSON.parse(text))` would. + mutating func appendValue(_ value: AuthJSONValue) throws { + switch value { + case .null: try append("null") + case .bool(let flag): try append(flag ? "true" : "false") + case .number: + // No certificate request or response member is numeric. ECMAScript + // would renormalize the number text, so refuse instead of guessing. + throw AuthError.invalidMessage + case .string(let text): try appendString(text) + case .array(let values): + try append("[") + for index in values.indices { + if index > 0 { try append(",") } + try appendValue(values[index]) + } + try append("]") + case .object(let members): + try append("{") + for (index, member) in Self.ecmaScriptOrder(members).enumerated() { + if index > 0 { try append(",") } + try appendString(member.key) + try append(":") + try appendValue(member.value) + } + try append("}") + } + } + + /// ECMAScript `OrdinaryOwnPropertyKeys` order for string keys. + static func ecmaScriptOrder(_ members: [AuthJSONMember]) -> [AuthJSONMember] { + let indexed = members.compactMap { member in + arrayIndex(member.key).map { (index: $0, member: member) } + } + guard !indexed.isEmpty else { return members } + return indexed.sorted { $0.index < $1.index }.map(\.member) + + members.filter { arrayIndex($0.key) == nil } + } + + /// Orders names the way this SDK writes them: array-index names first (as + /// ECMAScript places them), then the rest by UTF-8 bytes. + static func canonicalOrder(_ names: [String]) -> [String] { + names.sorted { lhs, rhs in + switch (arrayIndex(lhs), arrayIndex(rhs)) { + case (let left?, let right?): return left < right + case (.some, .none): return true + case (.none, .some): return false + case (.none, .none): return lhs.utf8.lexicographicallyPrecedes(rhs.utf8) + } + } + } + + /// A canonical decimal array index below 2^32 - 1, as ECMAScript defines it. + static func arrayIndex(_ key: String) -> UInt32? { + let utf8 = Array(key.utf8) + guard !utf8.isEmpty, utf8.count <= 10, utf8.allSatisfy({ (0x30...0x39).contains($0) }), + utf8.count == 1 || utf8[0] != 0x30, + let value = UInt64(key), value < 0xffff_ffff + else { return nil } + return UInt32(value) + } +} diff --git a/Sources/BSVAuth/BRC103/AuthModels.swift b/Sources/BSVAuth/BRC103/AuthModels.swift index 20b6d7d..3be033f 100644 --- a/Sources/BSVAuth/BRC103/AuthModels.swift +++ b/Sources/BSVAuth/BRC103/AuthModels.swift @@ -6,8 +6,14 @@ public typealias AuthenticationWallet = WalletPublicKeyProviding & WalletSignatu /// The certificate types, certifiers, and disclosed fields that a peer requests. /// -/// An instance is always nonempty. Use `nil` on `AuthMessage` when no -/// certificates are requested. +/// A set with no certifiers asks for nothing. `@bsv/sdk` 4.1.1 sends one as +/// `{"certifiers":[],"types":{}}` and treats it as no request +/// (`Peer.ts:836-838`, `Peer.ts:1097-1100`); `PeerAuthenticator` does the same. +/// +/// As in `@bsv/sdk` 4.1.1 (`AuthMessageValidation.ts:122-180`), the type map +/// and each field list may be empty. The set is an allowlist: a response may +/// carry any subset of the listed types and a nonempty subset of each type's +/// fields. `AuthCertificateExchange.validate` checks completeness. public struct AuthRequestedCertificateSet: Equatable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable @@ -20,8 +26,7 @@ public struct AuthRequestedCertificateSet: certificateTypes: [CertificateTypeID: [CertificateFieldName]], limits: AuthLimits = .standard ) throws { - guard !certifiers.isEmpty, !certificateTypes.isEmpty, - certifiers.count <= limits.maximumCertificateCertifierCount, + guard certifiers.count <= limits.maximumCertificateCertifierCount, certificateTypes.count <= limits.maximumCertificateTypeCount, Set(certifiers).count == certifiers.count else { throw AuthError.invalidCertificateRequest } @@ -33,8 +38,7 @@ public struct AuthRequestedCertificateSet: else { throw AuthError.resourceLimit } var aggregate = certifierBytes for fields in certificateTypes.values { - guard !fields.isEmpty, - fields.count <= limits.maximumCertificateFieldCount, + guard fields.count <= limits.maximumCertificateFieldCount, Set(fields).count == fields.count else { throw AuthError.invalidCertificateRequest } let (fieldBytes, overflow) = fields.reduce(into: (0, false)) { result, field in @@ -52,6 +56,16 @@ public struct AuthRequestedCertificateSet: self.certificateTypes = certificateTypes } + /// The bytes the set is charged in `AuthLimits.maximumCertificateAggregateBytes`: + /// 33 per certifier, and 32 per type plus the UTF-8 length of its field names. + /// `init` keeps this within the limit, so the sum cannot overflow. + var accountedBytes: Int { + certifiers.count * 33 + + certificateTypes.values.reduce(0) { total, fields in + total + 32 + fields.reduce(0) { $0 + $1.value.utf8.count } + } + } + public var description: String { "" } public var debugDescription: String { description } public var customMirror: Mirror { @@ -115,6 +129,11 @@ public struct AuthReceivedMessage: Equatable, Sendable, CustomStringConvertible, Mirror(self, children: EmptyCollection<(label: String?, value: Any)>()) } } +/// A certificate request from a peer. +/// +/// A request carried in `initialRequest` arrives before the peer has signed +/// anything, so `peer` is only the identity it claims. Answer it only with +/// wallet-proved keyrings, which are encrypted to that identity. public struct AuthReceivedCertificateRequest: Equatable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable @@ -132,9 +151,12 @@ public struct AuthReceivedCertificateResponse: Equatable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { - /// The peer response signature is valid. Call - /// `AuthCertificateExchange.validate` before you trust the certificates or - /// disclosed fields. + /// Certificates the peer sent for `requested`. From a certificateResponse + /// message, the peer's message signature over them is valid. From an + /// `initialResponse`, they are not covered by any message signature + /// (`Peer.ts:912-915`). In both cases call `AuthCertificateExchange.validate` + /// or `validateSubset` before you trust the certificates or disclosed + /// fields. public let sessionID: AuthSessionID public let peer: PublicKey public let requested: AuthRequestedCertificateSet @@ -175,12 +197,29 @@ public struct AuthMessage: Equatable, Sendable, CustomStringConvertible, public let signature: [UInt8]? public let certificates: [VerifiableCertificate]? public let requestedCertificates: AuthRequestedCertificateSet? + /// The certificate JSON text a decoded certificate message signs, rebuilt + /// from the received member order. `nil` for messages built in memory. + let receivedSigningBytes: [UInt8]? public init( version: String = "0.1", messageType: AuthMessageType, identityKey: PublicKey, nonce: String? = nil, initialNonce: String? = nil, yourNonce: String? = nil, payload: [UInt8]? = nil, signature: [UInt8]? = nil, certificates: [VerifiableCertificate]? = nil, requestedCertificates: AuthRequestedCertificateSet? = nil + ) { + self.init( + version: version, messageType: messageType, identityKey: identityKey, nonce: nonce, + initialNonce: initialNonce, yourNonce: yourNonce, payload: payload, + signature: signature, certificates: certificates, + requestedCertificates: requestedCertificates, receivedSigningBytes: nil) + } + init( + version: String, messageType: AuthMessageType, identityKey: PublicKey, + nonce: String?, initialNonce: String?, yourNonce: String?, + payload: [UInt8]?, signature: [UInt8]?, + certificates: [VerifiableCertificate]?, + requestedCertificates: AuthRequestedCertificateSet?, + receivedSigningBytes: [UInt8]? ) { self.version = version self.messageType = messageType @@ -192,6 +231,17 @@ public struct AuthMessage: Equatable, Sendable, CustomStringConvertible, self.signature = signature self.certificates = certificates self.requestedCertificates = requestedCertificates + self.receivedSigningBytes = receivedSigningBytes + } + /// Compares the message content. The received member order is transport + /// detail and is not part of equality. + public static func == (lhs: AuthMessage, rhs: AuthMessage) -> Bool { + lhs.version == rhs.version && lhs.messageType == rhs.messageType + && lhs.identityKey == rhs.identityKey && lhs.nonce == rhs.nonce + && lhs.initialNonce == rhs.initialNonce && lhs.yourNonce == rhs.yourNonce + && lhs.payload == rhs.payload && lhs.signature == rhs.signature + && lhs.certificates == rhs.certificates + && lhs.requestedCertificates == rhs.requestedCertificates } public var description: String { "" } public var debugDescription: String { description } @@ -200,17 +250,22 @@ public struct AuthMessage: Equatable, Sendable, CustomStringConvertible, } } -/// Bounds on what a peer accepts. +/// Resource limits for BRC-103 messages and sessions. +/// +/// The defaults accept everything `@bsv/sdk` 4.1.1 sends: a 16 MiB message +/// (`AuthMessageValidation.ts:8`), an authenticated response frame of 16 MiB +/// plus 512 KiB of framing (`clients/AuthFetch.ts:147`, `:571`), and 100 +/// certificates, certifiers and types (`AuthMessageValidation.ts:12-14`). /// -/// `maximumPayloadBytes` bounds a general message's payload, which over HTTP is the whole BRC-104 -/// request or response: its body plus a few hundred bytes of framing. The default is 16 MiB, the -/// TypeScript SDK's `MAX_AUTH_MESSAGE_BYTES` and `AuthFetch`'s request frame limit -/// (`MAX_AUTH_HTTP_REQUEST_FRAME_BYTES`), so a reply a TypeScript client reads is one this one -/// reads too. At 1 MiB, a wallet storage reply carrying a photo inscription's transaction was -/// refused before it was read. +/// Over HTTP `maximumPayloadBytes` bounds the whole BRC-104 request or response, +/// its body plus framing. At 1 MiB a wallet storage reply carrying a photo +/// inscription's transaction was refused before it was read. public struct AuthLimits: Equatable, Sendable { public static let maximumAllowedJSONBytes = 64 << 20 - public static let maximumAllowedPayloadBytes = 16 << 20 + public static let maximumAllowedPayloadBytes = 32 << 20 + /// 16 MiB plus 512 KiB, shared with `WalletCryptoLimits.defaultPayloadByteCount` so the + /// default wallet can sign and verify every payload these limits accept. + public static let defaultPayloadBytes = WalletCryptoLimits.defaultPayloadByteCount public static let maximumAllowedSessions = 65_536 public static let maximumAllowedSessionsPerIdentity = 4_096 public static let maximumAllowedPendingSessions = 65_536 @@ -235,11 +290,12 @@ public struct AuthLimits: Equatable, Sendable { public let certificateLimits: CertificateLimits public let handshakeTimeout: Duration public init( - maximumJSONBytes: Int = 8 << 20, maximumPayloadBytes: Int = 16 << 20, + maximumJSONBytes: Int = 16 << 20, + maximumPayloadBytes: Int = AuthLimits.defaultPayloadBytes, maximumSessions: Int = 1024, maximumSessionsPerIdentity: Int = 8, maximumPendingSessions: Int = 128, maximumMessages: Int = 4096, - maximumCertificateCount: Int = 64, maximumCertificateCertifierCount: Int = 64, - maximumCertificateTypeCount: Int = 64, maximumCertificateFieldCount: Int = 256, + maximumCertificateCount: Int = 100, maximumCertificateCertifierCount: Int = 100, + maximumCertificateTypeCount: Int = 100, maximumCertificateFieldCount: Int = 256, maximumCertificateAggregateBytes: Int = 8 << 20, certificateLimits: CertificateLimits = .standard, handshakeTimeout: Duration = .seconds(30) @@ -278,15 +334,15 @@ public struct AuthLimits: Equatable, Sendable { self.handshakeTimeout = handshakeTimeout } private init(standard: Void) { - maximumJSONBytes = 8 << 20 - maximumPayloadBytes = 16 << 20 + maximumJSONBytes = 16 << 20 + maximumPayloadBytes = Self.defaultPayloadBytes maximumSessions = 1024 maximumSessionsPerIdentity = 8 maximumPendingSessions = 128 maximumMessages = 4096 - maximumCertificateCount = 64 - maximumCertificateCertifierCount = 64 - maximumCertificateTypeCount = 64 + maximumCertificateCount = 100 + maximumCertificateCertifierCount = 100 + maximumCertificateTypeCount = 100 maximumCertificateFieldCount = 256 maximumCertificateAggregateBytes = 8 << 20 certificateLimits = .standard @@ -301,21 +357,26 @@ public enum AuthError: Error, Equatable, Sendable, LocalizedError { peerMismatch, notAuthenticated, certificateExchangeUnavailable, invalidCertificateRequest, certificateValidationFailed, resourceLimit, handshakeTimedOut, randomGenerationFailed + /// A short sentence that does not assume which side the app is on. The + /// case, and any detail logged with it, identify the cause. public var errorDescription: String? { switch self { case .notAuthenticated: - "Not authenticated with the storage server." + "The connection has not been authenticated yet." case .sessionNotFound: - "The storage session is no longer valid." + "The authenticated session is no longer valid." case .resourceLimit: - "The storage session reached its message limit." + "The authenticated session reached one of its limits." case .handshakeTimedOut: - "Authentication with the storage server timed out." + "Authentication timed out." case .invalidSignature, .replay, .peerMismatch: - "The storage server could not be verified." - case .invalidMessage, .invalidNonce, .unexpectedMessage, .invalidCertificateRequest, - .certificateValidationFailed, .certificateExchangeUnavailable: - "The storage server sent an invalid authentication message." + "The other side could not be verified." + case .invalidMessage, .invalidNonce, .unexpectedMessage, .invalidCertificateRequest: + "An authentication message was not valid." + case .certificateValidationFailed: + "The certificates do not match what was requested or could not be verified." + case .certificateExchangeUnavailable: + "Certificates cannot be exchanged this way." case .randomGenerationFailed: "A secure random value could not be generated." } diff --git a/Sources/BSVAuth/BRC103/BRC103.swift b/Sources/BSVAuth/BRC103/BRC103.swift index 4a3c179..8f1ff43 100644 --- a/Sources/BSVAuth/BRC103/BRC103.swift +++ b/Sources/BSVAuth/BRC103/BRC103.swift @@ -7,63 +7,75 @@ import Foundation /// Strict JSON codec for the bounded BRC-103 envelope. public enum AuthMessageCodec { + /// Writes the envelope by hand. Certificate members are written from the + /// exact bytes their signatures cover, because a TypeScript verifier signs + /// `JSON.stringify` of the parsed members in wire order (`Peer.ts:1070`, + /// `Peer.ts:1205`). Foundation's `.sortedKeys` order is not byte order, so + /// it cannot be used for these members. public static func encode(_ message: AuthMessage, limits: AuthLimits = .standard) throws -> [UInt8] { try validate(message, limits: limits) - var object: [String: Any] = [ - "version": message.version, "messageType": message.messageType.rawValue, - "identityKey": Hex.encode(message.identityKey.compressedBytes), - ] - if let nonce = message.nonce { object["nonce"] = nonce } - if let initial = message.initialNonce { object["initialNonce"] = initial } - if let yours = message.yourNonce { object["yourNonce"] = yours } + var estimatedByteCount = 0 + if let payload = message.payload { + estimatedByteCount = try checkedJSONByteCount( + estimatedByteCount, #","payload":"#.utf8.count, byteArrayJSONByteCount(payload), + maximum: limits.maximumJSONBytes) + } + if let signature = message.signature { + estimatedByteCount = try checkedJSONByteCount( + estimatedByteCount, #","signature":"#.utf8.count, + byteArrayJSONByteCount(signature), maximum: limits.maximumJSONBytes) + } + var writer = AuthJSONWriter(maximumByteCount: limits.maximumJSONBytes) + try writer.append(#"{"version":"#) + try writer.appendString(message.version) + try writer.append(#","messageType":"#) + try writer.appendString(message.messageType.rawValue) + try writer.append(#","identityKey":"#) + try writer.appendString(Hex.encode(message.identityKey.compressedBytes)) + for (name, value) in [ + ("nonce", message.nonce), ("initialNonce", message.initialNonce), + ("yourNonce", message.yourNonce), + ] { + guard let value else { continue } + try writer.append(",") + try writer.appendString(name) + try writer.append(":") + try writer.appendString(value) + } if let certificates = message.certificates { - _ = try AuthCertificateJSON.response(certificates, limits: limits) - object["certificates"] = try certificateObjects(certificates, limits: limits) + try writer.append(#","certificates":"#) + try writer.append(AuthCertificateJSON.response(certificates, limits: limits)) } if let requested = message.requestedCertificates { - _ = try AuthCertificateJSON.request(requested, limits: limits) - object["requestedCertificates"] = try requestedCertificateObject( - requested, - limits: limits - ) + try writer.append(#","requestedCertificates":"#) + try writer.append(AuthCertificateJSON.request(requested, limits: limits)) } - let baseData = try JSONSerialization.data( - withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]) - var estimatedByteCount = baseData.count + _ = try checkedJSONByteCount( + writer.bytes.count, estimatedByteCount, 1, maximum: limits.maximumJSONBytes) if let payload = message.payload { - estimatedByteCount = try checkedJSONByteCount( - estimatedByteCount, - #","payload":"#.utf8.count, - byteArrayJSONByteCount(payload), - maximum: limits.maximumJSONBytes - ) + try writer.append(#","payload":"#) + try writer.append(byteArrayJSON(payload)) } if let signature = message.signature { - estimatedByteCount = try checkedJSONByteCount( - estimatedByteCount, - #","signature":"#.utf8.count, - byteArrayJSONByteCount(signature), - maximum: limits.maximumJSONBytes - ) - } - guard estimatedByteCount <= limits.maximumJSONBytes else { - throw AuthError.resourceLimit + try writer.append(#","signature":"#) + try writer.append(byteArrayJSON(signature)) } - if let payload = message.payload { object["payload"] = payload.map(Int.init) } - if let signature = message.signature { object["signature"] = signature.map(Int.init) } - let data = try JSONSerialization.data( - withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]) - guard data.count <= limits.maximumJSONBytes else { throw AuthError.resourceLimit } - return [UInt8](data) + try writer.append("}") + return writer.bytes } + /// Decodes a message and keeps the bytes its signature covers. Encoding + /// the result writes members in this SDK's order, which can differ from + /// the sender's, so a relay must forward the received bytes rather than + /// re-encode a decoded certificate message. public static func decode(_ bytes: [UInt8], limits: AuthLimits = .standard) throws -> AuthMessage { guard bytes.count <= limits.maximumJSONBytes else { throw AuthError.resourceLimit } - guard StrictAuthJSONPreflight.accepts(bytes), - let object = try JSONSerialization.jsonObject(with: Data(bytes)) as? [String: Any] + let retained = try AuthJSONParser.parseEnvelope( + bytes, retaining: ["certificates", "requestedCertificates"]) + guard let object = try JSONSerialization.jsonObject(with: Data(bytes)) as? [String: Any] else { throw AuthError.invalidMessage } let permitted: Set = [ "version", "messageType", "identityKey", "nonce", "initialNonce", "yourNonce", @@ -100,11 +112,24 @@ public enum AuthMessageCodec { } return bytes } - let certificates = try decodeCertificates(object["certificates"], limits: limits) + let certificates = try decodeCertificates(retained["certificates"], limits: limits) let requested = try decodeRequestedCertificates( - object["requestedCertificates"], + retained["requestedCertificates"], limits: limits ) + var signingBytes: [UInt8]? + switch type { + case .certificateRequest: + if let value = retained["requestedCertificates"], requested != nil { + signingBytes = try AuthCertificateJSON.receivedRequest(value, limits: limits) + } + case .certificateResponse: + if let value = retained["certificates"], certificates != nil { + signingBytes = try AuthCertificateJSON.receivedResponse(value, limits: limits) + } + default: + break + } let result = AuthMessage( version: version, messageType: type, identityKey: identity, nonce: try optionalString("nonce"), initialNonce: try optionalString("initialNonce"), @@ -112,7 +137,8 @@ public enum AuthMessageCodec { payload: try optionalBytes("payload", maximum: limits.maximumPayloadBytes), signature: try optionalBytes("signature", maximum: 72), certificates: certificates, - requestedCertificates: requested) + requestedCertificates: requested, + receivedSigningBytes: signingBytes) try validate(result, limits: limits) return result } @@ -128,11 +154,15 @@ public enum AuthMessageCodec { lowS(signature) else { throw AuthError.invalidSignature } } + let noCertificates = message.certificates?.isEmpty ?? true switch message.messageType { case .initialRequest: + // `@bsv/sdk` sends its handshake certificate policy here + // (`Peer.ts:635-641`). It is unsigned; it is surfaced to the caller + // as a request and never trusted. guard message.initialNonce.map(validSessionNonce) == true, message.signature == nil, message.nonce == nil, message.yourNonce == nil, message.payload == nil, - message.certificates == nil, message.requestedCertificates == nil + noCertificates else { throw AuthError.invalidMessage } case .initialResponse: // The responder's own nonce travels as `initialNonce`; `nonce` is not sent. The @@ -149,19 +179,26 @@ public enum AuthMessageCodec { guard message.nonce.map(validMessageNonce) == true, message.yourNonce.map(validSessionNonce) == true, message.payload != nil, message.signature != nil, message.initialNonce == nil, - message.certificates == nil, message.requestedCertificates == nil + noCertificates else { throw AuthError.invalidMessage } case .certificateRequest: + // `initialNonce` is the sender's own session nonce and is required + // (`AuthMessageValidation.ts:404`, sent at `Peer.ts:467`). guard message.nonce.map(validMessageNonce) == true, + message.initialNonce.map(validSessionNonce) == true, message.yourNonce.map(validSessionNonce) == true, - message.requestedCertificates != nil, message.certificates == nil, - message.initialNonce == nil, message.payload == nil, message.signature != nil + message.requestedCertificates != nil, noCertificates, + message.payload == nil, message.signature != nil else { throw AuthError.invalidMessage } case .certificateResponse: + // An empty list is a valid answer (`AuthMessageValidation.ts:417`, + // sent at `Peer.ts:1117`). `initialNonce` is required + // (`AuthMessageValidation.ts:415`, sent at `Peer.ts:1156`). guard message.nonce.map(validMessageNonce) == true, + message.initialNonce.map(validSessionNonce) == true, message.yourNonce.map(validSessionNonce) == true, - message.certificates?.isEmpty == false, message.requestedCertificates == nil, - message.initialNonce == nil, message.payload == nil, message.signature != nil + message.certificates != nil, message.requestedCertificates == nil, + message.payload == nil, message.signature != nil else { throw AuthError.invalidMessage } } } @@ -180,51 +217,38 @@ public enum AuthMessageCodec { try AuthCertificateJSON.response(certificates, limits: limits) } - static func requestedCertificateObject( - _ request: AuthRequestedCertificateSet, - limits: AuthLimits - ) throws -> [String: Any] { - _ = try AuthRequestedCertificateSet( - certifiers: request.certifiers, - certificateTypes: request.certificateTypes, - limits: limits - ) - var types: [String: [String]] = [:] - for (type, fields) in request.certificateTypes { - types[type.base64] = fields.map(\.value) - } - return [ - "certifiers": request.certifiers.map { Hex.encode($0.compressedBytes) }, - "types": types, - ] - } - static func decodeRequestedCertificates( - _ value: Any?, + _ value: AuthJSONValue?, limits: AuthLimits ) throws -> AuthRequestedCertificateSet? { guard let value else { return nil } - guard let object = value as? [String: Any], - Set(object.keys) == ["certifiers", "types"] + guard case .object(let members) = value, + Set(members.map(\.key)) == ["certifiers", "types"], + let rawCertifiers = value["certifiers"], let rawTypes = value["types"] else { throw AuthError.invalidCertificateRequest } - let rawCertifiers = object["certifiers"] - let rawTypes = object["types"] - if rawCertifiers is NSNull || (rawCertifiers as? [Any])?.isEmpty == true, - rawTypes is NSNull || (rawTypes as? [String: Any])?.isEmpty == true - { - return nil + func isEmptyOrNull(_ value: AuthJSONValue) -> Bool { + switch value { + case .null: return true + case .array(let items): return items.isEmpty + case .object(let items): return items.isEmpty + default: return false + } } - guard let certifierValues = rawCertifiers as? [Any], + // `null` certifiers with no types is the empty set Go writes into + // every message. `@bsv/sdk` writes `{"certifiers":[],"types":{}}`, + // which is kept: it is signed text in a certificateRequest. + if case .null = rawCertifiers, isEmptyOrNull(rawTypes) { return nil } + guard case .array(let certifierValues) = rawCertifiers, certifierValues.count <= limits.maximumCertificateCertifierCount, - let typeValues = rawTypes as? [String: Any], + case .object(let typeValues) = rawTypes, typeValues.count <= limits.maximumCertificateTypeCount else { throw AuthError.invalidCertificateRequest } var certifiers: [PublicKey] = [] certifiers.reserveCapacity(certifierValues.count) for value in certifierValues { - guard let text = value as? String, + guard case .string(let text) = value, let bytes = try? Hex.decode(text, maximumDecodedByteCount: 33), bytes.count == 33, Hex.encode(bytes) == text, let key = try? PublicKey(bytes) @@ -233,15 +257,15 @@ public enum AuthMessageCodec { } var types: [CertificateTypeID: [CertificateFieldName]] = [:] - for (typeText, rawFields) in typeValues { - guard let type = try? CertificateTypeID(base64: typeText), - let fieldValues = rawFields as? [Any], + for member in typeValues { + guard let type = try? CertificateTypeID(base64: member.key), + case .array(let fieldValues) = member.value, fieldValues.count <= limits.maximumCertificateFieldCount else { throw AuthError.invalidCertificateRequest } var fields: [CertificateFieldName] = [] fields.reserveCapacity(fieldValues.count) for rawField in fieldValues { - guard let text = rawField as? String, + guard case .string(let text) = rawField, let field = try? CertificateFieldName( text, limits: limits.certificateLimits @@ -259,88 +283,46 @@ public enum AuthMessageCodec { ) } - private static func certificateObjects( - _ certificates: [VerifiableCertificate], - limits: AuthLimits - ) throws -> [[String: Any]] { - guard !certificates.isEmpty, - certificates.count <= limits.maximumCertificateCount - else { throw AuthError.certificateValidationFailed } - var result: [[String: Any]] = [] - result.reserveCapacity(certificates.count) - var aggregate = 0 - for verifiable in certificates { - let certificate = verifiable.certificate - guard let signature = certificate.signature else { - throw AuthError.certificateValidationFailed - } - let binary = try verifiable.binary(limits: limits.certificateLimits) - let (next, overflow) = aggregate.addingReportingOverflow(binary.count) - guard !overflow, next <= limits.maximumCertificateAggregateBytes else { - throw AuthError.resourceLimit - } - aggregate = next - var fields: [String: String] = [:] - for (name, value) in certificate.fields { fields[name.value] = value.base64 } - var keyring: [String: String] = [:] - for (name, value) in verifiable.keyring.entries { keyring[name.value] = value.base64 } - result.append([ - "type": certificate.type.base64, - "serialNumber": certificate.serialNumber.base64, - "subject": Hex.encode(certificate.subject.compressedBytes), - "certifier": Hex.encode(certificate.certifier.compressedBytes), - "revocationOutpoint": certificate.revocationOutpoint.description, - "fields": fields, - "signature": Hex.encode(signature.derBytes), - "keyring": keyring, - ]) - } - return result - } - private static func decodeCertificates( - _ value: Any?, + _ value: AuthJSONValue?, limits: AuthLimits ) throws -> [VerifiableCertificate]? { guard let value else { return nil } - guard let values = value as? [Any], + guard case .array(let values) = value, values.count <= limits.maximumCertificateCount else { throw AuthError.certificateValidationFailed } - if values.isEmpty { return nil } var result: [VerifiableCertificate] = [] result.reserveCapacity(values.count) var aggregate = 0 for rawValue in values { - guard var object = rawValue as? [String: Any], - Set(object.keys) == [ - "type", "serialNumber", "subject", "certifier", "revocationOutpoint", - "fields", "signature", "keyring", - ], - let rawKeyring = object.removeValue(forKey: "keyring") as? [String: Any] + guard case .object(let members) = rawValue, + Set(members.map(\.key)) == Set(AuthCertificateJSON.certificateMemberOrder), + case .object(let rawKeyring)? = rawValue["keyring"] else { throw AuthError.certificateValidationFailed } - let certificateData = try JSONSerialization.data( - withJSONObject: object, - options: [.sortedKeys, .withoutEscapingSlashes] - ) let certificate: Certificate do { + var writer = AuthJSONWriter(maximumByteCount: limits.maximumJSONBytes) + try writer.appendValue(.object(members.filter { $0.key != "keyring" })) certificate = try Certificate( - json: certificateData, + json: writer.bytes, limits: limits.certificateLimits ) } catch { + AuthLog.reported( + "AuthMessageCodec.decode certificate", error, + as: AuthError.certificateValidationFailed) throw AuthError.certificateValidationFailed } guard certificate.signature != nil, rawKeyring.count <= limits.maximumCertificateFieldCount else { throw AuthError.certificateValidationFailed } var entries: [CertificateFieldName: CertificateCiphertext] = [:] - for (nameText, rawCiphertext) in rawKeyring { - guard let ciphertextText = rawCiphertext as? String, + for member in rawKeyring { + guard case .string(let ciphertextText) = member.value, let name = try? CertificateFieldName( - nameText, + member.key, limits: limits.certificateLimits ), let ciphertext = try? CertificateCiphertext( @@ -391,6 +373,21 @@ public enum AuthMessageCodec { return true } + private static func byteArrayJSON(_ bytes: [UInt8]) -> [UInt8] { + var output: [UInt8] = [] + output.reserveCapacity(byteArrayJSONByteCount(bytes)) + output.append(0x5b) + for index in bytes.indices { + if index > 0 { output.append(0x2c) } + let byte = bytes[index] + if byte >= 100 { output.append(0x30 + byte / 100) } + if byte >= 10 { output.append(0x30 + (byte / 10) % 10) } + output.append(0x30 + byte % 10) + } + output.append(0x5d) + return output + } + private static func byteArrayJSONByteCount(_ bytes: [UInt8]) -> Int { guard !bytes.isEmpty else { return 2 } return 2 + bytes.count - 1 @@ -423,26 +420,71 @@ public actor PeerAuthenticator { var deadline: ContinuousClock.Instant? var seen: Set = [] var messageCount = 0 - var pendingCertificateRequest: AuthRequestedCertificateSet? - var receivedCertificateRequest: AuthRequestedCertificateSet? + /// Requests this side sent with certificateRequest messages and has + /// not had answered, oldest first. + var pendingCertificateRequests: [AuthRequestedCertificateSet] = [] + /// The policy this side sent in initialRequest or initialResponse, + /// until a response settles it. Responses are matched with it only + /// after `pendingCertificateRequests`, as `Peer.ts:1236-1240` does, + /// and also settled by a response whose certificates fit it + /// (`Peer.ts:1247`). + var pendingHandshakeRequest: AuthRequestedCertificateSet? = nil + /// Requests the peer sent with certificateRequest messages and this + /// side has not answered, oldest first. + var receivedCertificateRequests: [AuthRequestedCertificateSet] = [] + /// The policy the peer sent in initialRequest or initialResponse, + /// until this side answers it. + var receivedHandshakeRequest: AuthRequestedCertificateSet? = nil } + /// The most certificate requests a session keeps open in each direction. + /// `@bsv/sdk` keeps any number (`Peer.ts:474-478`); a bound keeps one + /// peer from growing a session without limit. + static let maximumOpenCertificateRequests = 16 private let wallet: any AuthenticationWallet private let limits: AuthLimits private let randomSource: any SecureRandomSource + private let certificatesToRequest: AuthRequestedCertificateSet? private let clock = ContinuousClock() private var sessions: [AuthSessionID: Session] = [:] private var inFlightNonces: Set = [] + /// Creates an authenticator. + /// + /// `certificatesToRequest` is this side's certificate policy, as the + /// `Peer` constructor takes it (`Peer.ts:139-159`). It is sent in every + /// `initialResponse` this side writes (`Peer.ts:867-876`), so a TypeScript + /// `AuthFetch` client answers it with a certificateResponse + /// (`clients/AuthFetch.ts:496-511`), and in `initialRequest` when + /// `beginAuthentication` is given no other policy. A policy with + /// certifiers is then awaited like a request sent with + /// `makeCertificateRequest`. public init( wallet: any AuthenticationWallet, limits: AuthLimits = .standard, - randomSource: any SecureRandomSource = SystemSecureRandomSource() + randomSource: any SecureRandomSource = SystemSecureRandomSource(), + certificatesToRequest: AuthRequestedCertificateSet? = nil ) { self.wallet = wallet self.limits = limits self.randomSource = randomSource + self.certificatesToRequest = certificatesToRequest } - public func beginAuthentication(with expectedPeer: PublicKey? = nil) async throws -> ( + /// Starts a handshake. + /// + /// `requesting` puts a certificate policy into `initialRequest`, as + /// `@bsv/sdk` does with `certificatesToRequest` (`Peer.ts:627-650`). When + /// it is `nil`, the policy given to `init` is sent, if any. A + /// peer may answer it with certificates in `initialResponse`; those + /// surface as `.certificateResponse` once the handshake verifies. They + /// are not covered by the response signature, so validate them with + /// `AuthCertificateExchange.validate` before relying on them, as + /// `Peer.ts:960-982` does. + public func beginAuthentication( + with expectedPeer: PublicKey? = nil, + requesting request: AuthRequestedCertificateSet? = nil + ) async throws -> ( sessionID: AuthSessionID, actions: [AuthPeerAction] ) { + let request = request ?? certificatesToRequest + if let request { _ = try AuthMessageCodec.certificateRequestSigningBytes(request, limits: limits) } try Task.checkCancellation() purgeExpired() try requireSessionCapacity(for: expectedPeer) @@ -455,8 +497,15 @@ public actor PeerAuthenticator { sessions[id] = .init( id: id, state: .challengeSent, peer: expectedPeer, ownNonce: nonce, peerNonce: nil, deadline: clock.now + limits.handshakeTimeout) + sessions[id]?.pendingHandshakeRequest = Self.askingRequest(request) return ( - id, [.send(.init(messageType: .initialRequest, identityKey: own, initialNonce: nonce))] + id, + [ + .send( + .init( + messageType: .initialRequest, identityKey: own, initialNonce: nonce, + requestedCertificates: request)) + ] ) } public func receive(_ message: AuthMessage) async throws -> [AuthPeerAction] { @@ -475,7 +524,8 @@ public actor PeerAuthenticator { { try Task.checkCancellation() purgeExpired() - guard payload.count <= limits.maximumPayloadBytes, let session = sessions[sessionID], + guard payload.count <= limits.maximumPayloadBytes else { throw AuthError.resourceLimit } + guard let session = sessions[sessionID], session.state == .authenticated, let peer = session.peer, let peerNonce = session.peerNonce else { throw AuthError.notAuthenticated } @@ -504,6 +554,15 @@ public actor PeerAuthenticator { messageType: .general, identityKey: own, nonce: nonce, yourNonce: peerNonce, payload: payload, signature: signature)) } + /// Asks the peer for certificates with a signed certificateRequest. + /// + /// The request stays open until a response settles it. Up to + /// `maximumOpenCertificateRequests` may be open per session. The peer + /// sends nothing back when it refuses a request; a Swift peer refuses one + /// identical to a request it already holds open, or one over its byte + /// budget. When the transport reports that the peer refused the message, + /// call `withdrawCertificateRequest(_:using:)` so the request no longer + /// counts as open here. public func makeCertificateRequest( _ request: AuthRequestedCertificateSet, using sessionID: AuthSessionID @@ -513,14 +572,15 @@ public actor PeerAuthenticator { guard let session = sessions[sessionID], session.state == .authenticated, let peer = session.peer, let peerNonce = session.peerNonce else { throw AuthError.notAuthenticated } - guard session.pendingCertificateRequest == nil else { - throw AuthError.unexpectedMessage + guard session.pendingCertificateRequests.count < Self.maximumOpenCertificateRequests else { + throw AuthError.resourceLimit } guard session.messageCount < limits.maximumMessages else { sessions.removeValue(forKey: sessionID) throw AuthError.resourceLimit } let data = try AuthMessageCodec.certificateRequestSigningBytes(request, limits: limits) + let ownNonce = session.ownNonce let nonce = try reserveUniqueNonce() defer { inFlightNonces.remove(nonce) } let own = try await identity() @@ -528,22 +588,28 @@ public actor PeerAuthenticator { let signature = try await sign(data, keyID: nonce + " " + peerNonce, peer: peer) try Task.checkCancellation() guard var current = sessions[sessionID], current.state == .authenticated, - current.peer == peer, current.peerNonce == peerNonce, - current.pendingCertificateRequest == nil + current.peer == peer, current.peerNonce == peerNonce else { throw AuthError.sessionNotFound } + guard current.pendingCertificateRequests.count < Self.maximumOpenCertificateRequests else { + throw AuthError.resourceLimit + } guard current.messageCount < limits.maximumMessages else { sessions.removeValue(forKey: sessionID) throw AuthError.resourceLimit } current.messageCount += 1 current.seen.insert(nonce) - current.pendingCertificateRequest = request + // A request without certifiers asks for nothing, so no answer is + // awaited (`Peer.ts:1097-1100`). + // Several requests may be open at once (`Peer.ts:474-478`). + if !request.certifiers.isEmpty { current.pendingCertificateRequests.append(request) } sessions[sessionID] = current return .send( AuthMessage( messageType: .certificateRequest, identityKey: own, nonce: nonce, + initialNonce: ownNonce, yourNonce: peerNonce, signature: signature, requestedCertificates: request @@ -551,16 +617,53 @@ public actor PeerAuthenticator { ) } + /// Stops waiting for an answer to a request sent with + /// `makeCertificateRequest`, oldest first among identical ones. Returns + /// whether one was open. `@bsv/sdk` drops a request the same way when + /// sending it fails (`Peer.ts:480-485`). A later response that would have + /// answered it is then refused unless another open request fits it. + @discardableResult + public func withdrawCertificateRequest( + _ request: AuthRequestedCertificateSet, + using sessionID: AuthSessionID + ) -> Bool { + guard let index = sessions[sessionID]?.pendingCertificateRequests.firstIndex(of: request) + else { return false } + sessions[sessionID]?.pendingCertificateRequests.remove(at: index) + return true + } + + /// Answers one of the peer's open certificate requests. + /// + /// The certificates may be any subset of the requested types, each + /// revealing a nonempty subset of its requested fields, and may be empty, + /// as `@bsv/sdk` 4.1.1 allows (`Peer.ts:359-389`, `Peer.ts:1117`). A + /// request that arrived in `initialRequest` can be answered before the + /// peer has sent its first signed message. + /// + /// `answering` names the request answered. When it is `nil`, the oldest + /// certificateRequest the certificates fit is answered, and the + /// handshake policy only if none fits, the order in which the peer + /// matches the response (`Peer.ts:1236-1241`). When the answered request + /// is a certificateRequest and the certificates, which must be nonempty, + /// also fit the handshake policy, the policy is settled too, because the + /// peer counts them as answering it as well (`Peer.ts:1247`). + /// + /// `answering` settles a request on this side only. The response does + /// not carry it, so the peer settles the oldest of its own requests that + /// the certificates fit, which may be a different one. public func makeCertificateResponse( _ certificates: [VerifiableCertificate], - using sessionID: AuthSessionID + using sessionID: AuthSessionID, + answering answered: AuthRequestedCertificateSet? = nil ) async throws -> AuthPeerAction { try Task.checkCancellation() purgeExpired() - guard let session = sessions[sessionID], session.state == .authenticated, + guard let session = sessions[sessionID], Self.canExchangeCertificates(session), let peer = session.peer, let peerNonce = session.peerNonce, - let request = session.receivedCertificateRequest + !Self.answerableRequests(session).isEmpty else { throw AuthError.notAuthenticated } + let ownNonce = session.ownNonce guard session.messageCount < limits.maximumMessages else { sessions.removeValue(forKey: sessionID) throw AuthError.resourceLimit @@ -573,12 +676,24 @@ public actor PeerAuthenticator { defer { inFlightNonces.remove(nonce) } let own = try await identity() try Task.checkCancellation() - try requireCertificateMatch(certificates, request: request, peer: own) + let request: AuthRequestedCertificateSet + if let answered { + guard Self.answerableRequests(session).contains(answered) else { + throw AuthError.unexpectedMessage + } + try requireCertificateMatch( + certificates, request: answered, peer: own, operation: "makeCertificateResponse") + request = answered + } else { + request = try firstMatchingRequest( + certificates, in: Self.answerableRequests(session), peer: own, + operation: "makeCertificateResponse") + } let signature = try await sign(data, keyID: nonce + " " + peerNonce, peer: peer) try Task.checkCancellation() - guard var current = sessions[sessionID], current.state == .authenticated, + guard var current = sessions[sessionID], Self.canExchangeCertificates(current), current.peer == peer, current.peerNonce == peerNonce, - current.receivedCertificateRequest == request + Self.answerableRequests(current).contains(request) else { throw AuthError.sessionNotFound } guard current.messageCount < limits.maximumMessages else { sessions.removeValue(forKey: sessionID) @@ -586,13 +701,25 @@ public actor PeerAuthenticator { } current.messageCount += 1 current.seen.insert(nonce) - current.receivedCertificateRequest = nil + if let answeredIndex = current.receivedCertificateRequests.firstIndex(of: request) { + current.receivedCertificateRequests.remove(at: answeredIndex) + // The peer also counts certificates that fit its handshake policy + // as answering it (`Peer.ts:1247`). + if let handshake = current.receivedHandshakeRequest, + Self.fitsHandshakePolicy(certificates, handshake, peer: own, limits: limits) + { + current.receivedHandshakeRequest = nil + } + } else { + current.receivedHandshakeRequest = nil + } sessions[sessionID] = current return .send( AuthMessage( messageType: .certificateResponse, identityKey: own, nonce: nonce, + initialNonce: ownNonce, yourNonce: peerNonce, signature: signature, certificates: certificates @@ -614,12 +741,16 @@ public actor PeerAuthenticator { purgeExpired() try reserve(new: incoming, peer: message.identityKey) try requireSessionCapacity(for: message.identityKey) - let ownNonce = try makeUniqueNonce(excluding: [incoming]) + // `@bsv/sdk` 4.1.1 requires a 48-byte responder session nonce + // (`AuthMessageValidation.ts:394`). + let ownNonce = try makeUniqueSessionNonce(excluding: [incoming]) let id = AuthSessionID() sessions[id] = .init( id: id, state: .responseSentAwaitingPeerProof, peer: message.identityKey, ownNonce: ownNonce, - peerNonce: incoming, deadline: clock.now + limits.handshakeTimeout, seen: [incoming]) + peerNonce: incoming, deadline: clock.now + limits.handshakeTimeout, seen: [incoming], + pendingHandshakeRequest: Self.askingRequest(certificatesToRequest), + receivedHandshakeRequest: Self.askingRequest(message.requestedCertificates)) let signature: [UInt8] do { signature = try await sign( @@ -631,13 +762,22 @@ public actor PeerAuthenticator { sessions.removeValue(forKey: id) throw error } - return [ + var actions: [AuthPeerAction] = [ .send( .init( messageType: .initialResponse, identityKey: own, nonce: ownNonce, initialNonce: ownNonce, - yourNonce: incoming, signature: signature)) + yourNonce: incoming, signature: signature, + // This side's policy, as `Peer.ts:867-876` sends it. The + // signature covers only the nonces. + requestedCertificates: certificatesToRequest)) ] + if let request = Self.askingRequest(message.requestedCertificates) { + actions.append( + .certificateRequest( + .init(sessionID: id, peer: message.identityKey, request: request))) + } + return actions } private func receiveResponse(_ message: AuthMessage) async throws -> [AuthPeerAction] { try Task.checkCancellation() @@ -657,6 +797,17 @@ public actor PeerAuthenticator { keyID: ownNonce + " " + peerNonce, peer: message.identityKey) else { throw AuthError.invalidSignature } try Task.checkCancellation() + // As `Peer.ts:960-967`, certificates are looked at only when this side + // asked for some and the peer sent at least one; otherwise they are + // ignored and any pending request stays open. + var answered: AuthRequestedCertificateSet? + if let certificates = message.certificates, !certificates.isEmpty, + let pending = sessions[index]?.pendingHandshakeRequest + { + answered = try firstMatchingRequest( + certificates, in: [pending], peer: message.identityKey, + operation: "receive initialResponse") + } guard var session = sessions[index], session.state == .challengeSent, session.ownNonce == ownNonce, session.peer == nil || session.peer == message.identityKey @@ -666,8 +817,87 @@ public actor PeerAuthenticator { session.state = .authenticated session.deadline = nil session.seen.insert(peerNonce) + // A responder with a certificate policy puts it here and then holds + // general messages until it receives a matching certificateResponse + // (`Peer.ts:840-850`, `Peer.ts:1326-1328`). + let theirRequest = Self.askingRequest(message.requestedCertificates) + session.receivedHandshakeRequest = theirRequest + var actions: [AuthPeerAction] = [] + // A responder answers a handshake policy with certificates in + // initialResponse (`Peer.ts:836-849`, `Peer.ts:872`). They are not + // covered by the signature, which binds only the nonces; the initiator + // validates them as `Peer.ts:960-982` does. + if let certificates = message.certificates, let request = answered, + session.pendingHandshakeRequest == request + { + session.pendingHandshakeRequest = nil + actions.append( + .certificateResponse( + .init( + sessionID: index, peer: message.identityKey, requested: request, + certificates: certificates))) + } sessions[index] = session - return [] + if let request = theirRequest { + actions.append( + .certificateRequest( + .init(sessionID: index, peer: message.identityKey, request: request))) + } + return actions + } + + /// Requests this side is waiting on, in the order a response is matched + /// with them: certificateRequests oldest first, then the handshake policy. + private static func openRequests(_ session: Session) -> [AuthRequestedCertificateSet] { + session.pendingCertificateRequests + (session.pendingHandshakeRequest.map { [$0] } ?? []) + } + + /// Requests the peer is waiting on this side to answer, in matching + /// order: certificateRequests oldest first, then the handshake policy. + private static func answerableRequests(_ session: Session) -> [AuthRequestedCertificateSet] { + session.receivedCertificateRequests + (session.receivedHandshakeRequest.map { [$0] } ?? []) + } + + /// Refuses a received request that would be the seventeenth open one, is + /// identical to one already open, or would take the open requests of the + /// session past `maximumCertificateAggregateBytes` together. This bounds + /// what one authenticated peer can keep in memory to what one request + /// may hold. + private func admitReceivedRequest( + _ request: AuthRequestedCertificateSet, + into session: Session + ) throws { + let open = Self.answerableRequests(session) + guard session.receivedCertificateRequests.count < Self.maximumOpenCertificateRequests else { + AuthLog.rejected( + "receive certificateRequest", + "\(session.receivedCertificateRequests.count) requests are already open", + as: AuthError.resourceLimit) + throw AuthError.resourceLimit + } + guard !open.contains(request) else { + AuthLog.rejected( + "receive certificateRequest", "an identical request is already open", + as: AuthError.unexpectedMessage) + throw AuthError.unexpectedMessage + } + let total = (open + [request]).reduce(0) { $0 + $1.accountedBytes } + guard total <= limits.maximumCertificateAggregateBytes else { + AuthLog.rejected( + "receive certificateRequest", + "open requests would hold \(total) bytes, over \(limits.maximumCertificateAggregateBytes)", + as: AuthError.resourceLimit) + throw AuthError.resourceLimit + } + } + + /// A requested set that asks for something. `@bsv/sdk` treats a set with + /// no certifiers as no request (`Peer.ts:836-838`, `Peer.ts:1097-1100`). + private static func askingRequest( + _ request: AuthRequestedCertificateSet? + ) -> AuthRequestedCertificateSet? { + guard let request, !request.certifiers.isEmpty else { return nil } + return request } private func receiveGeneral(_ message: AuthMessage) async throws -> [AuthPeerAction] { try Task.checkCancellation() @@ -713,13 +943,16 @@ public actor PeerAuthenticator { try Task.checkCancellation() guard let target = message.yourNonce, let nonce = message.nonce, let request = message.requestedCertificates, let signature = message.signature, - let index = authenticatedSessionIndex(target: target, peer: message.identityKey), + let index = certificateSessionIndex(target: target, peer: message.identityKey), let session = sessions[index] else { throw AuthError.sessionNotFound } + guard message.initialNonce == session.peerNonce else { throw AuthError.invalidNonce } guard !session.seen.contains(nonce) else { throw AuthError.replay } guard inFlightNonces.insert(nonce).inserted else { throw AuthError.replay } defer { inFlightNonces.remove(nonce) } - let data = try AuthMessageCodec.certificateRequestSigningBytes(request, limits: limits) + let data = + try message.receivedSigningBytes + ?? AuthMessageCodec.certificateRequestSigningBytes(request, limits: limits) guard try await verify( signature, @@ -729,17 +962,29 @@ public actor PeerAuthenticator { ) else { throw AuthError.invalidSignature } try Task.checkCancellation() - guard var current = sessions[index], current.state == .authenticated, + guard var current = sessions[index], Self.canExchangeCertificates(current), current.ownNonce == target, current.peer == message.identityKey, !current.seen.contains(nonce) else { throw AuthError.replay } - guard current.receivedCertificateRequest == nil else { - throw AuthError.unexpectedMessage - } + // A request without certifiers asks for nothing: it is verified and + // authenticates the sender, and there is nothing to answer + // (`Peer.ts:1092-1100`). + // Several requests may be open at once (`Peer.ts:474-478`), within + // `admitReceivedRequest`'s bounds. + // The nonce is claimed and the sender authenticated before the request + // is admitted (`Peer.ts:1088-1092`), so a refused request counts + // against `maximumMessages` and cannot be replayed. try consumeMessage(on: index, session: ¤t) current.seen.insert(nonce) - current.receivedCertificateRequest = request + markAuthenticated(¤t) sessions[index] = current + let asking = Self.askingRequest(request) + if asking != nil { + try admitReceivedRequest(request, into: current) + current.receivedCertificateRequests.append(request) + sessions[index] = current + } + guard asking != nil else { return [] } return [ .certificateRequest( .init(sessionID: index, peer: message.identityKey, request: request) @@ -753,20 +998,16 @@ public actor PeerAuthenticator { try Task.checkCancellation() guard let target = message.yourNonce, let nonce = message.nonce, let certificates = message.certificates, let signature = message.signature, - let index = authenticatedSessionIndex(target: target, peer: message.identityKey), + let index = certificateSessionIndex(target: target, peer: message.identityKey), let session = sessions[index] else { throw AuthError.sessionNotFound } + guard message.initialNonce == session.peerNonce else { throw AuthError.invalidNonce } guard !session.seen.contains(nonce) else { throw AuthError.replay } - guard let request = session.pendingCertificateRequest else { - throw AuthError.unexpectedMessage - } - try requireCertificateMatch(certificates, request: request, peer: message.identityKey) guard inFlightNonces.insert(nonce).inserted else { throw AuthError.replay } defer { inFlightNonces.remove(nonce) } - let data = try AuthMessageCodec.certificateResponseSigningBytes( - certificates, - limits: limits - ) + let data = + try message.receivedSigningBytes + ?? AuthMessageCodec.certificateResponseSigningBytes(certificates, limits: limits) guard try await verify( signature, @@ -776,33 +1017,94 @@ public actor PeerAuthenticator { ) else { throw AuthError.invalidSignature } try Task.checkCancellation() - guard var current = sessions[index], current.state == .authenticated, + guard var current = sessions[index], Self.canExchangeCertificates(current), current.ownNonce == target, current.peer == message.identityKey, - !current.seen.contains(nonce), current.pendingCertificateRequest == request + !current.seen.contains(nonce) else { throw AuthError.replay } + // As in `Peer.ts:1202-1227`, the signature is verified, the nonce + // claimed and the sender authenticated before the response is matched. try consumeMessage(on: index, session: ¤t) current.seen.insert(nonce) - current.pendingCertificateRequest = nil + markAuthenticated(¤t) sessions[index] = current - return [ + guard !Self.openRequests(current).isEmpty else { + AuthLog.rejected( + "receive certificateResponse", "no request is open", + as: AuthError.unexpectedMessage) + throw AuthError.unexpectedMessage + } + // A response does not name the request it answers, so it settles the + // oldest certificateRequest it fits, or the handshake policy if none + // fits (`Peer.ts:1236-1241`). Certificates that also fit the handshake + // policy settle it as well (`Peer.ts:1247`). An empty response + // declines the oldest open request in the same order. + let request = try firstMatchingRequest( + certificates, in: Self.openRequests(current), peer: message.identityKey, + operation: "receive certificateResponse") + var settled = [request] + if let answeredIndex = current.pendingCertificateRequests.firstIndex(of: request) { + current.pendingCertificateRequests.remove(at: answeredIndex) + if let handshake = current.pendingHandshakeRequest, + Self.fitsHandshakePolicy( + certificates, handshake, peer: message.identityKey, limits: limits) + { + current.pendingHandshakeRequest = nil + settled.append(handshake) + } + } else { + current.pendingHandshakeRequest = nil + } + sessions[index] = current + return settled.map { .certificateResponse( .init( sessionID: index, peer: message.identityKey, - requested: request, + requested: $0, certificates: certificates ) ) - ] + } + } + + /// Whether certificates that answered a certificateRequest also answer the + /// handshake policy. `Peer.ts:1229-1247` looks only at nonempty responses. + private static func fitsHandshakePolicy( + _ certificates: [VerifiableCertificate], + _ handshake: AuthRequestedCertificateSet, + peer: PublicKey, + limits: AuthLimits + ) -> Bool { + !certificates.isEmpty + && certificateMismatch(certificates, request: handshake, peer: peer, limits: limits) + == nil } - private func authenticatedSessionIndex(target: String, peer: PublicKey) -> AuthSessionID? { + /// A session that can send or receive signed certificate messages. + /// + /// `@bsv/sdk` 4.1.1 authenticates a responder session on a verified + /// certificateRequest or certificateResponse as well as on a general + /// message (`Peer.ts:1092`, `Peer.ts:1227`, `Peer.ts:1317`). + private static func canExchangeCertificates(_ session: Session) -> Bool { + session.peerNonce != nil + && (session.state == .authenticated + || session.state == .responseSentAwaitingPeerProof) + } + + private func certificateSessionIndex(target: String, peer: PublicKey) -> AuthSessionID? { sessions.first { $0.value.ownNonce == target && $0.value.peer == peer - && $0.value.state == .authenticated + && Self.canExchangeCertificates($0.value) }?.key } + private func markAuthenticated(_ session: inout Session) { + if session.state == .responseSentAwaitingPeerProof { + session.state = .authenticated + session.deadline = nil + } + } + private func consumeMessage(on id: AuthSessionID, session: inout Session) throws { guard session.messageCount < limits.maximumMessages else { sessions.removeValue(forKey: id) @@ -811,28 +1113,77 @@ public actor PeerAuthenticator { session.messageCount += 1 } + /// The oldest of `requests` that `certificates` fit. + private func firstMatchingRequest( + _ certificates: [VerifiableCertificate], + in requests: [AuthRequestedCertificateSet], + peer: PublicKey, + operation: String + ) throws -> AuthRequestedCertificateSet { + if let request = requests.first(where: { + Self.certificateMismatch(certificates, request: $0, peer: peer, limits: limits) == nil + }) { + return request + } + let reason = + requests.first.flatMap { + Self.certificateMismatch(certificates, request: $0, peer: peer, limits: limits) + } ?? "no request is open" + AuthLog.rejected( + operation, "certificates fit none of \(requests.count) open requests; oldest: \(reason)", + as: AuthError.certificateValidationFailed) + throw AuthError.certificateValidationFailed + } + private func requireCertificateMatch( _ certificates: [VerifiableCertificate], request: AuthRequestedCertificateSet, - peer: PublicKey + peer: PublicKey, + operation: String ) throws { - guard !certificates.isEmpty, - certificates.count <= limits.maximumCertificateCount - else { throw AuthError.certificateValidationFailed } - var foundTypes = Set() - for verifiable in certificates { - let certificate = verifiable.certificate - guard certificate.subject == peer, - request.certifiers.contains(certificate.certifier), - let fields = request.certificateTypes[certificate.type], - Set(verifiable.keyring.entries.keys) == Set(fields) - else { throw AuthError.certificateValidationFailed } - foundTypes.insert(certificate.type) - } - guard foundTypes == Set(request.certificateTypes.keys) else { + if let reason = Self.certificateMismatch( + certificates, request: request, peer: peer, limits: limits) + { + AuthLog.rejected(operation, reason, as: AuthError.certificateValidationFailed) throw AuthError.certificateValidationFailed } } + + /// Why `certificates` do not fit `request`, or `nil` when they do. + /// + /// The request is an allowlist (`Peer.ts:359-389`): every certificate + /// must be a requested certifier and type and reveal a nonempty subset of + /// the requested fields. Completeness is caller policy, checked by + /// `AuthCertificateExchange.validate`. + private static func certificateMismatch( + _ certificates: [VerifiableCertificate], + request: AuthRequestedCertificateSet, + peer: PublicKey, + limits: AuthLimits + ) -> String? { + guard certificates.count <= limits.maximumCertificateCount else { + return "\(certificates.count) certificates exceed the limit" + } + for (position, verifiable) in certificates.enumerated() { + let certificate = verifiable.certificate + guard certificate.subject == peer else { + return "certificate \(position) names another subject" + } + guard request.certifiers.contains(certificate.certifier) else { + return "certificate \(position) has a certifier that was not requested" + } + guard let fields = request.certificateTypes[certificate.type] else { + return "certificate \(position) has a type that was not requested" + } + guard !verifiable.keyring.entries.isEmpty, + Set(verifiable.keyring.entries.keys).isSubset(of: Set(fields)) + else { + return "certificate \(position) reveals no field or a field that was not requested" + } + } + return nil + } + private func reserve(new nonce: String, peer: PublicKey) throws { if nonceIsInUse(nonce) { throw AuthError.replay @@ -887,13 +1238,15 @@ public actor PeerAuthenticator { guard bytes.count == 48 else { throw AuthError.randomGenerationFailed } return Base64Encoding.encode(bytes) } catch { + AuthLog.reported( + "PeerAuthenticator session nonce", error, as: AuthError.randomGenerationFailed) throw AuthError.randomGenerationFailed } } - private func makeUniqueSessionNonce() throws -> String { + private func makeUniqueSessionNonce(excluding: Set = []) throws -> String { for _ in 0..<4 { let nonce = try makeSessionNonce() - if !nonceIsInUse(nonce) { return nonce } + if !excluding.contains(nonce), !nonceIsInUse(nonce) { return nonce } } throw AuthError.randomGenerationFailed } @@ -902,7 +1255,11 @@ public actor PeerAuthenticator { let bytes = try randomSource.randomBytes(count: 32) guard bytes.count == 32 else { throw AuthError.randomGenerationFailed } return Base64Encoding.encode(bytes) - } catch { throw AuthError.randomGenerationFailed } + } catch { + AuthLog.reported( + "PeerAuthenticator message nonce", error, as: AuthError.randomGenerationFailed) + throw AuthError.randomGenerationFailed + } } private func nonceBytes(_ text: String) throws -> [UInt8] { guard let data = try? Base64Encoding.decode(text, maximumDecodedByteCount: 48), diff --git a/Sources/BSVAuth/BRC103/StrictAuthJSONPreflight.swift b/Sources/BSVAuth/BRC103/StrictAuthJSONPreflight.swift deleted file mode 100644 index 307536c..0000000 --- a/Sources/BSVAuth/BRC103/StrictAuthJSONPreflight.swift +++ /dev/null @@ -1,191 +0,0 @@ -struct StrictAuthJSONPreflight { - private static let maximumNestingDepth = 64 - private let bytes: [UInt8] - private var offset = 0 - - static func accepts(_ bytes: [UInt8]) -> Bool { - var parser = Self(bytes: bytes) - do { - try parser.skipWhitespace() - try parser.parseValue(depth: 0) - try parser.skipWhitespace() - return parser.offset == bytes.count - } catch { - return false - } - } - - private mutating func parseValue(depth: Int) throws { - guard depth <= Self.maximumNestingDepth else { throw AuthError.invalidMessage } - guard offset < bytes.count else { throw AuthError.invalidMessage } - switch bytes[offset] { - case 0x7b: - try parseObject(depth: depth + 1) - case 0x5b: - try parseArray(depth: depth + 1) - case 0x22: - try parseString(allowEscapes: true) - case 0x74: - try consumeLiteral("true") - case 0x66: - try consumeLiteral("false") - case 0x6e: - try consumeLiteral("null") - case 0x2d, 0x30...0x39: - try parseNumber() - default: - throw AuthError.invalidMessage - } - } - - private mutating func parseObject(depth: Int) throws { - try consume(0x7b) - try skipWhitespace() - if consumeIfPresent(0x7d) { return } - - var names = Set() - while true { - let name = try parseObjectKey() - guard names.insert(name).inserted else { throw AuthError.invalidMessage } - try skipWhitespace() - try consume(0x3a) - try skipWhitespace() - try parseValue(depth: depth) - try skipWhitespace() - if consumeIfPresent(0x7d) { return } - try consume(0x2c) - try skipWhitespace() - } - } - - private mutating func parseArray(depth: Int) throws { - try consume(0x5b) - try skipWhitespace() - if consumeIfPresent(0x5d) { return } - while true { - try parseValue(depth: depth) - try skipWhitespace() - if consumeIfPresent(0x5d) { return } - try consume(0x2c) - try skipWhitespace() - } - } - - private mutating func parseObjectKey() throws -> String { - try consume(0x22) - let start = offset - while offset < bytes.count, bytes[offset] != 0x22 { - let byte = bytes[offset] - guard byte >= 0x20, byte <= 0x7e, byte != 0x5c else { - throw AuthError.invalidMessage - } - offset += 1 - } - guard offset < bytes.count else { throw AuthError.invalidMessage } - let name = String(decoding: bytes[start..= expected.count, - bytes[offset..<(offset + expected.count)].elementsEqual(expected) - else { - throw AuthError.invalidMessage - } - offset += expected.count - } - - private mutating func skipWhitespace() throws { - while offset < bytes.count { - switch bytes[offset] { - case 0x20, 0x09, 0x0a, 0x0d: - offset += 1 - default: - return - } - } - } - - private mutating func consume(_ expected: UInt8) throws { - guard consumeIfPresent(expected) else { throw AuthError.invalidMessage } - } - - private mutating func consumeIfPresent(_ expected: UInt8) -> Bool { - guard offset < bytes.count, bytes[offset] == expected else { return false } - offset += 1 - return true - } - - private func isDigit(_ byte: UInt8) -> Bool { - (0x30...0x39).contains(byte) - } - - private func isHexDigit(_ byte: UInt8) -> Bool { - (0x30...0x39).contains(byte) - || (0x41...0x46).contains(byte) - || (0x61...0x66).contains(byte) - } -} diff --git a/Sources/BSVAuth/BRC104/BRC104Error+LocalizedError.swift b/Sources/BSVAuth/BRC104/BRC104Error+LocalizedError.swift new file mode 100644 index 0000000..d690525 --- /dev/null +++ b/Sources/BSVAuth/BRC104/BRC104Error+LocalizedError.swift @@ -0,0 +1,53 @@ +import Foundation + +/// Plain sentences an app can show when an authenticated HTTP request or +/// response cannot be built or read. They hold whether the app is the client +/// or the server. +/// +/// The cases stay typed for callers that branch on them, and +/// `String(reflecting:)` still gives the case for a log. When a framing error +/// stands for a more detailed one, the detail is written to `AuthLog`. +extension BRC104Error: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidRequestID: + "The response does not belong to this request." + case .invalidMethod: + "The request method is not one that authenticated HTTP allows." + case .invalidPath: + "The request address is not valid or is too long." + case .invalidStatus: + "The response status is not one that authenticated HTTP allows." + case .invalidHeader, .duplicateHeader: + "The request or response has a header that is not valid." + case .headerNotPermitted: + "The request or response has a header that cannot be signed." + case .resourceLimit: + "The request or response is too large." + case .malformedPayload, .trailingData: + "The signed request or response could not be read." + } + } +} + +/// Plain sentences for an authenticated HTTP message whose headers or framing +/// are not valid. +extension BRC104HTTPFramingError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidFrame: + "The request or response is not one that authenticated HTTP allows." + case .invalidAuthenticationHeader, .duplicateAuthenticationHeader, + .unknownAuthenticationHeader: + "The authentication headers are not valid." + case .missingAuthenticationHeader: + "The request or response is missing authentication headers." + case .certificateExchangeUnavailable: + "Certificates cannot be sent with an HTTP request or response." + case .requestIDMismatch: + "The response does not belong to this request." + case .resourceLimit: + "The request or response is too large." + } + } +} diff --git a/Sources/BSVAuth/BRC104/BRC104HTTPFraming.swift b/Sources/BSVAuth/BRC104/BRC104HTTPFraming.swift index 78bd5c4..dedc151 100644 --- a/Sources/BSVAuth/BRC104/BRC104HTTPFraming.swift +++ b/Sources/BSVAuth/BRC104/BRC104HTTPFraming.swift @@ -16,6 +16,9 @@ public enum BRC104HTTPHeaderName { } /// Limits for transport-neutral BRC-104 HTTP frames. +/// +/// A frame holds every HTTP header the transport passes, signed or not, so the +/// defaults leave room above the signed-header limits in `BRC104Limits`. public struct BRC104HTTPFramingLimits: Equatable, Sendable { public static let maximumAllowedHeaderCount = 1_024 public static let maximumAllowedHeaderNameByteCount = 1_024 @@ -38,10 +41,10 @@ public struct BRC104HTTPFramingLimits: Equatable, Sendable { public init( authLimits: AuthLimits = .standard, payloadLimits: BRC104Limits = .standard, - maximumHeaderCount: Int = 128, - maximumHeaderNameByteCount: Int = 256, - maximumHeaderValueByteCount: Int = 64 << 10, - maximumAggregateHeaderByteCount: Int = 256 << 10, + maximumHeaderCount: Int = 1_024, + maximumHeaderNameByteCount: Int = 1_024, + maximumHeaderValueByteCount: Int = 256 << 10, + maximumAggregateHeaderByteCount: Int = 1 << 20, maximumMethodByteCount: Int = 32, maximumPathByteCount: Int = 8 << 10, maximumQueryByteCount: Int = 64 << 10 @@ -77,10 +80,10 @@ public struct BRC104HTTPFramingLimits: Equatable, Sendable { private init(standard: Void) { authLimits = .standard payloadLimits = .standard - maximumHeaderCount = 128 - maximumHeaderNameByteCount = 256 - maximumHeaderValueByteCount = 64 << 10 - maximumAggregateHeaderByteCount = 256 << 10 + maximumHeaderCount = 1_024 + maximumHeaderNameByteCount = 1_024 + maximumHeaderValueByteCount = 256 << 10 + maximumAggregateHeaderByteCount = 1 << 20 maximumMethodByteCount = 32 maximumPathByteCount = 8 << 10 maximumQueryByteCount = 64 << 10 @@ -142,7 +145,7 @@ public struct BRC104HTTPResponseFrame: Equatable, Sendable, CustomStringConverti body: [UInt8]? = nil, limits: BRC104HTTPFramingLimits = .standard ) throws { - guard (100...599).contains(status) else { + guard (200...599).contains(status) else { throw BRC104HTTPFramingError.invalidFrame } try BRC104HTTPFrameCodec.validateFrame(headers: headers, body: body, limits: limits) @@ -183,14 +186,13 @@ public enum BRC104HTTPFrameCodec { let request: BRC104Request do { request = try BRC104Codec.decodeRequest(payload, limits: limits.payloadLimits) - } catch BRC104Error.resourceLimit { - throw BRC104HTTPFramingError.resourceLimit } catch { - throw BRC104HTTPFramingError.invalidFrame + throw framingError(for: error, in: "BRC104HTTPFrameCodec.encodeRequest") } let authentication = try authenticationHeaders( for: message, - requestID: request.requestID + requestID: request.requestID, + limits: limits ) return try BRC104HTTPRequestFrame( method: request.method, @@ -214,7 +216,7 @@ public enum BRC104HTTPFrameCodec { ) try validateFrame(headers: frame.headers, body: frame.body, limits: limits) let split = try split(frame.headers, kind: .request, limits: limits) - let authentication = try parseAuthentication(split.authentication) + let authentication = try parseAuthentication(split.authentication, limits: limits) let request: BRC104Request do { request = try BRC104Request( @@ -226,18 +228,15 @@ public enum BRC104HTTPFrameCodec { body: frame.body, limits: limits.payloadLimits ) - } catch BRC104Error.resourceLimit { - throw BRC104HTTPFramingError.resourceLimit } catch { - throw BRC104HTTPFramingError.invalidFrame + throw framingError(for: error, in: "BRC104HTTPFrameCodec.decodeRequest") } let payload: [UInt8] do { - payload = try BRC104Codec.encode(request, limits: limits.payloadLimits) - } catch BRC104Error.resourceLimit { - throw BRC104HTTPFramingError.resourceLimit + payload = try BRC104Codec.encode( + request, applyingClientBodyDefault: false, limits: limits.payloadLimits) } catch { - throw BRC104HTTPFramingError.invalidFrame + throw framingError(for: error, in: "BRC104HTTPFrameCodec.decodeRequest") } return try makeMessage(authentication: authentication, payload: payload, limits: limits) } @@ -253,14 +252,13 @@ public enum BRC104HTTPFrameCodec { let response: BRC104Response do { response = try BRC104Codec.decodeResponse(payload, limits: limits.payloadLimits) - } catch BRC104Error.resourceLimit { - throw BRC104HTTPFramingError.resourceLimit } catch { - throw BRC104HTTPFramingError.invalidFrame + throw framingError(for: error, in: "BRC104HTTPFrameCodec.encodeResponse") } let authentication = try authenticationHeaders( for: message, - requestID: response.requestID + requestID: response.requestID, + limits: limits ) return try BRC104HTTPResponseFrame( status: response.status, @@ -280,9 +278,7 @@ public enum BRC104HTTPFrameCodec { } try validateFrame(headers: frame.headers, body: frame.body, limits: limits) let split = try split(frame.headers, kind: .response, limits: limits) - let authentication = try parseAuthentication( - split.authentication, messageTypeRequired: false - ) + let authentication = try parseAuthentication(split.authentication, limits: limits) guard authentication.requestID == expectedRequestID else { throw BRC104HTTPFramingError.requestIDMismatch } @@ -295,18 +291,14 @@ public enum BRC104HTTPFrameCodec { body: frame.body, limits: limits.payloadLimits ) - } catch BRC104Error.resourceLimit { - throw BRC104HTTPFramingError.resourceLimit } catch { - throw BRC104HTTPFramingError.invalidFrame + throw framingError(for: error, in: "BRC104HTTPFrameCodec.decodeResponse") } let payload: [UInt8] do { payload = try BRC104Codec.encode(response, limits: limits.payloadLimits) - } catch BRC104Error.resourceLimit { - throw BRC104HTTPFramingError.resourceLimit } catch { - throw BRC104HTTPFramingError.invalidFrame + throw framingError(for: error, in: "BRC104HTTPFrameCodec.decodeResponse") } return try makeMessage(authentication: authentication, payload: payload, limits: limits) } @@ -323,7 +315,7 @@ public enum BRC104HTTPFrameCodec { else { throw BRC104HTTPFramingError.resourceLimit } - guard BRC104Codec.validToken(method), !path.isEmpty, path.utf8.first == 47, + guard BRC104Codec.validMethod(method), !path.isEmpty, path.utf8.first == 47, BRC104Codec.safeText(path), !path.contains("?"), !path.contains("#") else { throw BRC104HTTPFramingError.invalidFrame @@ -333,6 +325,9 @@ public enum BRC104HTTPFrameCodec { throw BRC104HTTPFramingError.invalidFrame } } + guard BRC104Codec.validTargetLength(path: path, query: query) else { + throw BRC104HTTPFramingError.resourceLimit + } } static func validateFrame( @@ -375,6 +370,7 @@ public enum BRC104HTTPFrameCodec { let yourNonce: String let signature: [UInt8] let requestID: [UInt8] + let requestedCertificates: AuthRequestedCertificateSet? } private struct SplitHeaders { @@ -392,9 +388,6 @@ public enum BRC104HTTPFrameCodec { signed.reserveCapacity(min(headers.count, limits.payloadLimits.maximumHeaders)) for header in headers { let name = header.name.lowercased() - if name == BRC104HTTPHeaderName.requestedCertificates { - throw BRC104HTTPFramingError.certificateExchangeUnavailable - } if knownAuthenticationHeader(name) { guard authentication[name] == nil else { throw BRC104HTTPFramingError.duplicateAuthenticationHeader @@ -412,10 +405,8 @@ public enum BRC104HTTPFrameCodec { kind: kind, limits: limits.payloadLimits ) - } catch BRC104Error.resourceLimit { - throw BRC104HTTPFramingError.resourceLimit } catch { - throw BRC104HTTPFramingError.invalidFrame + throw framingError(for: error, in: "BRC104HTTPFrameCodec.split") } return SplitHeaders(authentication: authentication, signed: signed) } @@ -428,7 +419,8 @@ public enum BRC104HTTPFrameCodec { BRC104HTTPHeaderName.nonce, BRC104HTTPHeaderName.yourNonce, BRC104HTTPHeaderName.signature, - BRC104HTTPHeaderName.requestID: + BRC104HTTPHeaderName.requestID, + BRC104HTTPHeaderName.requestedCertificates: return true default: return false @@ -444,21 +436,17 @@ public enum BRC104HTTPFrameCodec { /// Reads the `x-bsv-auth-*` headers. /// - /// `messageType` is optional on a response because the reference middleware omits it there: - /// it writes that header only when the message is *not* general, and every ordinary answer is - /// general. Requiring it rejects every real response. When a sender does include it, it must - /// still say `general`. + /// `messageType` is optional on both sides. The reference middleware writes it on a response + /// only when the message is *not* general, and `SimplifiedFetchTransport` never writes it on a + /// request (`transports/SimplifiedFetchTransport.ts:189-194`); the middleware reads the other + /// six headers and assumes `general`. When a sender does include it, it must say `general`. private static func parseAuthentication( _ headers: [String: String], - messageTypeRequired: Bool = true - ) throws - -> ParsedAuthentication - { + limits: BRC104HTTPFramingLimits + ) throws -> ParsedAuthentication { let version = try required(BRC104HTTPHeaderName.version, in: headers) let messageType = - messageTypeRequired - ? try required(BRC104HTTPHeaderName.messageType, in: headers) - : headers[BRC104HTTPHeaderName.messageType] ?? AuthMessageType.general.rawValue + headers[BRC104HTTPHeaderName.messageType] ?? AuthMessageType.general.rawValue let keyText = try required(BRC104HTTPHeaderName.identityKey, in: headers) let nonce = try required(BRC104HTTPHeaderName.nonce, in: headers) let yourNonce = try required(BRC104HTTPHeaderName.yourNonce, in: headers) @@ -487,20 +475,73 @@ public enum BRC104HTTPFrameCodec { nonce: nonce, yourNonce: yourNonce, signature: signature, - requestID: requestID + requestID: requestID, + requestedCertificates: try parseRequestedCertificates( + headers[BRC104HTTPHeaderName.requestedCertificates], + limits: limits + ) ) } + /// The `@bsv/sdk` 4.1.1 limit for `x-bsv-auth-requested-certificates` + /// (`transports/SimplifiedFetchTransport.ts:30`). + static let maximumRequestedCertificatesHeaderBytes = 256 << 10 + + /// Reads `x-bsv-auth-requested-certificates`, the JSON text of a requested + /// certificate set (`transports/SimplifiedFetchTransport.ts:234-258`, + /// `auth-express-middleware/src/index.ts:985-988`). The header is not + /// covered by the message signature. + private static func parseRequestedCertificates( + _ value: String?, + limits: BRC104HTTPFramingLimits + ) throws -> AuthRequestedCertificateSet? { + guard let value else { return nil } + guard value.utf8.count <= maximumRequestedCertificatesHeaderBytes else { + throw BRC104HTTPFramingError.resourceLimit + } + do { + return try AuthMessageCodec.decodeRequestedCertificates( + try AuthJSONParser.parse(Array(value.utf8)), + limits: limits.authLimits + ) + } catch { + throw authenticationError( + for: error, in: "BRC104HTTPFrameCodec.parseRequestedCertificates") + } + } + + /// Reports a payload failure as a framing error and logs the detail. + private static func framingError(for error: any Error, in operation: String) + -> BRC104HTTPFramingError + { + let reported: BRC104HTTPFramingError = + error as? BRC104Error == .resourceLimit ? .resourceLimit : .invalidFrame + AuthLog.reported(operation, error, as: reported) + return reported + } + + /// Reports an authentication-message failure as a header error and logs + /// the detail. + private static func authenticationError(for error: any Error, in operation: String) + -> BRC104HTTPFramingError + { + let reported: BRC104HTTPFramingError = + error as? AuthError == .resourceLimit ? .resourceLimit : .invalidAuthenticationHeader + AuthLog.reported(operation, error, as: reported) + return reported + } + private static func authenticationHeaders( for message: AuthMessage, - requestID: [UInt8] + requestID: [UInt8], + limits: BRC104HTTPFramingLimits ) throws -> [BRC104Header] { guard requestID.count == 32, let nonce = message.nonce, let yourNonce = message.yourNonce, let signature = message.signature else { throw BRC104HTTPFramingError.invalidFrame } - return [ + var headers: [BRC104Header] = [ .init(name: BRC104HTTPHeaderName.version, value: message.version), .init(name: BRC104HTTPHeaderName.messageType, value: message.messageType.rawValue), .init( @@ -512,6 +553,14 @@ public enum BRC104HTTPFrameCodec { .init(name: BRC104HTTPHeaderName.signature, value: Hex.encode(signature)), .init(name: BRC104HTTPHeaderName.requestID, value: Base64Encoding.encode(requestID)), ] + if let request = message.requestedCertificates { + let json = try AuthCertificateJSON.request(request, limits: limits.authLimits) + headers.append( + .init( + name: BRC104HTTPHeaderName.requestedCertificates, + value: String(decoding: json, as: UTF8.self))) + } + return headers } private static func makeMessage( @@ -526,16 +575,13 @@ public enum BRC104HTTPFrameCodec { nonce: authentication.nonce, yourNonce: authentication.yourNonce, payload: payload, - signature: authentication.signature + signature: authentication.signature, + requestedCertificates: authentication.requestedCertificates ) do { try AuthMessageCodec.validate(message, limits: limits.authLimits) - } catch AuthError.resourceLimit { - throw BRC104HTTPFramingError.resourceLimit - } catch AuthError.certificateExchangeUnavailable { - throw BRC104HTTPFramingError.certificateExchangeUnavailable } catch { - throw BRC104HTTPFramingError.invalidAuthenticationHeader + throw authenticationError(for: error, in: "BRC104HTTPFrameCodec.makeMessage") } return message } @@ -544,17 +590,13 @@ public enum BRC104HTTPFrameCodec { _ message: AuthMessage, limits: BRC104HTTPFramingLimits ) throws { - guard message.certificates == nil, message.requestedCertificates == nil else { + guard message.certificates?.isEmpty ?? true else { throw BRC104HTTPFramingError.certificateExchangeUnavailable } do { try AuthMessageCodec.validate(message, limits: limits.authLimits) - } catch AuthError.resourceLimit { - throw BRC104HTTPFramingError.resourceLimit - } catch AuthError.certificateExchangeUnavailable { - throw BRC104HTTPFramingError.certificateExchangeUnavailable } catch { - throw BRC104HTTPFramingError.invalidAuthenticationHeader + throw authenticationError(for: error, in: "BRC104HTTPFrameCodec.validateGeneral") } } } diff --git a/Sources/BSVAuth/BRC104/BRC104Payload.swift b/Sources/BSVAuth/BRC104/BRC104Payload.swift index 8515ccd..7a7a90c 100644 --- a/Sources/BSVAuth/BRC104/BRC104Payload.swift +++ b/Sources/BSVAuth/BRC104/BRC104Payload.swift @@ -17,7 +17,7 @@ public struct BRC104Request: Equatable, Sendable, CustomStringConvertible, limits: BRC104Limits = .standard ) throws { guard requestID.count == 32 else { throw BRC104Error.invalidRequestID } - guard BRC104Codec.validToken(method) else { throw BRC104Error.invalidMethod } + guard BRC104Codec.validMethod(method) else { throw BRC104Error.invalidMethod } guard !path.isEmpty, path.utf8.first == 47, BRC104Codec.safeText(path), !path.contains("?"), !path.contains("#") else { throw BRC104Error.invalidPath } @@ -26,6 +26,9 @@ public struct BRC104Request: Equatable, Sendable, CustomStringConvertible, throw BRC104Error.invalidPath } } + guard BRC104Codec.validTargetLength(path: path, query: query) else { + throw BRC104Error.invalidPath + } self.requestID = requestID self.method = method self.path = path @@ -57,7 +60,9 @@ public struct BRC104Response: Equatable, Sendable, CustomStringConvertible, limits: BRC104Limits = .standard ) throws { guard requestID.count == 32 else { throw BRC104Error.invalidRequestID } - guard (100...599).contains(status) else { throw BRC104Error.invalidStatus } + // `AuthFetch` rejects an authenticated status outside 200...599 + // (`clients/AuthFetch.ts:587-589`). + guard (200...599).contains(status) else { throw BRC104Error.invalidStatus } self.requestID = requestID self.status = status self.headers = try BRC104Codec.normalized(headers, kind: .response, limits: limits) @@ -86,43 +91,61 @@ public struct BRC104Header: Equatable, Sendable, CustomStringConvertible, } } -/// Bounds on a BRC-104 request or response payload. +/// Limits for BRC-104 payloads. /// -/// `maximumPayloadBytes` defaults to 16 MiB, matching `AuthLimits` and the TypeScript SDK's -/// `AuthFetch` (`MAX_AUTH_HTTP_REQUEST_FRAME_BYTES`, and `DEFAULT_SIMPLIFIED_FETCH_MAX_RESPONSE_BYTES` -/// for a response body). +/// The defaults are the `@bsv/sdk` 4.1.1 limits: 512 signed headers, 1024-byte +/// names, 32 KiB values, 256 KiB of signed headers in total +/// (`transports/SimplifiedFetchTransport.ts:25-28`), a 256 KiB `x-bsv-payment` +/// request header (`:655-661`), and a 16 MiB body plus 512 KiB of framing +/// (`clients/AuthFetch.ts:147`, `:571`). public struct BRC104Limits: Equatable, Sendable { public let maximumPayloadBytes: Int public let maximumHeaders: Int public let maximumHeaderNameBytes: Int public let maximumHeaderValueBytes: Int + /// The value limit for the `x-bsv-payment` request header, which carries a + /// BRC-105 Atomic BEEF. + public let maximumPaymentHeaderValueBytes: Int public let maximumHeaderBytes: Int public init( - maximumPayloadBytes: Int = 16 << 20, maximumHeaders: Int = 64, - maximumHeaderNameBytes: Int = 256, - maximumHeaderValueBytes: Int = 8 << 10, maximumHeaderBytes: Int = 64 << 10 + maximumPayloadBytes: Int = AuthLimits.defaultPayloadBytes, maximumHeaders: Int = 512, + maximumHeaderNameBytes: Int = 1 << 10, + maximumHeaderValueBytes: Int = 32 << 10, maximumHeaderBytes: Int = 256 << 10, + maximumPaymentHeaderValueBytes: Int = 256 << 10 ) throws { guard maximumPayloadBytes >= 0, maximumHeaders >= 0, maximumHeaderNameBytes >= 0, - maximumHeaderValueBytes >= 0, maximumHeaderBytes >= 0 + maximumHeaderValueBytes >= 0, maximumHeaderBytes >= 0, + maximumPaymentHeaderValueBytes >= 0 else { throw BRC104Error.resourceLimit } self.maximumPayloadBytes = maximumPayloadBytes self.maximumHeaders = maximumHeaders self.maximumHeaderNameBytes = maximumHeaderNameBytes self.maximumHeaderValueBytes = maximumHeaderValueBytes + self.maximumPaymentHeaderValueBytes = maximumPaymentHeaderValueBytes self.maximumHeaderBytes = maximumHeaderBytes } private init( - validatedPayload: Int, headers: Int, headerName: Int, headerValue: Int, headerBytes: Int + validatedPayload: Int, headers: Int, headerName: Int, headerValue: Int, + paymentHeaderValue: Int, headerBytes: Int ) { maximumPayloadBytes = validatedPayload maximumHeaders = headers maximumHeaderNameBytes = headerName maximumHeaderValueBytes = headerValue + maximumPaymentHeaderValueBytes = paymentHeaderValue maximumHeaderBytes = headerBytes } public static let standard = BRC104Limits( - validatedPayload: 16 << 20, headers: 64, headerName: 256, headerValue: 8 << 10, - headerBytes: 64 << 10) + validatedPayload: AuthLimits.defaultPayloadBytes, headers: 512, headerName: 1 << 10, + headerValue: 32 << 10, paymentHeaderValue: 256 << 10, headerBytes: 256 << 10) + + static let paymentHeaderName = "x-bsv-payment" + + func maximumValueBytes(forHeader name: String, kind: BRC104Codec.HeaderKind) -> Int { + kind == .request && name == Self.paymentHeaderName + ? max(maximumHeaderValueBytes, maximumPaymentHeaderValueBytes) + : maximumHeaderValueBytes + } } public enum BRC104Error: Error, Equatable, Sendable { @@ -137,17 +160,35 @@ public enum BRC104Codec { throw BRC104Error.invalidRequestID } } + /// Encodes a request a client is about to sign. + /// + /// Like `AuthFetch` (`clients/AuthFetch.ts:755-760`), a POST, PUT, PATCH + /// or DELETE with a JSON content type and a `nil` body signs and sends + /// `{}`: `BRC104HTTPFrameCodec.encodeRequest` takes the body from this + /// payload. An empty body stays empty and is written as -1, never 0 + /// (`clients/AuthFetch.ts:762-770`). public static func encode(_ request: BRC104Request, limits: BRC104Limits = .standard) throws -> [UInt8] { + try encode(request, applyingClientBodyDefault: true, limits: limits) + } + + /// Encodes a request. A server rebuilding the payload of a received + /// request passes `false`: the TypeScript server signs -1 for a bodyless + /// JSON request (`authMiddlewareHelpers.ts:155-185`). + static func encode( + _ request: BRC104Request, applyingClientBodyDefault: Bool, limits: BRC104Limits + ) throws -> [UInt8] { var writer = Writer(limits: limits) try writer.bytes(request.requestID) try writer.string(request.method) try writer.string(request.path) try writer.optionalString(request.query) try writer.headers(request.headers, kind: .request) - try writer.optionalBytes( - normalizedBody(request.body, method: request.method, headers: request.headers)) + try writer.body( + applyingClientBodyDefault + ? normalizedBody(request.body, method: request.method, headers: request.headers) + : request.body) return writer.output } public static func decodeRequest(_ bytes: [UInt8], limits: BRC104Limits = .standard) throws @@ -173,7 +214,9 @@ public enum BRC104Codec { try writer.bytes(response.requestID) try writer.compact(UInt64(response.status)) try writer.headers(response.headers, kind: .response) - try writer.optionalBytes(response.body) + // An empty body is written as -1, never 0 (`SimplifiedFetchTransport.ts:314-321`, + // `auth-express-middleware/src/index.ts:2112-2117`). + try writer.body(response.body) return writer.output } public static func decodeResponse(_ bytes: [UInt8], limits: BRC104Limits = .standard) throws @@ -202,8 +245,8 @@ public enum BRC104Codec { for header in headers { let name = header.name.lowercased() guard validToken(name), name.utf8.count <= limits.maximumHeaderNameBytes, - header.value.utf8.count <= limits.maximumHeaderValueBytes, - safeText(header.value), permitted(name, kind: kind) + header.value.utf8.count <= limits.maximumValueBytes(forHeader: name, kind: kind), + signableValue(header.value), permitted(name, kind: kind) else { throw BRC104Error.invalidHeader } guard names.insert(name).inserted else { throw BRC104Error.duplicateHeader } let (fieldBytes, fieldOverflow) = name.utf8.count.addingReportingOverflow( @@ -213,27 +256,66 @@ public enum BRC104Codec { throw BRC104Error.resourceLimit } total = newTotal - let value = - name == "content-type" - ? String( - header.value.split( - separator: ";", maxSplits: 1, omittingEmptySubsequences: false - )[0] - ) - : header.value + let value = name == "content-type" ? signedContentType(header.value) : header.value guard name != "content-type" || !value.isEmpty else { throw BRC104Error.invalidHeader } result.append(.init(name: name, value: value)) } - return result.sorted { Array($0.name.utf8).lexicographicallyPrecedes(Array($1.name.utf8)) } + // `@bsv/sdk` sorts signed header names with `localeCompare` + // (`clients/AuthFetch.ts:740`, `transports/SimplifiedFetchTransport.ts:286`). + return result.sorted { LocaleCompareOrder.areInIncreasingOrder($0.name, $1.name) } + } + /// The signed form of a `content-type` value, as `authenticatedContentType` + /// in `utils/paymentTransport.ts:84-90` computes it: a `multipart/form-data` + /// value is kept whole so its boundary is signed; any other value is cut at + /// the first `;` and trimmed. + static func signedContentType(_ value: String) -> String { + let mediaType = ecmaScriptTrim( + String(value.split(separator: ";", maxSplits: 1, omittingEmptySubsequences: false)[0])) + return mediaType.lowercased() == "multipart/form-data" ? value : mediaType } + + /// `String.prototype.trim`: ECMAScript white space and line terminators. + static func ecmaScriptTrim(_ value: String) -> String { + func isSpace(_ scalar: Unicode.Scalar) -> Bool { + switch scalar.value { + case 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0xa0, 0xfeff, 0x2028, 0x2029: return true + default: return scalar.properties.generalCategory == .spaceSeparator + } + } + let scalars = value.unicodeScalars + guard let first = scalars.firstIndex(where: { !isSpace($0) }), + let last = scalars.lastIndex(where: { !isSpace($0) }) + else { return "" } + return String(scalars[first...last]) + } + static func permitted(_ name: String, kind: HeaderKind) -> Bool { - if name.hasPrefix("x-bsv-auth-") { return false } + // `@bsv/sdk` leaves every name that starts with `x-bsv-auth` unsigned, + // `x-bsv-authority` included (`AuthFetch.ts:727`, middleware + // `index.ts:2095`). + if name.hasPrefix("x-bsv-auth") { return false } if name.hasPrefix("x-bsv-") { return true } switch kind { case .request: return name == "authorization" || name == "content-type" case .response: return name == "authorization" } } + /// The methods the TypeScript middleware accepts: 1 to 32 uppercase token + /// characters, no digits (`auth-express-middleware/src/index.ts:2002`). + /// `AuthFetch` uppercases the method it sends (`clients/AuthFetch.ts:1310`). + static func validMethod(_ value: String) -> Bool { + (1...32).contains(value.utf8.count) + && value.utf8.allSatisfy { b in + (65...90).contains(b) || "!#$%&'*+.^_`|~-".utf8.contains(b) + } + } + /// The TypeScript middleware rejects a request target (`originalUrl`, the + /// path and query) longer than 8192 UTF-16 code units + /// (`auth-express-middleware/src/index.ts:2024`). + static let maximumRequestTargetLength = 8_192 + static func validTargetLength(path: String, query: String?) -> Bool { + path.utf16.count + (query?.utf16.count ?? 0) <= maximumRequestTargetLength + } static func validToken(_ value: String) -> Bool { !value.isEmpty && value.utf8.allSatisfy { b in @@ -241,17 +323,28 @@ public enum BRC104Codec { || "!#$%&'*+-.^_`|~".utf8.contains(b) } } + /// A header value that reaches the other side unchanged. `fetch` trims + /// leading and trailing white space and reads other bytes as Latin-1 + /// before `@bsv/sdk` rebuilds the signed payload + /// (`SimplifiedFetchTransport.ts:263-283`), so only printable ASCII with + /// no space at either end is signed. + static func signableValue(_ value: String) -> Bool { + value.utf8.allSatisfy { (0x20...0x7E).contains($0) } + && value.utf8.first != 0x20 && value.utf8.last != 0x20 + } static func safeText(_ value: String) -> Bool { value.utf8.allSatisfy { $0 >= 0x20 && $0 != 0x7f } } static func normalizedBody(_ body: [UInt8]?, method: String, headers: [BRC104Header]) -> [UInt8]? { - guard body?.isEmpty != false, + // `#defaultRequestBody` replaces only an absent body (`body !== undefined`) + // and matches `application/json` case-sensitively; an empty body stays + // empty and is written as -1. + guard body == nil, ["POST", "PUT", "PATCH", "DELETE"].contains(method.uppercased()), headers.contains(where: { - $0.name.lowercased() == "content-type" - && $0.value.lowercased().contains("application/json") + $0.name.lowercased() == "content-type" && $0.value.contains("application/json") }) else { return body } return Array("{}".utf8) @@ -277,8 +370,9 @@ public enum BRC104Codec { mutating func optionalString(_ value: String?) throws { if let value { try string(value) } else { try compact(UInt64.max) } } - mutating func optionalBytes(_ value: [UInt8]?) throws { - if let value { try counted(value) } else { try compact(UInt64.max) } + /// BRC-104 writes an absent or empty body as -1. + mutating func body(_ value: [UInt8]?) throws { + if let value, !value.isEmpty { try counted(value) } else { try compact(UInt64.max) } } mutating func headers(_ value: [BRC104Header], kind: HeaderKind) throws { let canonical = try BRC104Codec.normalized(value, kind: kind, limits: limits) diff --git a/Sources/BSVAuth/Certificates/CertificateEngine.swift b/Sources/BSVAuth/Certificates/CertificateEngine.swift index 34e76f5..107fc78 100644 --- a/Sources/BSVAuth/Certificates/CertificateEngine.swift +++ b/Sources/BSVAuth/Certificates/CertificateEngine.swift @@ -11,6 +11,11 @@ public enum CertificateEngine { /// `.self` creates a self-signed certificate. `.anyone` is intentionally /// rejected rather than silently being treated as self, a stricter Swift /// deviation from the pinned Go helper's ambiguous fallback. + /// + /// The certificate is signed with its fields in `localeCompare` order, as + /// `@bsv/sdk` signs them (`certificates/Certificate.ts:290`). Field names + /// must be ASCII; another name throws `CertificateFieldNameError.nonASCII` + /// (COMP-041). public static func issue( type: CertificateTypeID, serialNumber suppliedSerialNumber: CertificateSerialNumber? = nil, @@ -22,6 +27,7 @@ public enum CertificateEngine { randomSource: any SecureRandomSource = SystemSecureRandomSource() ) async throws -> MasterCertificate { try validateFieldSet(plaintextFields, limits: limits) + try Certificate.requireASCIIFieldNames(plaintextFields.keys) let serialNumber: CertificateSerialNumber if let suppliedSerialNumber { serialNumber = suppliedSerialNumber @@ -56,7 +62,7 @@ public enum CertificateEngine { fields: encrypted.fields, limits: limits ) - let signed = try await unsigned.signed(using: certifierWallet, limits: limits) + let signed = try await unsigned.signedInLocaleOrder(using: certifierWallet, limits: limits) return try MasterCertificate(certificate: signed, masterKeyring: encrypted.keyring) } @@ -74,7 +80,7 @@ public enum CertificateEngine { if let certifier = requirements.certifier, certifier != certificate.certifier { throw CertificateError.requirementMismatch } if let outpoint = requirements.revocationOutpoint, outpoint != certificate.revocationOutpoint { throw CertificateError.requirementMismatch } try validateKeyringBounds(masterCertificate.masterKeyring, limits: limits) - guard try await certificate.verifySignature(limits: limits) else { + guard try await certificate.verifySignatureInEitherFieldOrder(limits: limits) else { throw CertificateError.signatureMismatch } let identity = try await subjectWallet.getPublicKey(.init(selection: .identity)).publicKey @@ -116,7 +122,7 @@ public enum CertificateEngine { throw CertificateError.fieldNotFound } try validateKeyringBounds(masterCertificate.masterKeyring, limits: limits) - guard try await certificate.verifySignature(limits: limits) else { + guard try await certificate.verifySignatureInEitherFieldOrder(limits: limits) else { throw CertificateError.signatureMismatch } let identity = try await subjectWallet.getPublicKey(.init(selection: .identity)).publicKey @@ -155,6 +161,9 @@ public enum CertificateEngine { } catch WalletCryptoError.randomGenerationFailed { throw CertificateError.randomGenerationFailed } catch { + AuthLog.reported( + "CertificateEngine field key encryption", error, + as: CertificateError.encryptionFailed) throw CertificateError.encryptionFailed } projected[field] = try CertificateCiphertext( @@ -177,7 +186,7 @@ public enum CertificateEngine { ) async throws -> [CertificateFieldName: String] { let certificate = verifiableCertificate.certificate try validateKeyringBounds(verifiableCertificate.keyring, limits: limits) - guard try await certificate.verifySignature(limits: limits) else { + guard try await certificate.verifySignatureInEitherFieldOrder(limits: limits) else { throw CertificateError.signatureMismatch } return try await decryptAll( @@ -224,12 +233,21 @@ public enum CertificateEngine { throw CertificateError.fieldValueTooLarge(actual: plaintextBytes.count, maximum: limits.maximumFieldPlaintextByteCount) } let key: SymmetricKey - do { key = try SymmetricKey.random(using: randomSource) } - catch { throw CertificateError.randomGenerationFailed } + do { key = try SymmetricKey.random(using: randomSource) } catch { + AuthLog.reported( + "CertificateEngine.issue field key", error, + as: CertificateError.randomGenerationFailed) + throw CertificateError.randomGenerationFailed + } let encryptedField: [UInt8] do { encryptedField = try key.seal(plaintextBytes, using: randomSource) } catch SymmetricKeyError.randomGenerationFailed { throw CertificateError.randomGenerationFailed } - catch { throw CertificateError.encryptionFailed } + catch { + AuthLog.reported( + "CertificateEngine.issue field encryption", error, + as: CertificateError.encryptionFailed) + throw CertificateError.encryptionFailed + } fields[name] = try CertificateCiphertext( encryptedField, maximumByteCount: limits.maximumFieldCiphertextByteCount @@ -245,6 +263,9 @@ public enum CertificateEngine { } catch WalletCryptoError.randomGenerationFailed { throw CertificateError.randomGenerationFailed } catch { + AuthLog.reported( + "CertificateEngine field key encryption", error, + as: CertificateError.encryptionFailed) throw CertificateError.encryptionFailed } keyring[name] = try CertificateCiphertext( @@ -319,12 +340,18 @@ public enum CertificateEngine { ciphertext: wrappedKey.bytes )).plaintext } catch { + AuthLog.reported( + "CertificateEngine field key decryption", error, + as: CertificateError.decryptionFailed) throw CertificateError.decryptionFailed } guard key.count == SymmetricKey.keyByteCount else { throw CertificateError.decryptionFailed } let plaintextBytes: [UInt8] - do { plaintextBytes = try SymmetricKey(key).open(encryptedField.bytes) } - catch { throw CertificateError.decryptionFailed } + do { plaintextBytes = try SymmetricKey(key).open(encryptedField.bytes) } catch { + AuthLog.reported( + "CertificateEngine field decryption", error, as: CertificateError.decryptionFailed) + throw CertificateError.decryptionFailed + } guard plaintextBytes.count <= limits.maximumFieldPlaintextByteCount, let plaintext = String(bytes: plaintextBytes, encoding: .utf8), Array(plaintext.utf8) == plaintextBytes else { @@ -377,8 +404,11 @@ public enum CertificateEngine { private static func draw32(using randomSource: any SecureRandomSource) throws -> [UInt8] { let bytes: [UInt8] - do { bytes = try randomSource.randomBytes(count: 32) } - catch { throw CertificateError.randomGenerationFailed } + do { bytes = try randomSource.randomBytes(count: 32) } catch { + AuthLog.reported( + "CertificateEngine random bytes", error, as: CertificateError.randomGenerationFailed) + throw CertificateError.randomGenerationFailed + } guard bytes.count == 32 else { throw CertificateError.randomGenerationFailed } return bytes } diff --git a/Sources/BSVAuth/Certificates/CertificateSigningOrder.swift b/Sources/BSVAuth/Certificates/CertificateSigningOrder.swift new file mode 100644 index 0000000..873a432 --- /dev/null +++ b/Sources/BSVAuth/Certificates/CertificateSigningOrder.swift @@ -0,0 +1,127 @@ +import BSVCore +import BSVCrypto +import BSVKeys +import BSVWallet +import Foundation + +/// BRC-52 certificate signatures with fields in `localeCompare` order. +/// +/// `@bsv/sdk` signs and verifies the certificate binary with its fields sorted +/// by `localeCompare` (`certificates/Certificate.ts:290`). The Go SDK and +/// `Certificate.binary` sort them by UTF-8 bytes. The two orders agree for +/// lowercase ASCII names and differ for mixed case and some punctuation, for +/// example `age, Zip` against `Zip, age`. This SDK signs in the TypeScript order +/// and accepts a signature over either order. +extension Certificate { + /// The unsigned BRC-52 binary with fields in `LocaleCompareOrder`. + package func localeOrderSigningPreimage(limits: CertificateLimits) throws -> [UInt8] { + let byteOrder = try binary(includingSignature: false, limits: limits) + var records: [CertificateFieldName: [UInt8]] = [:] + var recordBytes = 0 + for (name, value) in fields { + let record = + CompactSize.encodeVarBytes(name.utf8Bytes) + + CompactSize.encodeVarBytes(Array(value.base64.utf8)) + records[name] = record + recordBytes += record.count + } + // The field records end the byte-order binary, so they cannot be + // longer than it. + guard recordBytes <= byteOrder.count else { throw CertificateError.sizeOverflow } + var preimage = Array(byteOrder.prefix(byteOrder.count - recordBytes)) + let names = fields.keys.sorted { + LocaleCompareOrder.areInIncreasingOrder($0.value, $1.value) + } + for name in names { + guard let record = records[name] else { throw CertificateError.fieldNotFound } + preimage += record + } + return preimage + } + + /// Signs the `localeCompare`-ordered preimage with the certifier wallet, + /// as `Certificate.sign` does in `@bsv/sdk`. + /// + /// Field names must be ASCII, the range where `LocaleCompareOrder` is + /// exact. A name with another character could be signed in an order that + /// TypeScript does not reproduce. + package func signedInLocaleOrder( + using wallet: any CertificateSignatureWallet, + limits: CertificateLimits + ) async throws -> Certificate { + guard signature == nil else { throw CertificateError.alreadySigned } + try Self.requireASCIIFieldNames(fields.keys) + let preimage = try localeOrderSigningPreimage(limits: limits) + let identity = try await wallet.getPublicKey(.init(selection: .identity)).publicKey + guard identity == certifier else { throw CertificateError.walletIdentityMismatch } + let result = try await wallet.createSignature( + .init( + protocolID: try CertificateProtocols.signature, + keyID: try WalletKeyID(signatureKeyID), + counterparty: .anyone, + payload: .digest(BSVHashing.sha256(preimage)) + )) + let signed = try replacingSignature(result.signature, limits: limits) + _ = try signed.binary(includingSignature: true, limits: limits) + return signed + } + + /// Throws `CertificateFieldNameError.nonASCII` unless every name is + /// printable ASCII (0x20-0x7E). ICU ignores control characters, so names + /// that differ only by them compare equal and their signed order would + /// depend on how the signer inserted them. + package static func requireASCIIFieldNames( + _ names: some Sequence + ) throws { + for name in names where !name.utf8Bytes.allSatisfy({ (0x20...0x7E).contains($0) }) { + AuthLog.rejected( + "Certificate signing", + "a field name of \(name.utf8Bytes.count) bytes is not printable ASCII", + as: CertificateFieldNameError.nonASCII) + throw CertificateFieldNameError.nonASCII + } + } + + /// Verifies the certifier signature over the `localeCompare`-ordered + /// preimage, or over the UTF-8 byte-ordered preimage that the Go SDK and + /// earlier releases of this SDK sign. + package func verifySignatureInEitherFieldOrder(limits: CertificateLimits) async throws -> Bool { + guard let signature else { throw CertificateError.missingSignature } + _ = try binary(includingSignature: true, limits: limits) + let preimage = try localeOrderSigningPreimage(limits: limits) + let verifier = try ProtoWallet.anyone() + let valid = try await verifier.verifySignature( + .init( + protocolID: try CertificateProtocols.signature, + keyID: try WalletKeyID(signatureKeyID), + counterparty: .publicKey(certifier), + payload: .digest(BSVHashing.sha256(preimage)), + signature: signature + ) + ).valid + if valid { return true } + guard try preimage != binary(includingSignature: false, limits: limits) else { + return false + } + return try await verifySignature(limits: limits) + } +} + +/// A certificate field name this SDK will not sign. +/// +/// `@bsv/sdk` orders signed field names with `localeCompare`, the ICU root +/// collation. `LocaleCompareOrder` reproduces it exactly only for printable +/// ASCII, so `CertificateEngine.issue` refuses other names, including +/// control characters, rather than sign a +/// certificate TypeScript may not verify. Certificates with such names signed +/// elsewhere are still verified in both orders this SDK knows. +public enum CertificateFieldNameError: Error, Equatable, Sendable, LocalizedError { + case nonASCII + + public var errorDescription: String? { + switch self { + case .nonASCII: + "Certificate field names must use only plain ASCII letters, digits, spaces and symbols." + } + } +} diff --git a/Sources/BSVAuth/Certificates/LocaleCompareOrder.swift b/Sources/BSVAuth/Certificates/LocaleCompareOrder.swift new file mode 100644 index 0000000..70f0488 --- /dev/null +++ b/Sources/BSVAuth/Certificates/LocaleCompareOrder.swift @@ -0,0 +1,99 @@ +/// The order `@bsv/sdk` sorts signed names in: JavaScript +/// `String.prototype.localeCompare` with no arguments, which Node and Bun +/// implement with the ICU root collation (`en-US`, tertiary strength, +/// punctuation not ignored). +/// +/// TypeScript uses it for certificate field names in the BRC-52 signing +/// preimage (`certificates/Certificate.ts:290`) and for signed BRC-104 header +/// names (`clients/AuthFetch.ts:740`, +/// `transports/SimplifiedFetchTransport.ts:286`, +/// `auth-express-middleware/src/index.ts:2105`). +/// +/// The order is exact for ASCII. Strings compare by primary weight first: +/// whitespace, then punctuation and symbols in ICU order, then digits, then +/// letters with case ignored. Remaining ties are broken by case, lowercase +/// first. ICU ignores the C0 controls other than tab, line feed, vertical tab, +/// form feed and carriage return, and DEL; so does this order. +/// +/// Other characters are not collated as ICU collates them. C1 controls and the +/// default-ignorable format characters are ignored; every other non-ASCII +/// scalar sorts after all ASCII, in code point order. Names with such +/// characters can sort differently in TypeScript. Strings ICU treats as equal +/// are ordered by UTF-8 bytes, so the order is total; TypeScript keeps their +/// insertion order instead. +package enum LocaleCompareOrder { + /// `true` when `lhs` sorts before `rhs`. + package static func areInIncreasingOrder(_ lhs: String, _ rhs: String) -> Bool { + compare(lhs, rhs) < 0 + } + + /// A negative, zero or positive value, as `localeCompare` returns, with + /// collation ties broken by UTF-8 bytes. + package static func compare(_ lhs: String, _ rhs: String) -> Int { + let left = key(lhs) + let right = key(rhs) + if let order = compareSequences(left.primary, right.primary) { return order } + if let order = compareSequences(left.tertiary, right.tertiary) { return order } + return compareSequences(Array(lhs.utf8), Array(rhs.utf8)) ?? 0 + } + + /// The ASCII characters ICU does not ignore, in ICU root order, each + /// lowercase letter followed by its uppercase form. + package static let asciiOrder = + "\t\n\u{0B}\u{0C}\r _-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$0123456789" + + "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ" + + /// The primary weight of each ASCII scalar, or `nil` when ICU ignores it. + /// An uppercase letter shares the weight of its lowercase form. + private static let asciiPrimary: [UInt32?] = { + var table = [UInt32?](repeating: nil, count: 128) + var weight: UInt32 = 0 + for scalar in asciiOrder.unicodeScalars { + let code = Int(scalar.value) + if (65...90).contains(code) { + table[code] = table[code + 32] + } else { + weight += 1 + table[code] = weight + } + } + return table + }() + + private struct Key { + var primary: [UInt32] = [] + var tertiary: [UInt8] = [] + } + + private static func key(_ value: String) -> Key { + var result = Key() + for scalar in value.unicodeScalars { + let code = scalar.value + if code < 128 { + guard let primary = asciiPrimary[Int(code)] else { continue } + result.primary.append(primary) + result.tertiary.append((65...90).contains(code) ? 1 : 0) + } else if !ignorable(code) { + result.primary.append(1_000 + code) + result.tertiary.append(0) + } + } + return result + } + + private static func ignorable(_ code: UInt32) -> Bool { + switch code { + case 0x80...0x9F, 0xAD, 0x200B...0x200F, 0x2060...0x2064, 0xFEFF: return true + default: return false + } + } + + private static func compareSequences( + _ lhs: [Element], _ rhs: [Element] + ) -> Int? { + for (left, right) in zip(lhs, rhs) where left != right { + return left < right ? -1 : 1 + } + return lhs.count == rhs.count ? nil : (lhs.count < rhs.count ? -1 : 1) + } +} diff --git a/Sources/BSVWallet/Values/WalletCryptoLimits.swift b/Sources/BSVWallet/Values/WalletCryptoLimits.swift index 4cdd4fb..90fa8bf 100644 --- a/Sources/BSVWallet/Values/WalletCryptoLimits.swift +++ b/Sources/BSVWallet/Values/WalletCryptoLimits.swift @@ -1,13 +1,19 @@ /// Bounds on what the wallet's own cryptography reads. /// /// `maximumPayloadByteCount` bounds the data signed, verified, HMACed or encrypted. The default is -/// 16 MiB: the TypeScript `ProtoWallet` sets no bound of its own, and BRC-103 signs each general -/// message's whole payload, which the TypeScript `AuthFetch` allows up to 16 MiB. At 1 MiB, an +/// `defaultPayloadByteCount`, 16 MiB plus 512 KiB: the TypeScript `ProtoWallet` sets no bound of +/// its own, and BRC-103 signs each general message's whole payload, which over HTTP is a body of up +/// to 16 MiB plus the 512 KiB of framing the TypeScript `AuthFetch` allows for +/// (`clients/AuthFetch.ts:147`, `:571`). `AuthLimits.defaultPayloadBytes` in BSVAuth is this same +/// value, so a payload BSVAuth accepts by default can always be signed and verified. At 1 MiB, an /// authenticated request or response over 1 MiB could not be signed or verified. public struct WalletCryptoLimits: Hashable, Sendable { + /// The default payload bound: 16 MiB plus 512 KiB. + public static let defaultPayloadByteCount = (16 << 20) + (512 << 10) + public static let standard = WalletCryptoLimits( - validatedPayload: 16_777_216, - ciphertext: 16_777_264, + validatedPayload: defaultPayloadByteCount, + ciphertext: defaultPayloadByteCount + 48, json: 8_388_608 ) @@ -16,7 +22,7 @@ public struct WalletCryptoLimits: Hashable, Sendable { public let maximumJSONByteCount: Int public init( - maximumPayloadByteCount: Int = 16_777_216, + maximumPayloadByteCount: Int = WalletCryptoLimits.defaultPayloadByteCount, maximumJSONByteCount: Int = 8_388_608 ) throws { guard maximumPayloadByteCount >= 0 else { diff --git a/Tests/BSVAuthTests/AuthLogLines.swift b/Tests/BSVAuthTests/AuthLogLines.swift new file mode 100644 index 0000000..d1bf588 --- /dev/null +++ b/Tests/BSVAuthTests/AuthLogLines.swift @@ -0,0 +1,24 @@ +import BSVAuth +import Foundation + +/// Collects `AuthLog` lines written while a test runs. +final class AuthLogLines: @unchecked Sendable { + private let lock = NSLock() + private var stored: [String] = [] + + var lines: [String] { + lock.lock() + defer { lock.unlock() } + return stored + } + + func record(_ body: () async throws -> T) async rethrows -> T { + try await AuthLog.$observer.withValue({ [self] line in + lock.lock() + stored.append(line) + lock.unlock() + }) { + try await body() + } + } +} diff --git a/Tests/BSVAuthTests/BRC103/AuthMessageCodecTests.swift b/Tests/BSVAuthTests/BRC103/AuthMessageCodecTests.swift index da86e34..fd34427 100644 --- a/Tests/BSVAuthTests/BRC103/AuthMessageCodecTests.swift +++ b/Tests/BSVAuthTests/BRC103/AuthMessageCodecTests.swift @@ -99,7 +99,7 @@ struct AuthMessageCodecTests { } } - @Test("certificate data is accepted only in signed certificate messages") + @Test("requested certificate sets are accepted in initialRequest and general messages") func certificateMessageBoundary() throws { let identity = try fixtureIdentity() let nonce = Base64Encoding.encode([UInt8](repeating: 3, count: 32)) @@ -108,29 +108,29 @@ struct AuthMessageCodecTests { certifiers: [identity], certificateTypes: [type: [try CertificateFieldName("name")]] ) - #expect(throws: AuthError.invalidMessage) { - try AuthMessageCodec.encode( - AuthMessage( - messageType: .initialRequest, - identityKey: identity, - initialNonce: nonce, - requestedCertificates: request - ) - ) - } - #expect(throws: AuthError.invalidMessage) { - try AuthMessageCodec.encode( - AuthMessage( - messageType: .general, - identityKey: identity, - nonce: nonce, - yourNonce: nonce, - payload: [1], - signature: [0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01], - requestedCertificates: request - ) - ) - } + // `@bsv/sdk` 4.1.1 sends its certificate policy in initialRequest + // (`Peer.ts:644-650`), so the codec accepts it there. + let initial = AuthMessage( + messageType: .initialRequest, + identityKey: identity, + initialNonce: nonce, + requestedCertificates: request + ) + #expect(try AuthMessageCodec.decode(AuthMessageCodec.encode(initial)) == initial) + // A general message may carry a requested set: BRC-104 moves one in + // the unsigned `x-bsv-auth-requested-certificates` header + // (`SimplifiedFetchTransport.ts:349`), and `@bsv/sdk` validates it + // like any other set (`AuthMessageValidation.ts:380-382`). + let general = AuthMessage( + messageType: .general, + identityKey: identity, + nonce: nonce, + yourNonce: nonce, + payload: [1], + signature: [0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01], + requestedCertificates: request + ) + #expect(try AuthMessageCodec.decode(AuthMessageCodec.encode(general)) == general) } @Test("rejects excessive JSON nesting before Foundation parsing") diff --git a/Tests/BSVAuthTests/BRC103/BRC103CertificateExchangeTests.swift b/Tests/BSVAuthTests/BRC103/BRC103CertificateExchangeTests.swift index b4c2379..1b6065e 100644 --- a/Tests/BSVAuthTests/BRC103/BRC103CertificateExchangeTests.swift +++ b/Tests/BSVAuthTests/BRC103/BRC103CertificateExchangeTests.swift @@ -21,12 +21,14 @@ struct BRC103CertificateExchangeTests { certificateTypes: [type: [field]] ) let nonce = Base64Encoding.encode([UInt8](repeating: 4, count: 32)) + let sessionNonce = Base64Encoding.encode([UInt8](repeating: 5, count: 48)) let signature = try fixtureSignature().derBytes let requestMessage = AuthMessage( messageType: .certificateRequest, identityKey: requester.publicKey, nonce: nonce, + initialNonce: sessionNonce, yourNonce: nonce, signature: signature, requestedCertificates: request @@ -51,6 +53,7 @@ struct BRC103CertificateExchangeTests { messageType: .certificateResponse, identityKey: peer.publicKey, nonce: nonce, + initialNonce: sessionNonce, yourNonce: nonce, signature: signature, certificates: [certificate] @@ -65,16 +68,26 @@ struct BRC103CertificateExchangeTests { #expect(throws: AuthError.certificateValidationFailed) { try AuthMessageCodec.decode(Array(extraCertificateMember.utf8)) } + + // Certificate messages carry the sender's session nonce + // (`AuthMessageValidation.ts:404`, `:415`). + let withoutInitialNonce = String(decoding: requestJSON, as: UTF8.self) + .replacingOccurrences(of: #""initialNonce":"\#(sessionNonce)","#, with: "") + #expect(throws: AuthError.self) { + try AuthMessageCodec.decode(Array(withoutInitialNonce.utf8)) + } } - @Test("request validation rejects empty, duplicate, and over-limit values") + @Test("request validation rejects duplicate and over-limit values") func requestBounds() throws { let certifier = try key(11).publicKey let type = try CertificateTypeID([UInt8](repeating: 1, count: 32)) let field = try CertificateFieldName("name") - #expect(throws: AuthError.invalidCertificateRequest) { + // `@bsv/sdk` 4.1.1 sends and accepts a set with no certifiers + // (`AuthMessageValidation.ts:134-136`); it asks for nothing. + #expect( try AuthRequestedCertificateSet(certifiers: [], certificateTypes: [type: [field]]) - } + .certifiers.isEmpty) #expect(throws: AuthError.resourceLimit) { try AuthLimits( maximumCertificateCount: AuthLimits.maximumAllowedCertificateCount + 1 @@ -157,6 +170,7 @@ struct BRC103CertificateExchangeTests { messageType: responseMessage.messageType, identityKey: responseMessage.identityKey, nonce: responseMessage.nonce, + initialNonce: responseMessage.initialNonce, yourNonce: responseMessage.yourNonce, signature: requestSignature, certificates: responseMessage.certificates @@ -176,6 +190,432 @@ struct BRC103CertificateExchangeTests { } } + @Test("several certificate requests may be open at once, as in Peer.ts") + func severalOpenRequests() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let requester = PeerAuthenticator(wallet: ProtoWallet(rootKey: requesterKey)) + let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: peerKey)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + let nameType = try CertificateTypeID([UInt8](repeating: 0x31, count: 32)) + let ageType = try CertificateTypeID([UInt8](repeating: 0x32, count: 32)) + let name = try CertificateFieldName("name") + let age = try CertificateFieldName("age") + let first = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [nameType: [name]]) + let second = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [ageType: [age]]) + + // `Peer.ts:474-478` keys each request by nonce; neither replaces the other. + for request in [first, second] { + let message = try sent( + try await requester.makeCertificateRequest(request, using: session.requester)) + guard case .certificateRequest(let received) = try await peer.receive(message).first + else { + Issue.record("missing certificate request") + return + } + #expect(received.request == request) + } + + // Answered out of order: each response settles the request it fits + // (`Peer.ts:1236-1241`). + let ageCertificate = try fixtureCertificate( + subject: peerKey.publicKey, certifier: certifierKey.publicKey, type: ageType, + field: age) + let nameCertificate = try fixtureCertificate( + subject: peerKey.publicKey, certifier: certifierKey.publicKey, type: nameType, + field: name) + let ageResponse = try sent( + try await peer.makeCertificateResponse([ageCertificate], using: session.peer)) + let nameResponse = try sent( + try await peer.makeCertificateResponse([nameCertificate], using: session.peer)) + guard case .certificateResponse(let ageAnswer) = try await requester.receive(ageResponse).first, + case .certificateResponse(let nameAnswer) = try await requester.receive(nameResponse).first + else { + Issue.record("missing certificate response") + return + } + #expect(ageAnswer.requested == second) + #expect(nameAnswer.requested == first) + + // Both are settled, so nothing more is awaited on either side. + await #expect(throws: AuthError.notAuthenticated) { + try await peer.makeCertificateResponse([], using: session.peer) + } + let late = try sent( + try await requester.makeCertificateRequest(first, using: session.requester)) + _ = try await peer.receive(late) + let decline = try sent(try await peer.makeCertificateResponse([], using: session.peer)) + guard case .certificateResponse(let declined) = try await requester.receive(decline).first + else { + Issue.record("missing certificate response") + return + } + #expect(declined.requested == first) + } + + @Test("an empty answer declines the oldest open request; at most 16 are open") + func openRequestOrderAndLimit() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let requester = PeerAuthenticator(wallet: ProtoWallet(rootKey: requesterKey)) + let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: peerKey)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + var requests: [AuthRequestedCertificateSet] = [] + for index in 0..<16 { + let request = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], + certificateTypes: [ + try CertificateTypeID([UInt8](repeating: UInt8(0x40 + index), count: 32)): + [try CertificateFieldName("name")] + ]) + requests.append(request) + _ = try await peer.receive( + try sent(try await requester.makeCertificateRequest(request, using: session.requester))) + } + await #expect(throws: AuthError.resourceLimit) { + try await requester.makeCertificateRequest(requests[0], using: session.requester) + } + + let decline = try sent(try await peer.makeCertificateResponse([], using: session.peer)) + guard case .certificateResponse(let declined) = try await requester.receive(decline).first + else { + Issue.record("missing certificate response") + return + } + #expect(declined.requested == requests[0]) + #expect(declined.certificates.isEmpty) + // One slot is free again. + _ = try await requester.makeCertificateRequest(requests[0], using: session.requester) + } + + @Test("a response can name the request it answers") + func answeringNamedRequest() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let requester = PeerAuthenticator(wallet: ProtoWallet(rootKey: requesterKey)) + let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: peerKey)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + let type = try CertificateTypeID([UInt8](repeating: 0x31, count: 32)) + let other = try CertificateTypeID([UInt8](repeating: 0x32, count: 32)) + let name = try CertificateFieldName("name") + let first = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [type: [name]]) + let second = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [other: [name], type: [name]]) + for request in [first, second] { + _ = try await peer.receive( + try sent(try await requester.makeCertificateRequest(request, using: session.requester))) + } + let certificate = try fixtureCertificate( + subject: peerKey.publicKey, certifier: certifierKey.publicKey, type: type, field: name) + let unasked = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [other: [name]]) + await #expect(throws: AuthError.unexpectedMessage) { + try await peer.makeCertificateResponse( + [certificate], using: session.peer, answering: unasked) + } + // The certificate fits both; `answering` settles the second. + _ = try await peer.makeCertificateResponse( + [certificate], using: session.peer, answering: second) + let left = try sent(try await peer.makeCertificateResponse([certificate], using: session.peer)) + guard case .certificateResponse(let received) = try await requester.receive(left).first + else { + Issue.record("missing certificate response") + return + } + #expect(received.requested == first) + } + + @Test("a response fitting a certificateRequest and the handshake policy settles both, as in Peer.ts") + func requestBeforeHandshakePolicy() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let type = try CertificateTypeID([UInt8](repeating: 0x31, count: 32)) + let name = try CertificateFieldName("name") + let age = try CertificateFieldName("age") + let policy = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [type: [name]]) + let request = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [type: [name, age]]) + let requester = PeerAuthenticator( + wallet: ProtoWallet(rootKey: requesterKey), certificatesToRequest: policy) + let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: peerKey)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + _ = try await peer.receive( + try sent(try await requester.makeCertificateRequest(request, using: session.requester))) + + // The certificate fits both. `Peer.ts:1240` validates it against + // the certificateRequest, `:1245` settles that request and `:1247` + // counts the handshake policy as answered too. + let certificate = try fixtureCertificate( + subject: peerKey.publicKey, certifier: certifierKey.publicKey, type: type, field: name) + let answer = try sent( + try await peer.makeCertificateResponse([certificate], using: session.peer)) + let actions = try await requester.receive(answer) + let settled = actions.compactMap { action -> AuthRequestedCertificateSet? in + guard case .certificateResponse(let response) = action else { return nil } + #expect(response.certificates == [certificate]) + return response.requested + } + #expect(settled == [request, policy]) + + // Nothing is open on either side now. + await #expect(throws: AuthError.notAuthenticated) { + try await peer.makeCertificateResponse([], using: session.peer) + } + } + + @Test("an empty response settles one request, not the handshake policy as well") + func emptyResponseSettlesOne() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let type = try CertificateTypeID([UInt8](repeating: 0x31, count: 32)) + let name = try CertificateFieldName("name") + let policy = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [type: [name]]) + let requester = PeerAuthenticator( + wallet: ProtoWallet(rootKey: requesterKey), certificatesToRequest: policy) + let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: peerKey)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + let request = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], + certificateTypes: [type: [name, try CertificateFieldName("age")]]) + _ = try await peer.receive( + try sent(try await requester.makeCertificateRequest(request, using: session.requester))) + // `Peer.ts:1229` looks at a response only when it carries certificates. + let decline = try sent(try await peer.makeCertificateResponse([], using: session.peer)) + let first = try await requester.receive(decline) + #expect(first.count == 1) + guard case .certificateResponse(let declined) = first.first else { + Issue.record("missing certificate response") + return + } + #expect(declined.requested == request) + // The handshake policy is still open on both sides. + let second = try await requester.receive( + try sent(try await peer.makeCertificateResponse([], using: session.peer))) + guard case .certificateResponse(let declinedPolicy) = second.first else { + Issue.record("missing certificate response") + return + } + #expect(declinedPolicy.requested == policy) + } + + @Test("open received requests share one byte budget, and a repeat is refused") + func receivedRequestBudget() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let requester = PeerAuthenticator(wallet: ProtoWallet(rootKey: requesterKey)) + // Each request below is charged 33 + 32 + 4 = 69 bytes. + let peer = PeerAuthenticator( + wallet: ProtoWallet(rootKey: peerKey), + limits: try AuthLimits(maximumCertificateAggregateBytes: 200)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + func request(_ byte: UInt8) throws -> AuthRequestedCertificateSet { + try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], + certificateTypes: [ + try CertificateTypeID([UInt8](repeating: byte, count: 32)): + [try CertificateFieldName("name")] + ]) + } + func ask(_ set: AuthRequestedCertificateSet) async throws -> [AuthPeerAction] { + try await peer.receive( + try sent(try await requester.makeCertificateRequest(set, using: session.requester))) + } + _ = try await ask(try request(0x50)) + let log = AuthLogLines() + await log.record { + await #expect(throws: AuthError.unexpectedMessage) { + try await ask(try request(0x50)) + } + } + #expect(log.lines.contains { $0.contains("an identical request is already open") }) + _ = try await ask(try request(0x51)) + await #expect(throws: AuthError.resourceLimit) { + try await ask(try request(0x52)) + } + // The session stays usable; answering one frees its share. + #expect((await peer.session(session.peer))?.state == .authenticated) + _ = try await peer.makeCertificateResponse([], using: session.peer) + _ = try await ask(try request(0x52)) + } + + @Test("a response's signature is checked before it is matched") + func signatureBeforeMatching() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let requester = PeerAuthenticator(wallet: ProtoWallet(rootKey: requesterKey)) + let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: peerKey)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + let type = try CertificateTypeID([UInt8](repeating: 0x31, count: 32)) + let name = try CertificateFieldName("name") + let request = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [type: [name]]) + _ = try await peer.receive( + try sent(try await requester.makeCertificateRequest(request, using: session.requester))) + let response = try sent(try await peer.makeCertificateResponse([], using: session.peer)) + // Certificates that fit no request, under a signature over none. + let unfitting = try fixtureCertificate( + subject: peerKey.publicKey, certifier: certifierKey.publicKey, + type: try CertificateTypeID([UInt8](repeating: 0x39, count: 32)), field: name) + let forged = AuthMessage( + messageType: response.messageType, identityKey: response.identityKey, + nonce: response.nonce, initialNonce: response.initialNonce, + yourNonce: response.yourNonce, signature: response.signature, + certificates: [unfitting]) + let log = AuthLogLines() + await log.record { + await #expect(throws: AuthError.invalidSignature) { + try await requester.receive(forged) + } + } + #expect(log.lines.isEmpty) + } + + @Test("an unsolicited response is checked for its signature before it is refused") + func unsolicitedResponseSignatureFirst() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let requester = PeerAuthenticator(wallet: ProtoWallet(rootKey: requesterKey)) + let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: peerKey)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + let request = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], + certificateTypes: [ + try CertificateTypeID([UInt8](repeating: 0x31, count: 32)): + [try CertificateFieldName("name")] + ]) + _ = try await peer.receive( + try sent(try await requester.makeCertificateRequest(request, using: session.requester))) + let response = try sent(try await peer.makeCertificateResponse([], using: session.peer)) + _ = try await requester.receive(response) + // Nothing is open now. `Peer.ts:1202-1217` checks the signature first. + let forged = AuthMessage( + messageType: .certificateResponse, identityKey: response.identityKey, + nonce: Base64Encoding.encode([UInt8](repeating: 0x77, count: 32)), + initialNonce: response.initialNonce, yourNonce: response.yourNonce, + signature: response.signature, certificates: []) + await #expect(throws: AuthError.invalidSignature) { + try await requester.receive(forged) + } + } + + @Test("a refused certificateRequest uses up its nonce") + func refusedRequestCannotBeReplayed() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let requester = PeerAuthenticator(wallet: ProtoWallet(rootKey: requesterKey)) + let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: peerKey)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + let request = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], + certificateTypes: [ + try CertificateTypeID([UInt8](repeating: 0x31, count: 32)): + [try CertificateFieldName("name")] + ]) + _ = try await peer.receive( + try sent(try await requester.makeCertificateRequest(request, using: session.requester))) + let repeated = try sent( + try await requester.makeCertificateRequest(request, using: session.requester)) + let log = AuthLogLines() + await log.record { + await #expect(throws: AuthError.unexpectedMessage) { + try await peer.receive(repeated) + } + // `Peer.ts:1088-1092` claims the nonce before acting on the request. + await #expect(throws: AuthError.replay) { + try await peer.receive(repeated) + } + // Even once the first request is answered and the repeat would fit. + _ = try? await peer.makeCertificateResponse([], using: session.peer) + await #expect(throws: AuthError.replay) { + try await peer.receive(repeated) + } + } + #expect(log.lines.count == 1) + } + + @Test("a sender can stop waiting for a request the peer refused") + func withdrawRefusedRequest() async throws { + let requesterKey = try key(3) + let peerKey = try key(7) + let certifierKey = try key(11) + let requester = PeerAuthenticator(wallet: ProtoWallet(rootKey: requesterKey)) + let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: peerKey)) + let session = try await authenticate(requester, peer, peerKey: peerKey.publicKey) + let request = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], + certificateTypes: [ + try CertificateTypeID([UInt8](repeating: 0x31, count: 32)): + [try CertificateFieldName("name")] + ]) + _ = try await peer.receive( + try sent(try await requester.makeCertificateRequest(request, using: session.requester))) + await #expect(throws: AuthError.unexpectedMessage) { + try await peer.receive( + try self.sent( + try await requester.makeCertificateRequest(request, using: session.requester))) + } + #expect(await requester.withdrawCertificateRequest(request, using: session.requester)) + // One answer settles the one request still open on each side. + _ = try await requester.receive( + try sent(try await peer.makeCertificateResponse([], using: session.peer))) + #expect(await requester.withdrawCertificateRequest(request, using: session.requester) == false) + } + + @Test("only errors this SDK defines are logged in clear") + func logPrivacy() async throws { + #expect(AuthLog.isSDKError(AuthError.invalidSignature)) + #expect(AuthLog.isSDKError(BRC104Error.invalidMethod)) + #expect(!AuthLog.isSDKError(WalletFailure(secret: "x"))) + #expect(!AuthLog.isSDKError(CocoaError(.fileNoSuchFile))) + + // Through a real call path: a caller's wallet fails while a + // certificate field is decrypted. + let certifierKey = try key(13) + let subjectKey = try key(17) + let verifierKey = try key(19) + let type = try CertificateTypeID([UInt8](repeating: 0x41, count: 32)) + let field = try CertificateFieldName("email") + let master = try await CertificateEngine.issue( + type: type, subject: .publicKey(subjectKey.publicKey), + plaintextFields: [field: "alice@example.test"], + using: ProtoWallet(rootKey: certifierKey)) + let projected = try await CertificateEngine.project( + master, fields: [field], to: verifierKey.publicKey, + using: ProtoWallet(rootKey: subjectKey)) + let request = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], certificateTypes: [type: [field]]) + let failing = FailingDecryptWallet( + base: ProtoWallet(rootKey: verifierKey), secret: "wallet secret 1234") + let entries = AuthLogEntries() + await entries.record { + await #expect(throws: AuthError.certificateValidationFailed) { + try await AuthCertificateExchange.validate( + [projected], from: subjectKey.publicKey, requested: request, using: failing) + } + } + let walletEntry = try #require( + entries.entries.first { $0.detail.contains("wallet secret 1234") }) + #expect(walletEntry.detailIsPrivate) + #expect(walletEntry.prefix.hasPrefix("CertificateEngine field key decryption: WalletFailure")) + #expect(entries.entries.allSatisfy { !$0.publicText.contains("wallet secret 1234") }) + // The SDK's own errors along the same path are public. + #expect(entries.entries.contains { !$0.detailIsPrivate }) + } + @Test("wallet preparation and validation are exact and all-or-nothing") func walletPreparationAndValidation() async throws { let certifierKey = try key(13) @@ -309,6 +749,58 @@ struct BRC103CertificateExchangeTests { } } +private struct WalletFailure: Error { + let secret: String +} + +/// A caller's wallet that fails to decrypt with an error holding a secret. +private struct FailingDecryptWallet: CertificateWallet { + let base: ProtoWallet + let secret: String + + func getPublicKey(_ request: WalletGetPublicKeyRequest) async throws -> WalletGetPublicKeyResult { + try await base.getPublicKey(request) + } + func createSignature( + _ request: WalletCreateSignatureRequest + ) async throws -> WalletCreateSignatureResult { + try await base.createSignature(request) + } + func verifySignature( + _ request: WalletVerifySignatureRequest + ) async throws -> WalletVerifySignatureResult { + try await base.verifySignature(request) + } + func encrypt(_ request: WalletEncryptRequest) async throws -> WalletEncryptResult { + try await base.encrypt(request) + } + func decrypt(_ request: WalletDecryptRequest) async throws -> WalletDecryptResult { + throw WalletFailure(secret: secret) + } +} + +/// Collects `AuthLog` entries about underlying errors while a test runs. +private final class AuthLogEntries: @unchecked Sendable { + private let lock = NSLock() + private var stored: [AuthLog.Entry] = [] + + var entries: [AuthLog.Entry] { + lock.lock() + defer { lock.unlock() } + return stored + } + + func record(_ body: () async throws -> Void) async rethrows { + try await AuthLog.$entryObserver.withValue({ [self] entry in + lock.lock() + stored.append(entry) + lock.unlock() + }) { + try await body() + } + } +} + private actor CertificateOperationStub: WalletCertificateOperations { let certificate: Certificate let keyring: [CertificateFieldName: CertificateCiphertext] diff --git a/Tests/BSVAuthTests/BRC103/PeerAuthenticatorTests.swift b/Tests/BSVAuthTests/BRC103/PeerAuthenticatorTests.swift index 00a9c5a..7d03bd4 100644 --- a/Tests/BSVAuthTests/BRC103/PeerAuthenticatorTests.swift +++ b/Tests/BSVAuthTests/BRC103/PeerAuthenticatorTests.swift @@ -107,6 +107,49 @@ struct PeerAuthenticatorTests { #expect(await expiring.session(start.sessionID) == nil) } + @Test("a general message at the default payload limit is signed and verified") + func defaultPayloadLimitThroughTheWallet() async throws { + // `AuthLimits` and the default wallet share one bound, so whatever + // the authenticator accepts, `ProtoWallet` can sign and verify. + #expect(AuthLimits.defaultPayloadBytes == WalletCryptoLimits.defaultPayloadByteCount) + #expect(AuthLimits.standard.maximumPayloadBytes == (16 << 20) + (512 << 10)) + let aKey = try privateKey(3) + let bKey = try privateKey(7) + let a = PeerAuthenticator(wallet: ProtoWallet(rootKey: aKey)) + let b = PeerAuthenticator(wallet: ProtoWallet(rootKey: bKey)) + let start = try await a.beginAuthentication(with: bKey.publicKey) + _ = try await a.receive(try sentMessage(try await b.receive(try sentMessage(start.actions)))) + let payload = [UInt8](repeating: 0x2a, count: AuthLimits.defaultPayloadBytes) + let message = try sentMessage([ + try await a.makeGeneralMessage(payload: payload, using: start.sessionID) + ]) + guard case .deliver(let delivered) = try await b.receive(message).first else { + Issue.record("the general message was not delivered") + return + } + #expect(delivered.payload.count == AuthLimits.defaultPayloadBytes) + + // One byte more is refused on both sides, before the wallet is asked. + await #expect(throws: AuthError.resourceLimit) { + try await a.makeGeneralMessage(payload: payload + [0], using: start.sessionID) + } + let larger = AuthLimits.defaultPayloadBytes + 1 + let wide = PeerAuthenticator( + wallet: ProtoWallet( + rootKey: aKey, limits: try WalletCryptoLimits(maximumPayloadByteCount: larger)), + limits: try AuthLimits(maximumPayloadBytes: larger)) + let wideStart = try await wide.beginAuthentication(with: bKey.publicKey) + _ = try await wide.receive( + try sentMessage(try await b.receive(try sentMessage(wideStart.actions)))) + let oversized = try sentMessage([ + try await wide.makeGeneralMessage(payload: payload + [0], using: wideStart.sessionID) + ]) + // `AuthMessageCodec.validate` refuses it before the signature is checked. + await #expect(throws: AuthError.invalidMessage) { + try await b.receive(oversized) + } + } + @Test("redacts authentication values") func redaction() async throws { let peer = PeerAuthenticator(wallet: ProtoWallet(rootKey: try privateKey(3))) diff --git a/Tests/BSVAuthTests/BRC103/TypeScriptAuthVectors.swift b/Tests/BSVAuthTests/BRC103/TypeScriptAuthVectors.swift new file mode 100644 index 0000000..df436c4 --- /dev/null +++ b/Tests/BSVAuthTests/BRC103/TypeScriptAuthVectors.swift @@ -0,0 +1,123 @@ +// Vectors produced by running the `@bsv/sdk` 4.1.1 source (ts-stack origin/main +// 3b1abc569) with the generator in Documentation/Compatibility/TypeScriptAuthVectors.md. +// Keys are the scalars 3 (TypeScript peer), 7 (Swift peer) and 11 (certifier). Strings are +// the exact `JSON.stringify` wire text the TypeScript transports send. Do not edit by hand. +enum TypeScriptAuthVectors { + static let typeScriptIdentity = "02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9" + static let swiftIdentity = "025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc" + static let certifier = "03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb" + + /// `Peer.processInitialRequest` answering a Swift initialRequest whose nonce is 48 bytes of + /// 0x41, with a handshake certificate policy (`Peer.ts:866-875`). + static let initialResponse = + #"{"version":"0.1","messageType":"initialResponse","identityKey":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","initialNonce":"t2GehKKRKfHzFdmJoYaoJHdwFmckHJj79NcYY8vQsfsfp6GwDYCAOyvKa005uh1k","yourNonce":"QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB","requestedCertificates":{"certifiers":["03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb"],"types":{"UVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVE=":["email"]}},"signature":[48,69,2,33,0,249,37,249,204,111,204,41,161,15,17,26,177,57,50,91,87,70,166,39,144,236,230,139,126,25,222,249,62,217,33,145,244,2,32,12,205,11,122,207,186,76,248,57,86,141,216,232,181,83,93,227,180,64,79,121,122,100,234,169,190,147,172,19,48,253,106]}"# + + /// `Peer.sendCertificateResponse` (`Peer.ts:1129-1171`) answering the Swift request for + /// `certificateFields`. Fields are in issue order, the keyring in reveal order. + static let certificateResponse = + #"{"version":"0.1","messageType":"certificateResponse","identityKey":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","nonce":"EL06aQMDYM9nyBPqYX7SvtFjabdPl03qT+AbEoK7dtw=","initialNonce":"t2GehKKRKfHzFdmJoYaoJHdwFmckHJj79NcYY8vQsfsfp6GwDYCAOyvKa005uh1k","yourNonce":"QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB","certificates":[{"type":"YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE=","serialNumber":"YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmI=","subject":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","certifier":"03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","revocationOutpoint":"0000000000000000000000000000000000000000000000000000000000000000.0","fields":{"userName":"nijMv898VDwVehKVHQOZTVPJoVawruML2G6x1us7pXgkpOAFQFzzC7zNvU3mzgSyUnuLJ68=","profilePhoto":"4x/Mk889OSNCpSolyILlx8uJSTxX/HbFvxEUa4nZXr2CAfBfGO5NF1/LOmGvV80wJquXX/NotyQO8j5DdniEHRp9m+FZEZokFcM=","a&b":"couccQyLN80AJRt7zqZdL3y2bCadjY4GsIJxPgglhs4Tp8Ii8Ua1Ez9qyltVCFcZgmvx"},"signature":"30450221009daf6400fc86107ffbe6fc2d8388dbeedb767dc132e056436aba726e082fbde0022077a5297f6467f561db2b65dbfdb8f017790737cc35d5c550c7d2a2cc26d44634","keyring":{"profilePhoto":"2z9rOKSCx+SOFgeepLUmpeBhnmACoCe/PtdgFsgJ0qhS5c5xndVjqecQ+jv8sVTR6PHrf/m7sRkX56qw0GL8NAqaIZlHRWs+OKHz64q4SXA=","a&b":"MyhofFrHB5hfmE3Bt8GqY7ZWGcSE/9+MrdgRougNhP3TFYMjrYDOgoHc91Tb0GrNSEh59K3dP81q6oCSN5dzgkkX5OQ9HIIoyMXwtTr2yqY=","userName":"I1oxXmBESB0B5vLsJuJKEmg/bcxq4e20cX8z5TO5969eAnWaLokfA5yEpNJrq2HiJ9B/24O0C+ePpm3+X31z6XtYGIfbPCRG8Mqia7+BhBE="}}],"signature":[48,69,2,33,0,130,119,51,11,102,215,45,215,57,101,146,91,129,90,26,142,181,164,42,198,189,98,2,232,6,170,181,111,69,180,117,133,2,32,104,132,101,212,78,204,10,137,96,167,12,68,98,248,44,234,39,213,42,12,155,238,159,76,219,208,88,51,64,242,66,246]}"# + + /// `Peer.requestCertificates` (`Peer.ts:430-490`) with types inserted 0x02… then 0x01…. + static let certificateRequest = + #"{"version":"0.1","messageType":"certificateRequest","identityKey":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","nonce":"uOSuu7zNANSHpD6jzPoQOJCR8dgalxH0ugqzNm7YtBM=","initialNonce":"t2GehKKRKfHzFdmJoYaoJHdwFmckHJj79NcYY8vQsfsfp6GwDYCAOyvKa005uh1k","yourNonce":"QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB","requestedCertificates":{"certifiers":["03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb"],"types":{"AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=":["name","email"],"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=":["x"]}},"signature":[48,68,2,32,102,15,10,147,50,62,188,241,129,225,6,25,39,199,62,61,209,242,141,252,151,78,76,118,117,218,221,85,135,95,242,215,2,32,97,102,217,124,194,79,89,42,87,226,162,166,193,205,133,54,7,147,126,130,109,108,127,234,11,35,144,77,175,159,107,48]}"# + + /// The certificate type the Swift peer requested and its plaintext fields. + static let certificateType = [UInt8](repeating: 0x61, count: 32) + static let certificateFields: [(name: String, value: String)] = [ + ("userName", "Alice"), + ("profilePhoto", "https://example.test/p.png"), + ("a&b", "x>y"), + ] + + /// `SimplifiedFetchTransport` handshake body sent by `AuthFetch` to a server whose session + /// nonce is 48 bytes of 0x61. + static let authFetchInitialRequest = + #"{"version":"0.1","messageType":"initialRequest","identityKey":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","initialNonce":"21Uw2kMrt/9UZz+7VUm1pYsiyy1jTRm5UaQdCyXemqfMdCyYSU+rYAi/F1UGZFIr","requestedCertificates":{"certifiers":[],"types":{}}}"# + + /// The HTTP request `AuthFetch.fetch(url, { method: "GET" })` then sends for + /// `https://swift.example/a` (`SimplifiedFetchTransport.ts:189-194`). + static let authFetchMethod = "GET" + static let authFetchPath = "/a" + static let authFetchHeaders: [(name: String, value: String)] = [ + ("x-bsv-auth-identity-key", "02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"), + ("x-bsv-auth-nonce", "34BBeQmZbcIjiX9sCjViz9CMe2DMiHthnyW6GK8wnlU="), + ("x-bsv-auth-request-id", "rjJeyo4LMVSfdwJ2KVdfUTFtE0ziXiwECF+FMiTTNRg="), + ("x-bsv-auth-signature", "3045022100ab14f827b68fbf3b46bf42fdb919a28a2d55560039403c7a015f94005c70024202202cd89cc0eac92e7e66d8ce9ddcd0d7d18e6b0f84f41df2f2935f8df33a0bc628"), + ("x-bsv-auth-version", "0.1"), + ("x-bsv-auth-your-nonce", "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh"), + ] + + /// `AuthFetch.serializeRequest` (`clients/AuthFetch.ts:784-818`) with request ID 32×0x07. + static let serializedGetNoBody = + "070707070707070707070707070707070707070707070707070707070707070703474554022f61ffffffffffffffffff00ffffffffffffffffff" + static let serializedPostJsonDefault = + "070707070707070707070707070707070707070707070707070707070707070704504f5354092f76312f6974656d73ffffffffffffffffff010c636f6e74656e742d74797065106170706c69636174696f6e2f6a736f6e027b7d" + static let serializedPostEmptyString = + "070707070707070707070707070707070707070707070707070707070707070704504f5354092f76312f6974656d73ffffffffffffffffff010c636f6e74656e742d74797065106170706c69636174696f6e2f6a736f6effffffffffffffffff" + static let serializedContentTypeSpaces = + "070707070707070707070707070707070707070707070707070707070707070704504f5354092f76312f6974656d73043f783d31010c636f6e74656e742d74797065106170706c69636174696f6e2f6a736f6e077b2261223a317d" + static let serializedMultipart = + "070707070707070707070707070707070707070707070707070707070707070704504f5354072f75706c6f6164ffffffffffffffffff010c636f6e74656e742d74797065246d756c7469706172742f666f726d2d646174613b20626f756e646172793d6162633132330470617274" + + /// `Peer.processInitialRequest` with no listener answering a Swift initialRequest (nonce + /// 48 bytes of 0x41) that carries `handshakePolicy`: the wallet's certificate is included + /// in initialResponse (`Peer.ts:836-849`, `Peer.ts:872`). The certificate was issued by + /// `MasterCertificate.issueCertificateForSubject` with `handshakeFields` in this order. + static let initialResponseWithCertificates = + #"{"version":"0.1","messageType":"initialResponse","identityKey":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","initialNonce":"pSRSlnhZqBpHB0ZhS+ty0CS3xklJMplE71l5vfWYbsGYnWd0AR9PQJMIKZn1zRVn","yourNonce":"QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB","certificates":[{"type":"cXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXE=","serialNumber":"cnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnI=","subject":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","certifier":"03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","revocationOutpoint":"0000000000000000000000000000000000000000000000000000000000000000.0","fields":{"Zip":"3gf6t4OfmHH/zq+ClRv5jqu+qa6orjSfq/bASIqPcSisGi9ARuudggYdlo2w6pHGMceoxG8=","age":"kPUGb15CmxrmGMOUJk3Yjf6OQz2qbf2VibczTKNFu+JdiB+mP7lsCW0SVp0MPv0x01A=","a-b":"5488fUBFuQLITiTHyiYv+0dixBymT13lGIG2UfH4iVIsLB30HXSWmu7Pn5GDFoJ137wD2g==","a_b":"Zga0RrT4c74Wi0NzqGICMOd2IzXPPiF0H26JPZPKZLlR8ZAN9M1uGxZJnNC0mbU8nRPoNLNKX5+2FA=="},"signature":"3045022100b35528432b32e67eab8a90180274c2ce95136865c6df6d1b9fff5630e1cf72a902204350b8c38da0b7ce885b39a7d030098b452ed61ea4864a89b6a8a94b340ea914","keyring":{"Zip":"9Smff62IiabgK0ivnZA56qeC1YMwur2n+v7eoTsiylK7wo85Y1getFsPKhjNA657r+LEAzOsTjQPnCphEQoM/HIKKXYK0MxF4AdwJ2dftT0=","age":"rvlNNesJX7zgj74e2LaSWvTDugZjrYMEgeGSnoERCERDcQzf7W3+/FZQyh6HZ44UZp66k19IAx45Vq0dhLRDpJp4/3kBl7HW3VynVyvLDUo=","a_b":"WySh7VB4LsdmuxlaP2LlXxQOaC997pEv4BQy/rKLpyOocNwBJ4lomZG1Kkp2oKPgpgI+lj2O6ljdKsJObKSU3iZJ85VhCKEvw46PUxWxnSk="}}],"requestedCertificates":{"certifiers":[],"types":{}},"signature":[48,68,2,32,32,173,160,191,207,86,48,118,150,22,192,70,89,41,249,214,216,21,217,218,25,186,8,39,143,253,1,30,178,66,215,49,2,32,31,210,32,24,185,117,253,158,247,173,35,152,218,151,248,226,236,238,70,83,34,246,111,135,219,241,203,20,85,64,195,233]}"# + static let handshakeCertificateType = [UInt8](repeating: 0x71, count: 32) + static let handshakeRequestedFields = ["Zip", "age", "a_b"] + static let handshakeFields: [(name: String, value: String)] = [ + ("Zip", "90210"), + ("age", "30"), + ("a-b", "dash"), + ("a_b", "underscore"), + ] + + /// A TS `Peer` initiator's initialRequest to a Swift responder whose nonce is 48 bytes of + /// 0x61, then `Peer.requestCertificates({ certifiers: [], types: {} })`. + static let emptyRequestInitialRequest = + #"{"version":"0.1","messageType":"initialRequest","identityKey":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","initialNonce":"DISF/nIEYj2XCTXSFNevRHQwhA+wzZhk/oaMpNXTgWTRFq6JvNVxPCcXof/PK24g","requestedCertificates":{"certifiers":[],"types":{}}}"# + static let emptyCertificateRequest = + #"{"version":"0.1","messageType":"certificateRequest","identityKey":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","nonce":"pE8az4ZVFQOJNre5boun9nHNDvdjZAd7KIvVWWzNAgc=","initialNonce":"DISF/nIEYj2XCTXSFNevRHQwhA+wzZhk/oaMpNXTgWTRFq6JvNVxPCcXof/PK24g","yourNonce":"YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh","requestedCertificates":{"certifiers":[],"types":{}},"signature":[48,69,2,33,0,167,181,167,72,66,187,106,236,29,171,58,69,25,189,157,24,148,59,227,111,227,89,66,228,152,143,136,165,40,215,186,173,2,32,102,170,157,112,234,194,192,3,203,142,43,230,176,97,239,3,188,61,239,61,216,197,89,163,200,62,175,255,148,1,192,104]}"# + + /// A certificate signed by `Certificate.sign` (`Certificate.ts:464-485`) with field names + /// that `localeCompare` and byte order sort differently, and its unsigned binary + /// (`Certificate.ts:290`). + static let mixedCaseCertificate = + #"{"type":"gYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYE=","serialNumber":"goKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoI=","subject":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","certifier":"03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","revocationOutpoint":"0000000000000000000000000000000000000000000000000000000000000000.0","fields":{"Zip":"AQ==","age":"Ag==","a-b":"Aw==","a_b":"BA==","Email":"BQ==","email":"Bg=="},"signature":"3045022100df81a49a963198439b6f035955214a3b37375f3396463bacb97525349e7e9889022075bc35f586ab78bc3b09f407737d7065a46a597e9eeb0f78bb76f77ed6e56b0f"}"# + static let mixedCaseCertificatePreimage = + "8181818181818181818181818181818181818181818181818181818181818181828282828282828282828282828282828282828282828282828282828282828202f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f903774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb0000000000000000000000000000000000000000000000000000000000000000000603615f620442413d3d03612d620441773d3d036167650441673d3d05656d61696c0442673d3d05456d61696c0442513d3d035a69700441513d3d" + + /// `AuthFetch.serializeRequest` with headers sorted by `localeCompare` (`AuthFetch.ts:740`). + static let serializedHeaderOrder = + "070707070707070707070707070707070707070707070707070707070707070704504f5354022f68ffffffffffffffffff070c636f6e74656e742d74797065106170706c69636174696f6e2f6a736f6e09782d6273762d615f62013409782d6273762d612d62013309782d6273762d612e62013508782d6273762d616201320b782d6273762d757070657201360a782d6273762d7a6574610131027b7d" + + /// A TS `AuthFetch` client whose wallet holds a certificate, against a Swift server + /// (nonce 48 bytes of 0x61) whose policy is `serverPolicyFields` of + /// `serverPolicyCertificateType`: its handshake body, the initialResponse the server + /// was expected to send, the certificateResponse `AuthFetch` then posted on its own + /// (`clients/AuthFetch.ts:496-511`), and the headers of the GET it sent next. + static let policyInitialRequest = + #"{"version":"0.1","messageType":"initialRequest","identityKey":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","initialNonce":"36fQZMGI/qb/BJPvo+duptf66NmajaSKzY+nFdekqQKx8HuzckGbNzYeZaLUngtF","requestedCertificates":{"certifiers":[],"types":{}}}"# + static let policyInitialResponse = + #"{"version":"0.1","messageType":"initialResponse","identityKey":"025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","nonce":"YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh","initialNonce":"YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh","yourNonce":"36fQZMGI/qb/BJPvo+duptf66NmajaSKzY+nFdekqQKx8HuzckGbNzYeZaLUngtF","signature":[48,68,2,32,18,168,85,75,185,246,163,31,25,219,164,3,230,34,53,221,209,189,71,70,166,188,110,76,131,122,138,154,90,176,148,57,2,32,89,213,47,207,125,157,87,52,54,192,154,54,21,16,159,155,171,175,221,192,55,147,188,5,143,173,59,245,54,94,1,65],"requestedCertificates":{"certifiers":["03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb"],"types":{"kZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZE=":["Zip","age"]}}}"# + static let policyCertificateResponse = + #"{"version":"0.1","messageType":"certificateResponse","identityKey":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","nonce":"ZcYuVyYvt7LGT0vvaiE9oXvFp8gHY4FxsmJlMS1tXGE=","initialNonce":"36fQZMGI/qb/BJPvo+duptf66NmajaSKzY+nFdekqQKx8HuzckGbNzYeZaLUngtF","yourNonce":"YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh","certificates":[{"type":"kZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZE=","serialNumber":"kpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpI=","subject":"02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","certifier":"03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","revocationOutpoint":"0000000000000000000000000000000000000000000000000000000000000000.0","fields":{"Zip":"8KmA6si+bMmJh2RJed/DOO9FsexeLfHRXCHSJMUTmz2VYOgI4TrHQ4GQH8VzfzbNjNhUEug=","age":"/rrSNdKw7TfgKrUwWI/sFIYyJSc2c0HiK+jE/nz0dy5zaul1Pd0aXcZQn6+Enxk37Z4=","name":"MiS9uFUxPaCux3KnrE6Cg4kko3O7EiyH/gefcemOwVaxb+VkpNdekJF8XNryXtJepnEA"},"signature":"3044022056fc9bf64fa53f8f4aaaaa7c642cf6443d616abea8b0637d04ee748299665fcd02203a1333189d62a31668df783955f9031faa8caa6b9f2cfc4822798dd10ceb1c25","keyring":{"Zip":"IzNeGjHj7EZ2Fx2ExLIz2zhV3lQE6sYhDwd23PCTPB8wKp5suoKsK0DKJ0Wm8dPiyCjDaOrtnFbZz7x4YDj4cLsIVjNclpaXXNFiVOTflaM=","age":"JweQlOfF3/TLY7Zj6/H7pWm9PoH0mG473RA1Hbsevft33G5jaurUx4EuAbtk0DJcEO0hoEtSAYkepyMkOoWQqjwCE9T8lY1HEfPMcojEI+0="}}],"signature":[48,68,2,32,127,35,170,65,228,215,109,175,147,12,176,205,7,52,139,113,32,45,204,31,244,50,24,52,66,43,102,155,73,45,239,102,2,32,77,251,251,32,28,24,21,175,30,51,2,41,89,105,158,15,107,153,111,0,133,45,60,215,71,234,36,41,143,67,38,162]}"# + static let policyGetPath = "/b" + static let policyGetHeaders: [(name: String, value: String)] = [ + ("x-bsv-auth-identity-key", "02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"), + ("x-bsv-auth-nonce", "rFP4AInEyQUDjXTLfc0gkyOH0fxgzJmB9Ln/F5Ow/Qg="), + ("x-bsv-auth-request-id", "WBZAIUmmGV+LHdLdlgWVytR0CvIWuxMT5Xq1DVBEx18="), + ("x-bsv-auth-signature", "3045022100bcc0c3b34372b50742a0929ee519c008ff2d93b507da2725a121ceb20df451be022074fdf6d0f4383c170c4856b1aced314b87b1e61fb874e1c05cd197341c2a942e"), + ("x-bsv-auth-version", "0.1"), + ("x-bsv-auth-your-nonce", "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh"), + ] + static let serverPolicyCertificateType = [UInt8](repeating: 0x91, count: 32) + static let serverPolicyFields = ["Zip", "age"] + static let serverPolicyPlaintext: [(name: String, value: String)] = [ + ("Zip", "73301"), + ("age", "41"), + ("name", "Bob"), + ] +} diff --git a/Tests/BSVAuthTests/BRC103/TypeScriptInteropTests.swift b/Tests/BSVAuthTests/BRC103/TypeScriptInteropTests.swift new file mode 100644 index 0000000..07e0289 --- /dev/null +++ b/Tests/BSVAuthTests/BRC103/TypeScriptInteropTests.swift @@ -0,0 +1,660 @@ +import BSVAuth +import BSVCore +import BSVCrypto +import BSVKeys +import BSVWallet +import Foundation +import Testing + +/// Replays wire messages produced by `@bsv/sdk` 4.1.1 (`TypeScriptAuthVectors`) +/// against this SDK, in both directions of a session. +@Suite("BRC-103/104 TypeScript 4.1.1 interoperability") +struct TypeScriptInteropTests { + // MARK: Swift client, TypeScript `Peer` responder + + @Test("Swift initiator completes the handshake and certificate exchange with a TS peer") + func swiftClientWithTypeScriptPeer() async throws { + let typeScript = try key(3).publicKey + let certifier = try key(11).publicKey + let swiftWallet = ProtoWallet(rootKey: try key(7)) + let client = PeerAuthenticator( + wallet: swiftWallet, randomSource: CountingRandomSource(seed: 0x40)) + + let start = try await client.beginAuthentication(with: typeScript) + let request = try sent(start.actions) + #expect(request.initialNonce == Base64Encoding.encode([UInt8](repeating: 0x41, count: 48))) + + // `Peer.ts:866-875` sends its handshake certificate policy in + // initialResponse; `Peer.ts:1326-1328` holds general messages until it + // is answered. + let initialResponse = try decode(TypeScriptAuthVectors.initialResponse) + let responseActions = try await client.receive(initialResponse) + #expect(responseActions.count == 1) + guard case .certificateRequest(let handshake) = responseActions.first else { + Issue.record("initialResponse requestedCertificates were not surfaced") + return + } + #expect(handshake.peer == typeScript) + #expect(handshake.request.certifiers == [certifier]) + let handshakeType = try CertificateTypeID([UInt8](repeating: 0x51, count: 32)) + #expect(handshake.request.certificateTypes == [handshakeType: [try field("email")]]) + #expect((await client.session(start.sessionID))?.state == .authenticated) + + // An empty response is valid (`AuthMessageValidation.ts:417`, `Peer.ts:1117`). + let empty = try sent([try await client.makeCertificateResponse([], using: start.sessionID)]) + #expect(empty.certificates == []) + #expect(empty.initialNonce == request.initialNonce) + let emptyWire = try String(decoding: AuthMessageCodec.encode(empty), as: UTF8.self) + #expect(emptyWire.contains(#""certificates":[]"#)) + + let requested = try AuthRequestedCertificateSet( + certifiers: [certifier], + certificateTypes: [ + try CertificateTypeID(TypeScriptAuthVectors.certificateType): [ + try field("userName"), try field("profilePhoto"), try field("a&b"), + ] + ]) + let certificateRequest = try sent([ + try await client.makeCertificateRequest(requested, using: start.sessionID) + ]) + // TS requires initialNonce on certificate messages (`AuthMessageValidation.ts:404`). + #expect(certificateRequest.initialNonce == request.initialNonce) + #expect( + certificateRequest.nonce + == Base64Encoding.encode([UInt8](repeating: 0x43, count: 32))) + + // `Peer.ts:1142` signs the certificates in issue order for `fields` and + // reveal order for `keyring`, neither byte-sorted. + let tsResponse = try decode(TypeScriptAuthVectors.certificateResponse) + let responseResult = try await client.receive(tsResponse) + guard case .certificateResponse(let received) = responseResult.first else { + Issue.record("missing certificate response") + return + } + #expect(received.requested == requested) + let validated = try await AuthCertificateExchange.validate( + received.certificates, from: typeScript, requested: requested, using: swiftWallet) + #expect(validated.count == 1) + var expected: [CertificateFieldName: String] = [:] + for item in TypeScriptAuthVectors.certificateFields { + expected[try field(item.name)] = item.value + } + #expect(validated.first?.disclosedFields == expected) + + // A wider request: `validate` needs every type and field, while + // `validateSubset` accepts what was disclosed, as + // `validateCertificates.ts:23-29` does. + let wider = try AuthRequestedCertificateSet( + certifiers: [certifier], + certificateTypes: [ + try CertificateTypeID(TypeScriptAuthVectors.certificateType): [ + try field("userName"), try field("profilePhoto"), try field("a&b"), + try field("email"), + ], + try CertificateTypeID([UInt8](repeating: 0x6a, count: 32)): [try field("age")], + ]) + let log = AuthLogLines() + await log.record { + await #expect(throws: AuthError.certificateValidationFailed) { + try await AuthCertificateExchange.validate( + received.certificates, from: typeScript, requested: wider, using: swiftWallet) + } + } + #expect(log.lines.first?.contains("does not reveal exactly the requested fields") == true) + let subset = try await AuthCertificateExchange.validateSubset( + received.certificates, from: typeScript, requested: wider, using: swiftWallet) + #expect(subset.first?.disclosedFields == expected) + // No certificates is a failure, as `validateCertificates.ts:74` has it. + await #expect(throws: AuthError.certificateValidationFailed) { + try await AuthCertificateExchange.validateSubset( + [], from: typeScript, requested: wider, using: swiftWallet) + } + let narrower = try AuthRequestedCertificateSet( + certifiers: [certifier], + certificateTypes: [ + try CertificateTypeID(TypeScriptAuthVectors.certificateType): [try field("userName")] + ]) + await #expect(throws: AuthError.certificateValidationFailed) { + try await AuthCertificateExchange.validateSubset( + received.certificates, from: typeScript, requested: narrower, using: swiftWallet) + } + + // `Peer.ts:453` signs the policy in insertion order: 0x02… before 0x01…. + let tsRequest = try decode(TypeScriptAuthVectors.certificateRequest) + let requestResult = try await client.receive(tsRequest) + guard case .certificateRequest(let peerRequest) = requestResult.first else { + Issue.record("missing certificate request") + return + } + #expect( + peerRequest.request.certificateTypes == [ + try CertificateTypeID([UInt8](repeating: 0x02, count: 32)): [ + try field("name"), try field("email"), + ], + try CertificateTypeID([UInt8](repeating: 0x01, count: 32)): [try field("x")], + ]) + } + + @Test("a TS certificate message with the wrong initialNonce is rejected") + func certificateInitialNonceBinding() async throws { + let client = PeerAuthenticator( + wallet: ProtoWallet(rootKey: try key(7)), randomSource: CountingRandomSource(seed: 0x40)) + let start = try await client.beginAuthentication(with: try key(3).publicKey) + _ = try await client.receive(try decode(TypeScriptAuthVectors.initialResponse)) + _ = try await client.makeCertificateResponse([], using: start.sessionID) + + let tsInitialNonce = try #require( + try decode(TypeScriptAuthVectors.initialResponse).initialNonce) + let wrong = Base64Encoding.encode([UInt8](repeating: 0x7e, count: 48)) + let tampered = TypeScriptAuthVectors.certificateRequest.replacingOccurrences( + of: #""initialNonce":"\#(tsInitialNonce)""#, with: #""initialNonce":"\#(wrong)""#) + #expect(tampered != TypeScriptAuthVectors.certificateRequest) + await #expect(throws: AuthError.invalidNonce) { + try await client.receive(try decode(tampered)) + } + + let missing = TypeScriptAuthVectors.certificateRequest.replacingOccurrences( + of: #""initialNonce":"\#(tsInitialNonce)","#, with: "") + #expect(throws: AuthError.self) { try decode(missing) } + } + + @Test("a TS peer answers a Swift handshake policy with certificates in initialResponse") + func handshakeCertificatesInInitialResponse() async throws { + let typeScript = try key(3).publicKey + let certifier = try key(11).publicKey + let swiftWallet = ProtoWallet(rootKey: try key(7)) + let type = try CertificateTypeID(TypeScriptAuthVectors.handshakeCertificateType) + let requested = try AuthRequestedCertificateSet( + certifiers: [certifier], + certificateTypes: [type: try TypeScriptAuthVectors.handshakeRequestedFields.map(field)]) + let client = PeerAuthenticator( + wallet: swiftWallet, randomSource: CountingRandomSource(seed: 0x40)) + let start = try await client.beginAuthentication(with: typeScript, requesting: requested) + let initialRequest = try sent(start.actions) + #expect(initialRequest.requestedCertificates == requested) + #expect(initialRequest.initialNonce == Base64Encoding.encode([UInt8](repeating: 0x41, count: 48))) + #expect(try decode(String(decoding: AuthMessageCodec.encode(initialRequest), as: UTF8.self)) == initialRequest) + + // `Peer.ts:960-982`: the initiator validates initialResponse certificates + // against its own policy. + let actions = try await client.receive( + try decode(TypeScriptAuthVectors.initialResponseWithCertificates)) + #expect(actions.count == 1) + guard case .certificateResponse(let received) = actions.first else { + Issue.record("initialResponse certificates were not surfaced") + return + } + #expect(received.sessionID == start.sessionID) + #expect(received.peer == typeScript) + #expect(received.requested == requested) + #expect((await client.session(start.sessionID))?.state == .authenticated) + let validated = try await AuthCertificateExchange.validate( + received.certificates, from: typeScript, requested: requested, using: swiftWallet) + var expected: [CertificateFieldName: String] = [:] + for item in TypeScriptAuthVectors.handshakeFields + where TypeScriptAuthVectors.handshakeRequestedFields.contains(item.name) { + expected[try field(item.name)] = item.value + } + #expect(validated.first?.disclosedFields == expected) + + // The policy was answered, so a later certificate request may be sent. + _ = try await client.makeCertificateRequest(requested, using: start.sessionID) + } + + @Test("initialResponse certificates are ignored unless requested and must match the policy") + func handshakeCertificatesPolicy() async throws { + let typeScript = try key(3).publicKey + let vector = try decode(TypeScriptAuthVectors.initialResponseWithCertificates) + + // Not requested: ignored, as `Peer.ts:960-967` does. + let plain = PeerAuthenticator( + wallet: ProtoWallet(rootKey: try key(7)), randomSource: CountingRandomSource(seed: 0x40)) + let plainStart = try await plain.beginAuthentication(with: typeScript) + #expect(try await plain.receive(vector).isEmpty) + #expect((await plain.session(plainStart.sessionID))?.state == .authenticated) + + // A narrower policy than the certificates reveal is refused before the + // session changes. + let narrow = try AuthRequestedCertificateSet( + certifiers: [try key(11).publicKey], + certificateTypes: [ + try CertificateTypeID(TypeScriptAuthVectors.handshakeCertificateType): [ + try field("Zip") + ] + ]) + let strict = PeerAuthenticator( + wallet: ProtoWallet(rootKey: try key(7)), randomSource: CountingRandomSource(seed: 0x40)) + let strictStart = try await strict.beginAuthentication(with: typeScript, requesting: narrow) + await #expect(throws: AuthError.self) { try await strict.receive(vector) } + #expect((await strict.session(strictStart.sessionID))?.state == .challengeSent) + } + + @Test("a TS certificateRequest with no certifiers authenticates and asks for nothing") + func emptyCertifierRequest() async throws { + let server = PeerAuthenticator( + wallet: ProtoWallet(rootKey: try key(7)), randomSource: CountingRandomSource(seed: 0x60)) + let initialRequest = try decode(TypeScriptAuthVectors.emptyRequestInitialRequest) + // `Peer.ts:644-650` always sends a policy; this one asks for nothing. + #expect(initialRequest.requestedCertificates?.certifiers == []) + let actions = try await server.receive(initialRequest) + #expect(actions.count == 1) + let response = try sent(actions) + #expect(response.initialNonce == Base64Encoding.encode([UInt8](repeating: 0x61, count: 48))) + + let request = try decode(TypeScriptAuthVectors.emptyCertificateRequest) + #expect(request.requestedCertificates?.certifiers == []) + #expect(request.requestedCertificates?.certificateTypes == [:]) + // `Peer.ts:1085-1119` verifies it and authenticates the sender, with no callback. + #expect(try await server.receive(request).isEmpty) + + // A replay is still refused. + await #expect(throws: AuthError.self) { try await server.receive(request) } + } + + @Test("Swift sends a certificateRequest with no certifiers without awaiting an answer") + func swiftEmptyCertifierRequest() async throws { + let client = PeerAuthenticator( + wallet: ProtoWallet(rootKey: try key(7)), randomSource: CountingRandomSource(seed: 0x40)) + let start = try await client.beginAuthentication(with: try key(3).publicKey) + _ = try await client.receive(try decode(TypeScriptAuthVectors.initialResponse)) + _ = try await client.makeCertificateResponse([], using: start.sessionID) + let empty = try AuthRequestedCertificateSet(certifiers: [], certificateTypes: [:]) + let message = try sent([try await client.makeCertificateRequest(empty, using: start.sessionID)]) + let wire = try String(decoding: AuthMessageCodec.encode(message), as: UTF8.self) + #expect(wire.contains(#""requestedCertificates":{"certifiers":[],"types":{}}"#)) + // Nothing is pending, so another request may follow. + _ = try await client.makeCertificateRequest(empty, using: start.sessionID) + } + + @Test("a TS AuthFetch client answers a Swift server's certificate policy") + func serverPolicyAnsweredByAuthFetch() async throws { + let typeScript = try key(3).publicKey + let type = try CertificateTypeID(TypeScriptAuthVectors.serverPolicyCertificateType) + let policy = try AuthRequestedCertificateSet( + certifiers: [try key(11).publicKey], + certificateTypes: [type: try TypeScriptAuthVectors.serverPolicyFields.map(field)]) + let serverWallet = ProtoWallet(rootKey: try key(7)) + let server = PeerAuthenticator( + wallet: serverWallet, randomSource: CountingRandomSource(seed: 0x60), + certificatesToRequest: policy) + + // `Peer.ts:867-876`: the responder's policy travels in initialResponse. + let actions = try await server.receive(try decode(TypeScriptAuthVectors.policyInitialRequest)) + #expect(actions.count == 1) + let initialResponse = try sent(actions) + #expect(initialResponse.requestedCertificates == policy) + #expect(initialResponse == (try decode(TypeScriptAuthVectors.policyInitialResponse))) + + // `AuthFetch` answered it on its own (`clients/AuthFetch.ts:496-511`). + let answer = try await server.receive( + try decode(TypeScriptAuthVectors.policyCertificateResponse)) + #expect(answer.count == 1) + guard case .certificateResponse(let received) = answer.first else { + Issue.record("the certificateResponse was not surfaced") + return + } + #expect(received.peer == typeScript) + #expect(received.requested == policy) + let validated = try await AuthCertificateExchange.validate( + received.certificates, from: typeScript, requested: policy, using: serverWallet) + var expected: [CertificateFieldName: String] = [:] + for item in TypeScriptAuthVectors.serverPolicyPlaintext + where TypeScriptAuthVectors.serverPolicyFields.contains(item.name) { + expected[try field(item.name)] = item.value + } + #expect(validated.first?.disclosedFields == expected) + + // Its next request is delivered as usual. + let frame = try BRC104HTTPRequestFrame( + method: "GET", path: TypeScriptAuthVectors.policyGetPath, + headers: TypeScriptAuthVectors.policyGetHeaders.map { + BRC104Header(name: $0.name, value: $0.value) + }) + let delivered = try await server.receive(try BRC104HTTPFrameCodec.decodeRequest(frame)) + guard case .deliver(let message) = delivered.first else { + Issue.record("the GET was not delivered") + return + } + #expect(try BRC104Codec.decodeRequest(message.payload).path == "/b") + #expect((await server.session(message.sessionID))?.state == .authenticated) + + // A second answer to the same policy is not expected. + await #expect(throws: AuthError.self) { + try await server.receive(try decode(TypeScriptAuthVectors.policyCertificateResponse)) + } + } + + // MARK: TypeScript `AuthFetch` client, Swift server + + @Test("Swift server answers a TS AuthFetch handshake and verifies its GET request") + func typeScriptAuthFetchWithSwiftServer() async throws { + let server = PeerAuthenticator( + wallet: ProtoWallet(rootKey: try key(7)), randomSource: CountingRandomSource(seed: 0x60)) + + let initialRequest = try decode(TypeScriptAuthVectors.authFetchInitialRequest) + let actions = try await server.receive(initialRequest) + // AuthFetch sends `requestedCertificates: {certifiers: [], types: {}}`. + #expect(actions.count == 1) + let response = try sent(actions) + // `AuthMessageValidation.ts:394` requires exactly 48 bytes. + let responderNonce = try #require(response.initialNonce) + #expect(responderNonce.utf8.count == 64) + #expect( + try Base64Encoding.decode(responderNonce, maximumDecodedByteCount: 64) + == [UInt8](repeating: 0x61, count: 48)) + #expect(response.yourNonce == initialRequest.initialNonce) + + // `SimplifiedFetchTransport.ts:189-194`: six headers, no message type, + // no body for a GET. + let frame = try BRC104HTTPRequestFrame( + method: TypeScriptAuthVectors.authFetchMethod, + path: TypeScriptAuthVectors.authFetchPath, + headers: TypeScriptAuthVectors.authFetchHeaders.map { + BRC104Header(name: $0.name, value: $0.value) + }, + body: nil) + let general = try BRC104HTTPFrameCodec.decodeRequest(frame) + #expect(general.messageType == .general) + let delivered = try await server.receive(general) + guard case .deliver(let message) = delivered.first else { + Issue.record("missing delivered request") + return + } + let request = try BRC104Codec.decodeRequest(message.payload) + #expect(request.method == "GET") + #expect(request.path == "/a") + #expect(request.body == nil) + #expect((await server.session(message.sessionID))?.state == .authenticated) + + // A transport that hands over an empty array for the absent body signs + // the same -1 (`authMiddlewareHelpers.ts:155-185`). + let emptyFrame = try BRC104HTTPRequestFrame( + method: frame.method, path: frame.path, headers: frame.headers, body: []) + #expect(try BRC104HTTPFrameCodec.decodeRequest(emptyFrame).payload == general.payload) + } + + // MARK: BRC-104 payload vectors + + @Test("request payloads equal AuthFetch.serializeRequest output") + func requestPayloadVectors() throws { + let id = [UInt8](repeating: 0x07, count: 32) + let json = BRC104Header(name: "content-type", value: "application/json") + let cases: [(BRC104Request, String)] = [ + ( + // `AuthFetch.ts:740` sorts signed headers with `localeCompare`. + try BRC104Request( + requestID: id, method: "POST", path: "/h", + headers: [ + .init(name: "x-bsv-zeta", value: "1"), .init(name: "x-bsv-ab", value: "2"), + .init(name: "x-bsv-a-b", value: "3"), .init(name: "x-bsv-a_b", value: "4"), + .init(name: "x-bsv-a.b", value: "5"), .init(name: "x-bsv-upper", value: "6"), + json, + ], + body: Array("{}".utf8)), + TypeScriptAuthVectors.serializedHeaderOrder + ), + ( + try BRC104Request(requestID: id, method: "GET", path: "/a"), + TypeScriptAuthVectors.serializedGetNoBody + ), + ( + try BRC104Request( + requestID: id, method: "POST", path: "/v1/items", headers: [json]), + TypeScriptAuthVectors.serializedPostJsonDefault + ), + ( + try BRC104Request( + requestID: id, method: "POST", path: "/v1/items", headers: [json], body: []), + TypeScriptAuthVectors.serializedPostEmptyString + ), + ( + try BRC104Request( + requestID: id, method: "POST", path: "/v1/items", query: "?x=1", + headers: [.init(name: "content-type", value: "application/json ; charset=utf-8")], + body: Array(#"{"a":1}"#.utf8)), + TypeScriptAuthVectors.serializedContentTypeSpaces + ), + ( + try BRC104Request( + requestID: id, method: "POST", path: "/upload", + headers: [ + .init(name: "content-type", value: "multipart/form-data; boundary=abc123") + ], + body: Array("part".utf8)), + TypeScriptAuthVectors.serializedMultipart + ), + ] + for (request, hex) in cases { + #expect(Hex.encode(try BRC104Codec.encode(request)) == hex) + } + } + + @Test("bodyless responses sign -1 whether the body is nil or empty") + func emptyResponseBodies() throws { + // `SimplifiedFetchTransport.ts:314-321` and + // `auth-express-middleware/src/index.ts:2112-2117`. + let id = [UInt8](repeating: 0x07, count: 32) + let minusOne = [UInt8](repeating: 0xff, count: 9) + for body in [nil, [UInt8]()] as [[UInt8]?] { + let noContent = try BRC104Response(requestID: id, status: 204, body: body) + #expect(try BRC104Codec.encode(noContent) == id + [0xcc, 0x00] + minusOne) + let notFound = try BRC104Response(requestID: id, status: 404, body: body) + #expect(try BRC104Codec.encode(notFound) == id + [0xfd, 0x94, 0x01, 0x00] + minusOne) + } + } + + @Test("default limits accept TS-sized messages and payment headers") + func typeScriptLimits() throws { + // `AuthMessageValidation.ts:8-14`, `SimplifiedFetchTransport.ts:25-28`, + // `SimplifiedFetchTransport.ts:655-661`, `clients/AuthFetch.ts:147`. + #expect(AuthLimits.standard.maximumJSONBytes == 16 << 20) + #expect(AuthLimits.standard.maximumPayloadBytes == (16 << 20) + (512 << 10)) + #expect(AuthLimits.standard.maximumCertificateCount == 100) + #expect(BRC104Limits.standard.maximumHeaders == 512) + #expect(BRC104Limits.standard.maximumHeaderValueBytes == 32 << 10) + + let id = [UInt8](repeating: 0x07, count: 32) + let payment = String(repeating: "A", count: 200 << 10) + let request = try BRC104Request( + requestID: id, method: "POST", path: "/pay", + headers: [.init(name: "x-bsv-payment", value: payment)]) + #expect(request.headers.first?.value == payment) + #expect(throws: BRC104Error.invalidHeader) { + try BRC104Request( + requestID: id, method: "POST", path: "/pay", + headers: [.init(name: "x-bsv-other", value: String(repeating: "A", count: 33 << 10))]) + } + #expect(throws: BRC104Error.invalidHeader) { + try BRC104Response( + requestID: id, status: 200, + headers: [.init(name: "x-bsv-payment", value: payment)]) + } + } + + // MARK: Certificate JSON preimage + + @Test("Foundation sortedKeys order is not UTF-8 byte order on this platform") + func foundationSortedKeysOrder() throws { + // The old encoder wrote the wire JSON with `.sortedKeys` but signed + // byte-sorted text. Two base64 type IDs that start "Z2dn" (0x67…) and + // "aWlp" (0x69…) sort differently under the two rules. + let upper = Base64Encoding.encode([UInt8](repeating: 0x67, count: 32)) + let lower = Base64Encoding.encode([UInt8](repeating: 0x69, count: 32)) + #expect(Array(upper.utf8).lexicographicallyPrecedes(Array(lower.utf8))) + let data = try JSONSerialization.data( + withJSONObject: [upper: 1, lower: 2], options: [.sortedKeys]) + let text = String(decoding: data, as: UTF8.self) + let upperIndex = try #require(text.range(of: upper)).lowerBound + let lowerIndex = try #require(text.range(of: lower)).lowerBound + #expect(lowerIndex < upperIndex, "Foundation sortedKeys: \(text)") + + // The encoder now writes exactly the bytes it signs. + let requested = try AuthRequestedCertificateSet( + certifiers: [try key(11).publicKey], + certificateTypes: [ + try CertificateTypeID([UInt8](repeating: 0x67, count: 32)): [try field("Zip")], + try CertificateTypeID([UInt8](repeating: 0x69, count: 32)): [try field("age")], + ]) + let message = AuthMessage( + messageType: .certificateRequest, identityKey: try key(7).publicKey, + nonce: Base64Encoding.encode([UInt8](repeating: 1, count: 32)), + initialNonce: Base64Encoding.encode([UInt8](repeating: 2, count: 48)), + yourNonce: Base64Encoding.encode([UInt8](repeating: 3, count: 48)), + signature: [0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01], + requestedCertificates: requested) + let wire = String(decoding: try AuthMessageCodec.encode(message), as: UTF8.self) + let signed = String( + decoding: try AuthMessageCodec.certificateRequestSigningBytes(requested, limits: .standard), + as: UTF8.self) + #expect(wire.contains(#""requestedCertificates":\#(signed)"#)) + #expect(signed.range(of: upper)!.lowerBound < signed.range(of: lower)!.lowerBound) + #expect(try AuthMessageCodec.decode(Array(wire.utf8)) == message) + } + + @Test("certificate JSON escapes exactly as JSON.stringify does") + func certificateJSONEscaping() throws { + let requested = try AuthRequestedCertificateSet( + certifiers: [try key(11).publicKey], + certificateTypes: [ + try CertificateTypeID([UInt8](repeating: 0x01, count: 32)): [ + try field("R&D"), try field("a\u{2028}"), try field("q\"\\\t\u{01}"), + ] + ]) + let signed = String( + decoding: try AuthMessageCodec.certificateRequestSigningBytes(requested, limits: .standard), + as: UTF8.self) + #expect(signed.hasSuffix(#":["R&D","a\#u{2028}","q\"\\\t\u0001"]}}"#)) + } + + // MARK: Swift messages for a TypeScript verifier + + /// Writes the messages this SDK sends in the two vector sessions, for the + /// verifier in `Documentation/Compatibility/TypeScriptAuthVectors.md`, + /// which feeds them to a live `@bsv/sdk` `Peer` and `AuthFetch`. Runs only + /// when `BSV_TS_INTEROP_DUMP` names the output file. + @Test("writes Swift messages for the TypeScript verifier") + func swiftMessagesForTypeScript() async throws { + guard let path = ProcessInfo.processInfo.environment["BSV_TS_INTEROP_DUMP"] else { return } + var output: [String: Any] = [:] + + // Swift server answering the AuthFetch session. + let server = PeerAuthenticator( + wallet: ProtoWallet(rootKey: try key(7)), randomSource: CountingRandomSource(seed: 0x60)) + let initialResponse = try sent( + try await server.receive(try decode(TypeScriptAuthVectors.authFetchInitialRequest))) + output["serverInitialResponse"] = try wire(initialResponse) + let frame = try BRC104HTTPRequestFrame( + method: TypeScriptAuthVectors.authFetchMethod, + path: TypeScriptAuthVectors.authFetchPath, + headers: TypeScriptAuthVectors.authFetchHeaders.map { + BRC104Header(name: $0.name, value: $0.value) + }) + guard + case .deliver(let delivered) = try await server.receive( + try BRC104HTTPFrameCodec.decodeRequest(frame) + ).first + else { throw AuthError.invalidMessage } + let request = try BRC104Codec.decodeRequest(delivered.payload) + let payload = try BRC104Codec.encode( + try BRC104Response(requestID: request.requestID, status: 204, body: [])) + let general = try sent([ + try await server.makeGeneralMessage(payload: payload, using: delivered.sessionID) + ]) + let responseFrame = try BRC104HTTPFrameCodec.encodeResponse(general) + var headers: [String: String] = [:] + for header in responseFrame.headers { headers[header.name] = header.value } + output["serverResponse"] = ["status": responseFrame.status, "headers": headers] + + // Swift client in the `Peer` session: answers the handshake policy with + // a certificate, then requests the TypeScript certificate and sends a + // general message. `Zip` and `age` sort differently in `localeCompare` + // order, which TypeScript verifies the certificate in (`Certificate.ts:290`). + let typeScript = try key(3).publicKey + let certifierKey = try key(11) + let swiftWallet = ProtoWallet(rootKey: try key(7)) + let client = PeerAuthenticator( + wallet: swiftWallet, randomSource: CountingRandomSource(seed: 0x40)) + let start = try await client.beginAuthentication(with: typeScript) + guard + case .certificateRequest(let handshake) = try await client.receive( + try decode(TypeScriptAuthVectors.initialResponse) + ).first + else { throw AuthError.invalidMessage } + let handshakeType = try CertificateTypeID([UInt8](repeating: 0x51, count: 32)) + let master = try await CertificateEngine.issue( + type: handshakeType, + serialNumber: try CertificateSerialNumber([UInt8](repeating: 0x52, count: 32)), + subject: .publicKey(try key(7).publicKey), + plaintextFields: [ + try field("email"): "swift@example.test", try field("Zip"): "R&D <1>", + try field("age"): "30", try field("a&b"): "\u{2028}", + ], + using: ProtoWallet(rootKey: certifierKey)) + let revealed = try await CertificateEngine.project( + master, fields: try #require(handshake.request.certificateTypes[handshakeType]), + to: typeScript, using: swiftWallet) + output["clientCertificateResponse"] = try wire( + try sent([try await client.makeCertificateResponse([revealed], using: start.sessionID)])) + let requested = try AuthRequestedCertificateSet( + certifiers: [certifierKey.publicKey], + certificateTypes: [ + try CertificateTypeID(TypeScriptAuthVectors.certificateType): [ + try field("userName"), try field("profilePhoto"), try field("a&b"), + ], + try CertificateTypeID([UInt8](repeating: 0x67, count: 32)): [try field("Zip")], + try CertificateTypeID([UInt8](repeating: 0x69, count: 32)): [try field("age")], + ]) + output["clientCertificateRequest"] = try wire( + try sent([try await client.makeCertificateRequest(requested, using: start.sessionID)])) + output["clientGeneral"] = try wire( + try sent([ + try await client.makeGeneralMessage( + payload: Array("hello from swift".utf8), using: start.sessionID) + ])) + + let data = try JSONSerialization.data(withJSONObject: output, options: [.sortedKeys]) + try data.write(to: URL(fileURLWithPath: path)) + } + + private func wire(_ message: AuthMessage) throws -> String { + String(decoding: try AuthMessageCodec.encode(message), as: UTF8.self) + } + + // MARK: Helpers + + private func decode(_ text: String) throws -> AuthMessage { + try AuthMessageCodec.decode(Array(text.utf8)) + } + + private func key(_ scalar: UInt8) throws -> PrivateKey { + var bytes = [UInt8](repeating: 0, count: 32) + bytes[31] = scalar + return try PrivateKey(bytes) + } + + private func field(_ name: String) throws -> CertificateFieldName { + try CertificateFieldName(name) + } + + private func sent(_ actions: [AuthPeerAction]) throws -> AuthMessage { + guard case .send(let message) = actions.first else { throw AuthError.invalidMessage } + return message + } +} + +/// Call `k` (from 1) returns `count` bytes of `seed + k`, matching the inputs +/// the TypeScript generator assumed for the Swift peer. +private final class CountingRandomSource: SecureRandomSource, @unchecked Sendable { + private let seed: UInt8 + private let lock = NSLock() + private var calls: UInt8 = 0 + + init(seed: UInt8) { self.seed = seed } + + func randomBytes(count: Int) throws -> [UInt8] { + lock.lock() + defer { lock.unlock() } + calls += 1 + return [UInt8](repeating: seed &+ calls, count: count) + } +} diff --git a/Tests/BSVAuthTests/BRC104/BRC104ErrorDescriptionTests.swift b/Tests/BSVAuthTests/BRC104/BRC104ErrorDescriptionTests.swift new file mode 100644 index 0000000..d4f262a --- /dev/null +++ b/Tests/BSVAuthTests/BRC104/BRC104ErrorDescriptionTests.swift @@ -0,0 +1,67 @@ +import BSVAuth +import Foundation +import Testing + +/// What an app shows when authentication fails. The sentences hold whether +/// the app is the client or the server. +@Suite("BRC-103/104 error descriptions") +struct BRC104ErrorDescriptionTests { + @Test("payload errors say what is wrong with the request or response") + func payloadSentences() { + #expect( + BRC104Error.invalidStatus.localizedDescription + == "The response status is not one that authenticated HTTP allows.") + #expect( + BRC104Error.invalidMethod.localizedDescription + == "The request method is not one that authenticated HTTP allows.") + #expect( + BRC104Error.invalidPath.localizedDescription + == "The request address is not valid or is too long.") + #expect(String(reflecting: BRC104Error.invalidPath).hasSuffix("invalidPath")) + } + + @Test("framing errors say what is wrong with the headers") + func framingSentences() { + #expect( + BRC104HTTPFramingError.invalidAuthenticationHeader.localizedDescription + == "The authentication headers are not valid.") + #expect( + BRC104HTTPFramingError.missingAuthenticationHeader.localizedDescription + == "The request or response is missing authentication headers.") + #expect( + BRC104HTTPFramingError.resourceLimit.localizedDescription + == "The request or response is too large.") + #expect( + BRC104HTTPFramingError.invalidFrame.localizedDescription + == "The request or response is not one that authenticated HTTP allows.") + } + + @Test("authentication and certificate errors name no side") + func roleNeutralSentences() { + let all: [AuthError] = [ + .invalidMessage, .invalidNonce, .invalidSignature, .replay, .sessionNotFound, + .unexpectedMessage, .peerMismatch, .notAuthenticated, .certificateExchangeUnavailable, + .invalidCertificateRequest, .certificateValidationFailed, .resourceLimit, + .handshakeTimedOut, .randomGenerationFailed, + ] + let framing: [BRC104HTTPFramingError] = [ + .invalidFrame, .invalidAuthenticationHeader, .duplicateAuthenticationHeader, + .missingAuthenticationHeader, .unknownAuthenticationHeader, + .certificateExchangeUnavailable, .requestIDMismatch, .resourceLimit, + ] + let text = all.map(\.localizedDescription) + framing.map(\.localizedDescription) + for sentence in text { + #expect(!sentence.lowercased().contains("server"), "\(sentence)") + #expect(!sentence.lowercased().contains("storage"), "\(sentence)") + } + #expect( + AuthError.certificateValidationFailed.localizedDescription + == "The certificates do not match what was requested or could not be verified.") + #expect( + AuthError.notAuthenticated.localizedDescription + == "The connection has not been authenticated yet.") + #expect( + CertificateFieldNameError.nonASCII.localizedDescription + == "Certificate field names must use only plain ASCII letters, digits, spaces and symbols.") + } +} diff --git a/Tests/BSVAuthTests/BRC104/BRC104HTTPFramingTests.swift b/Tests/BSVAuthTests/BRC104/BRC104HTTPFramingTests.swift index 73bae48..df64ea5 100644 --- a/Tests/BSVAuthTests/BRC104/BRC104HTTPFramingTests.swift +++ b/Tests/BSVAuthTests/BRC104/BRC104HTTPFramingTests.swift @@ -93,7 +93,9 @@ struct BRC104HTTPFramingTests { .init(name: BRC104HTTPHeaderName.requestedCertificates, value: "{}") ] ) - #expect(throws: BRC104HTTPFramingError.certificateExchangeUnavailable) { + // `{}` is not a requested set; `@bsv/sdk` rejects it too + // (`AuthMessageValidation.ts:134-136`). + #expect(throws: BRC104HTTPFramingError.invalidAuthenticationHeader) { try BRC104HTTPFrameCodec.decodeRequest(certificateRequest) } @@ -104,7 +106,7 @@ struct BRC104HTTPFramingTests { .init(name: BRC104HTTPHeaderName.requestedCertificates, value: "{}") ] ) - #expect(throws: BRC104HTTPFramingError.certificateExchangeUnavailable) { + #expect(throws: BRC104HTTPFramingError.invalidAuthenticationHeader) { try BRC104HTTPFrameCodec.decodeResponse( responseCertificateRequest, expectedRequestID: fixture.requestID @@ -169,18 +171,178 @@ struct BRC104HTTPFramingTests { } } + @Test("x-bsv-auth-requested-certificates carries a requested set on general messages") + func requestedCertificatesHeader() async throws { + let fixture = try await makeHTTPFixture() + let certifier = try httpPrivateKey(11).publicKey + let type = try CertificateTypeID([UInt8](repeating: 0x05, count: 32)) + let requested = try AuthRequestedCertificateSet( + certifiers: [certifier], certificateTypes: [type: [try CertificateFieldName("Zip")]]) + let request = withRequestedCertificates(fixture.requestMessage, requested) + let response = withRequestedCertificates(fixture.responseMessage, requested) + // The middleware writes the set as JSON (`index.ts:985-988`) and the + // client reads it back with `JSON.parse` (`SimplifiedFetchTransport.ts:234-258`). + let expected = + #"{"certifiers":[""# + Hex.encode(certifier.compressedBytes) + + #""],"types":{""# + Base64Encoding.encode(type.bytes) + #"":["Zip"]}}"# + + let requestFrame = try BRC104HTTPFrameCodec.encodeRequest(request) + #expect(header(BRC104HTTPHeaderName.requestedCertificates, in: requestFrame.headers) == expected) + #expect(try BRC104HTTPFrameCodec.decodeRequest(requestFrame) == request) + let encodedResponse = try BRC104HTTPFrameCodec.encodeResponse(response) + #expect(header(BRC104HTTPHeaderName.requestedCertificates, in: encodedResponse.headers) == expected) + #expect( + try BRC104HTTPFrameCodec.decodeResponse( + encodedResponse, expectedRequestID: fixture.requestID) == response) + #expect( + header( + BRC104HTTPHeaderName.requestedCertificates, + in: try BRC104HTTPFrameCodec.encodeRequest(fixture.requestMessage).headers) == nil) + + // The set `@bsv/sdk` sends when it asks for nothing. + let plain = try BRC104HTTPFrameCodec.encodeResponse(fixture.responseMessage) + let empty = try responseFrame( + basedOn: plain, + headers: plain.headers + [ + .init(name: "X-BSV-Auth-Requested-Certificates", value: #"{"certifiers":[],"types":{}}"#) + ]) + let decoded = try BRC104HTTPFrameCodec.decodeResponse( + empty, expectedRequestID: fixture.requestID) + #expect(decoded.requestedCertificates?.certifiers.isEmpty == true) + #expect(decoded.requestedCertificates?.certificateTypes.isEmpty == true) + + for malformed in ["not json", "[]", #"{"certifiers":["zz"],"types":{}}"#, #"{"certifiers":[]}"#] { + let frame = try responseFrame( + basedOn: plain, + headers: plain.headers + [ + .init(name: BRC104HTTPHeaderName.requestedCertificates, value: malformed) + ]) + #expect(throws: BRC104HTTPFramingError.invalidAuthenticationHeader) { + try BRC104HTTPFrameCodec.decodeResponse(frame, expectedRequestID: fixture.requestID) + } + } + // `MAX_REQUESTED_CERTIFICATES_HEADER_BYTES` (`SimplifiedFetchTransport.ts:30`). + let oversized = #"{"certifiers":[],"types":{}}"# + + String(repeating: " ", count: (256 << 10) - 27) + #expect(oversized.utf8.count == (256 << 10) + 1) + #expect(throws: BRC104HTTPFramingError.resourceLimit) { + try BRC104HTTPFrameCodec.decodeResponse( + try responseFrame( + basedOn: plain, + headers: plain.headers + [ + .init(name: BRC104HTTPHeaderName.requestedCertificates, value: oversized) + ]), + expectedRequestID: fixture.requestID) + } + } + + @Test("a general message with a requested set is delivered and the set ignored") + func requestedCertificatesOnGeneralMessagesAreIgnored() async throws { + let client = PeerAuthenticator(wallet: ProtoWallet(rootKey: try httpPrivateKey(3))) + let server = PeerAuthenticator(wallet: ProtoWallet(rootKey: try httpPrivateKey(7))) + let start = try await client.beginAuthentication(with: try httpPrivateKey(7).publicKey) + _ = try await client.receive( + try sentHTTPMessage(try await server.receive(try sentHTTPMessage(start.actions)))) + let request = try BRC104Request( + requestID: [UInt8](repeating: 9, count: 32), method: "GET", path: "/") + let message = try sentHTTPMessage([ + try await client.makeGeneralMessage( + payload: try BRC104Codec.encode(request), using: start.sessionID) + ]) + let requested = try AuthRequestedCertificateSet( + certifiers: [try httpPrivateKey(11).publicKey], + certificateTypes: [ + try CertificateTypeID([UInt8](repeating: 0x05, count: 32)): [ + try CertificateFieldName("name") + ] + ]) + // `Peer.processGeneralMessage` does not act on the header's set + // (`Peer.ts:1272-1340`); it is not covered by the signature. + let actions = try await server.receive( + try BRC104HTTPFrameCodec.decodeRequest( + try BRC104HTTPFrameCodec.encodeRequest(withRequestedCertificates(message, requested)))) + #expect(actions.count == 1) + guard case .deliver(let delivered) = actions.first else { + Issue.record("general message was not delivered") + return + } + #expect(try BRC104Codec.decodeRequest(delivered.payload) == request) + } + + @Test("frames refuse statuses, methods and request targets that @bsv/sdk rejects") + func typeScriptFrameLimits() async throws { + let fixture = try await makeHTTPFixture() + for status in [100, 199, 600] { + #expect(throws: BRC104HTTPFramingError.invalidFrame) { + try BRC104HTTPResponseFrame(status: status) + } + } + #expect(try BRC104HTTPResponseFrame(status: 200).status == 200) + let frame = try BRC104HTTPFrameCodec.encodeRequest(fixture.requestMessage) + for method in ["post", "M1", "G E T"] { + #expect(throws: BRC104HTTPFramingError.invalidFrame) { + try BRC104HTTPRequestFrame(method: method, path: "/", headers: frame.headers) + } + } + let path = "/" + String(repeating: "p", count: 4_095) + let query = "?" + String(repeating: "q", count: 4_096) + #expect(throws: BRC104HTTPFramingError.resourceLimit) { + try BRC104HTTPRequestFrame(method: "GET", path: path, query: query) + } + #expect( + try BRC104HTTPRequestFrame(method: "GET", path: path, query: String(query.dropLast())) + .path == path) + } + + @Test("a framing error keeps the detailed cause in the log") + func detailedCauseIsLogged() async throws { + let fixture = try await makeHTTPFixture() + let message = fixture.requestMessage + let malformed = AuthMessage( + messageType: .general, identityKey: message.identityKey, nonce: message.nonce, + yourNonce: message.yourNonce, payload: [1, 2, 3], signature: message.signature) + let log = AuthLogLines() + await log.record { + #expect(throws: BRC104HTTPFramingError.invalidFrame) { + try BRC104HTTPFrameCodec.encodeRequest(malformed) + } + } + let line = try #require(log.lines.first) + #expect(line.hasPrefix("BRC104HTTPFrameCodec.encodeRequest: BRC104Error: ")) + #expect(line.hasSuffix("reported as BSVAuth.BRC104HTTPFramingError.invalidFrame")) + + let plain = try BRC104HTTPFrameCodec.encodeResponse(fixture.responseMessage) + let headerLog = AuthLogLines() + await headerLog.record { + #expect(throws: BRC104HTTPFramingError.invalidAuthenticationHeader) { + try BRC104HTTPFrameCodec.decodeResponse( + try responseFrame( + basedOn: plain, + headers: plain.headers + [ + .init(name: BRC104HTTPHeaderName.requestedCertificates, value: "[]") + ]), + expectedRequestID: fixture.requestID) + } + } + #expect( + headerLog.lines.first?.hasPrefix( + "BRC104HTTPFrameCodec.parseRequestedCertificates: AuthError: ") == true) + } + + /// The TypeScript `AuthFetch` sends a request frame of up to 16 MiB /// (`MAX_AUTH_HTTP_REQUEST_FRAME_BYTES`) and reads a response body of up to 16 MiB - /// (`DEFAULT_SIMPLIFIED_FETCH_MAX_RESPONSE_BYTES`). A wallet storage reply carrying a 180 KB + /// (`DEFAULT_SIMPLIFIED_FETCH_MAX_RESPONSE_BYTES`) plus 512 KiB of framing + /// (`clients/AuthFetch.ts:147`), which is the default here. A wallet storage reply carrying a 180 KB /// image inscription as JSON numbers was 1,330,479 bytes, and at the old 1 MiB default it was /// refused with `resourceLimit` before it was read. - @Test("payloads over 1 MiB and under 16 MiB are signed, framed and read") + @Test("payloads over 1 MiB and up to the default limit are signed, framed and read") func payloadsOverOneMebibyte() async throws { - #expect(AuthLimits.standard.maximumPayloadBytes == 16 << 20) - #expect(try AuthLimits().maximumPayloadBytes == 16 << 20) - #expect(BRC104Limits.standard.maximumPayloadBytes == 16 << 20) - #expect(try BRC104Limits().maximumPayloadBytes == 16 << 20) - #expect(BRC104HTTPFramingLimits.standard.payloadLimits.maximumPayloadBytes == 16 << 20) + #expect(AuthLimits.standard.maximumPayloadBytes == AuthLimits.defaultPayloadBytes) + #expect(try AuthLimits().maximumPayloadBytes == AuthLimits.defaultPayloadBytes) + #expect(BRC104Limits.standard.maximumPayloadBytes == AuthLimits.defaultPayloadBytes) + #expect(try BRC104Limits().maximumPayloadBytes == AuthLimits.defaultPayloadBytes) + #expect(BRC104HTTPFramingLimits.standard.payloadLimits.maximumPayloadBytes == AuthLimits.defaultPayloadBytes) let requestBody = [UInt8](repeating: 0x5b, count: (1 << 20) + 1) let responseBody = [UInt8](repeating: 0x31, count: 1_330_479) @@ -206,27 +368,29 @@ struct BRC104HTTPFramingTests { #expect(inner.body == responseBody) } - @Test("a response payload of exactly 16 MiB is read and one byte more is refused") - func sixteenMebibyteBoundary() throws { + @Test("a response payload at exactly the default limit is read and one byte more is refused") + func defaultPayloadBoundary() throws { + let limit = AuthLimits.defaultPayloadBytes let requestID = [UInt8](repeating: 9, count: 32) - let empty = try BRC104Codec.encode( - BRC104Response(requestID: requestID, status: 200, body: []) + let oneByte = try BRC104Codec.encode( + BRC104Response(requestID: requestID, status: 200, body: [1]) ) - // The empty body's one-byte length prefix is five bytes for a body this large. - let overhead = empty.count - 1 + 5 + // A one-byte body has a one-byte length prefix, which is five bytes for a + // body this large. (An empty body is written as -1, nine bytes.) + let overhead = oneByte.count - 2 + 5 let largest = try BRC104Response( requestID: requestID, status: 200, - body: [UInt8](repeating: 1, count: (16 << 20) - overhead) + body: [UInt8](repeating: 1, count: limit - overhead) ) let encoded = try BRC104Codec.encode(largest) - #expect(encoded.count == 16 << 20) + #expect(encoded.count == limit) #expect(try BRC104Codec.decodeResponse(encoded) == largest) #expect(throws: BRC104Error.resourceLimit) { try BRC104Codec.encode( BRC104Response( requestID: requestID, status: 200, - body: [UInt8](repeating: 1, count: (16 << 20) - overhead + 1) + body: [UInt8](repeating: 1, count: limit - overhead + 1) ) ) } @@ -235,7 +399,7 @@ struct BRC104HTTPFramingTests { } #expect(throws: BRC104HTTPFramingError.resourceLimit) { try BRC104HTTPResponseFrame( - status: 200, body: [UInt8](repeating: 1, count: (16 << 20) + 1) + status: 200, body: [UInt8](repeating: 1, count: limit + 1) ) } } @@ -351,4 +515,18 @@ private func httpPrivateKey(_ scalar: UInt8) throws -> PrivateKey { return try PrivateKey(bytes) } +private func withRequestedCertificates( + _ message: AuthMessage, _ requested: AuthRequestedCertificateSet +) -> AuthMessage { + AuthMessage( + messageType: message.messageType, identityKey: message.identityKey, + nonce: message.nonce, initialNonce: message.initialNonce, yourNonce: message.yourNonce, + payload: message.payload, signature: message.signature, + requestedCertificates: requested) +} + +private func header(_ name: String, in headers: [BRC104Header]) -> String? { + headers.first { $0.name == name }?.value +} + private func assertHTTPFramingSendable(_ type: T.Type) {} diff --git a/Tests/BSVAuthTests/BRC104/BRC104PayloadTests.swift b/Tests/BSVAuthTests/BRC104/BRC104PayloadTests.swift index 0b4598f..0ad4fc7 100644 --- a/Tests/BSVAuthTests/BRC104/BRC104PayloadTests.swift +++ b/Tests/BSVAuthTests/BRC104/BRC104PayloadTests.swift @@ -93,6 +93,84 @@ struct BRC104PayloadTests { ) } + @Test("refuses statuses, methods and request targets that @bsv/sdk rejects") + func typeScriptRequestLimits() throws { + let requestID = [UInt8](repeating: 4, count: 32) + // `AuthFetch.ts:587-589` rejects an authenticated status outside 200...599. + for status in [100, 101, 199, 600] { + #expect(throws: BRC104Error.invalidStatus) { + try BRC104Response(requestID: requestID, status: status) + } + } + for status in [200, 204, 599] { + #expect(try BRC104Response(requestID: requestID, status: status).status == status) + } + var informational = try BRC104Codec.encode( + try BRC104Response(requestID: requestID, status: 200)) + #expect(informational[32] == 200) + informational[32] = 199 + #expect(throws: BRC104Error.invalidStatus) { + try BRC104Codec.decodeResponse(informational) + } + + // The middleware accepts 1 to 32 uppercase token characters + // (`auth-express-middleware/src/index.ts:2002`). + for method in ["get", "Post", "M1", "", "GET ", String(repeating: "A", count: 33)] { + #expect(throws: BRC104Error.invalidMethod) { + try BRC104Request(requestID: requestID, method: method, path: "/") + } + } + for method in ["GET", "PROPFIND", "M-SEARCH", "!#$%&'*+.^_`|~-", String(repeating: "A", count: 32)] { + #expect(try BRC104Request(requestID: requestID, method: method, path: "/").method == method) + } + + // `originalUrl`, the path and query, is limited to 8192 characters + // (`auth-express-middleware/src/index.ts:2024`). + let path = "/" + String(repeating: "p", count: 4_095) + let exactQuery = "?" + String(repeating: "q", count: 4_095) + #expect( + try BRC104Request(requestID: requestID, method: "GET", path: path, query: exactQuery) + .query == exactQuery) + #expect(throws: BRC104Error.invalidPath) { + try BRC104Request( + requestID: requestID, method: "GET", path: path, query: exactQuery + "q") + } + #expect(throws: BRC104Error.invalidPath) { + try BRC104Request( + requestID: requestID, method: "GET", path: path + String(repeating: "p", count: 4_097)) + } + } + + @Test("refuses header values and names that @bsv/sdk would not sign as given") + func unsignableHeaders() throws { + let requestID = [UInt8](repeating: 4, count: 32) + // `fetch` trims values and reads bytes as Latin-1 + // (`SimplifiedFetchTransport.ts:263-283`). + for value in [" leading", "trailing ", "caf\u{E9}", "\u{1F600}"] { + #expect(throws: BRC104Error.invalidHeader) { + try BRC104Request( + requestID: requestID, method: "GET", path: "/", + headers: [.init(name: "x-bsv-note", value: value)]) + } + #expect(throws: BRC104Error.invalidHeader) { + try BRC104Response( + requestID: requestID, status: 200, + headers: [.init(name: "x-bsv-note", value: value)]) + } + } + #expect( + try BRC104Request( + requestID: requestID, method: "GET", path: "/", + headers: [.init(name: "x-bsv-note", value: "inner space, ~!")] + ).headers.first?.value == "inner space, ~!") + // `@bsv/sdk` signs no name starting with `x-bsv-auth` (`AuthFetch.ts:727`). + #expect(throws: BRC104Error.invalidHeader) { + try BRC104Request( + requestID: requestID, method: "GET", path: "/", + headers: [.init(name: "x-bsv-authority", value: "1")]) + } + } + @Test("response correlation is exact") func responseCorrelation() throws { let requestID = [UInt8](repeating: 1, count: 32) diff --git a/Tests/BSVAuthTests/Certificates/LocaleCompareOrderTests.swift b/Tests/BSVAuthTests/Certificates/LocaleCompareOrderTests.swift new file mode 100644 index 0000000..15d87e6 --- /dev/null +++ b/Tests/BSVAuthTests/Certificates/LocaleCompareOrderTests.swift @@ -0,0 +1,241 @@ +import BSVAuth +import BSVCore +import BSVCrypto +import BSVKeys +import BSVWallet +import Foundation +import Testing + +/// `LocaleCompareOrder` against JavaScript `localeCompare`, and BRC-52 +/// certificate signatures over fields in that order. +/// +/// The expected values were produced by Bun 1.4.4 and Node 22.23.4 (both ICU, +/// locale `en-US`) running `collate-vec.ts` in +/// Documentation/Compatibility/TypeScriptAuthVectors.md; both printed the same +/// results. +@Suite("localeCompare order") +struct LocaleCompareOrderTests { + @Test("printable ASCII sorts as localeCompare does") + func printableASCII() { + let printable = (0x20...0x7E).map { String(UnicodeScalar(UInt8($0))) } + let sorted = printable.sorted(by: LocaleCompareOrder.areInIncreasingOrder) + #expect( + sorted.joined() + == " _-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$0123456789" + + "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ") + #expect(LocaleCompareOrder.asciiOrder.hasSuffix(sorted.joined())) + } + + @Test("every pair of printable ASCII characters sorts as localeCompare does") + func printableASCIIPairs() { + let printable = (0x20...0x7E).map { String(UnicodeScalar(UInt8($0))) } + var pairs: [String] = [] + for first in printable { for second in printable { pairs.append(first + second) } } + #expect(pairs.count == 9_025) + // localeCompare reports no ties among these 9025 strings, so the order is total. + #expect( + sortedDigest(pairs) + == "486638e314651e755e158382de74daec1be1e94d392ff87e70f48006b14bc4f8") + } + + @Test("three-character strings over spaces, punctuation, digits and both cases") + func triples() { + let alphabet = Array(" !-._09aAzZ").map(String.init) + var triples: [String] = [] + for a in alphabet { for b in alphabet { for c in alphabet { triples.append(a + b + c) } } } + #expect(triples.count == 1_331) + #expect( + sortedDigest(triples) + == "a7264e62b832c8d1682eb3222b5dadff4d39138b5c05a7fd517bbc32941eb25f") + } + + @Test("random printable ASCII strings of one to eight characters") + func randomStrings() { + // x = (1103515245 x + 12345) mod 2^31 from x = 1, as in `collate-vec.ts`. + var state: UInt32 = 1 + func next() -> Int { + state = (state &* 1_103_515_245 &+ 12_345) & 0x7FFF_FFFF + return Int(state) + } + var strings: [String] = [] + for _ in 0..<4_000 { + let length = 1 + next() % 8 + var value = "" + for _ in 0..^0"]) + #expect(Set(strings).count == 4_000) + #expect( + sortedDigest(strings) + == "1c2fb4ded5031dfa2cf5cf764b119dcb5477b331e17dd8ce43dc71234585957a") + } + + @Test("field and header names sort as localeCompare does") + func names() { + let names = [ + "Zip", "age", "a_b", "a-b", "ab", "a b", "A", "a", "aB", "Ab", "a1", "a10", "a2", + "x-bsv-a_b", "x-bsv-ab", "x-bsv-a-b", "x-bsv-Z", "x-bsv-z", "email", "Email", + "first_name", "firstName", "first-name", + ] + #expect( + names.sorted(by: LocaleCompareOrder.areInIncreasingOrder) == [ + "a", "A", "a b", "a_b", "a-b", "a1", "a10", "a2", "ab", "aB", "Ab", "age", "email", + "Email", "first_name", "first-name", "firstName", "x-bsv-a_b", "x-bsv-a-b", + "x-bsv-ab", "x-bsv-z", "x-bsv-Z", "Zip", + ]) + #expect(LocaleCompareOrder.compare("age", "Zip") < 0) + #expect(Array("age".utf8).lexicographicallyPrecedes(Array("Zip".utf8)) == false) + } + + @Test("non-ASCII and ignorable characters have a documented total order") + func nonASCII() { + // ICU ignores most C0 controls: `'a\u0001b'.localeCompare('ab') === 0`. + // Such ties fall back to UTF-8 byte order, so the order stays total. + #expect(LocaleCompareOrder.compare("a\u{01}b", "ab") < 0) + #expect(LocaleCompareOrder.compare("ab", "a\u{01}b") > 0) + #expect(LocaleCompareOrder.compare("a\u{AD}b", "abc") < 0) + // Other non-ASCII sorts after ASCII in code point order. ICU puts + // `é` between `e` and `f`; this order does not. + #expect(LocaleCompareOrder.compare("é", "z") > 0) + #expect(LocaleCompareOrder.compare("日本", "é") > 0) + #expect(LocaleCompareOrder.compare("same", "same") == 0) + } + + private func sortedDigest(_ strings: [String]) -> String { + let sorted = strings.sorted(by: LocaleCompareOrder.areInIncreasingOrder) + return Hex.encode(BSVHashing.sha256(Array(sorted.joined(separator: "\n").utf8)).bytes) + } +} + +@Suite("BRC-52 certificate field order") +struct CertificateFieldOrderTests { + @Test("a TS-signed certificate with mixed-case fields verifies") + func typeScriptMixedCaseCertificate() async throws { + let certificate = try Certificate(json: Array(TypeScriptAuthVectors.mixedCaseCertificate.utf8)) + #expect( + Hex.encode(try certificate.localeOrderSigningPreimage(limits: .standard)) + == TypeScriptAuthVectors.mixedCaseCertificatePreimage) + #expect(try await certificate.verifySignatureInEitherFieldOrder(limits: .standard)) + #expect(try await verifies(certificate, over: certificate.localeOrderSigningPreimage(limits: .standard))) + + // Signing the same unsigned certificate gives TypeScript's RFC 6979 signature. + let unsigned = try unsignedCopy(of: certificate) + let resigned = try await unsigned.signedInLocaleOrder( + using: ProtoWallet(rootKey: try key(11)), limits: .standard) + #expect(resigned.signature == certificate.signature) + } + + @Test("issued certificates are signed in localeCompare order") + func issuedMixedCaseCertificate() async throws { + let master = try await CertificateEngine.issue( + type: try CertificateTypeID([UInt8](repeating: 0x21, count: 32)), + subject: .publicKey(try key(7).publicKey), + plaintextFields: [ + try CertificateFieldName("Zip"): "90210", try CertificateFieldName("age"): "30", + try CertificateFieldName("a_b"): "1", try CertificateFieldName("a-b"): "2", + ], + using: ProtoWallet(rootKey: try key(11))) + let certificate = master.certificate + let localeOrder = try certificate.localeOrderSigningPreimage(limits: .standard) + #expect(localeOrder != (try certificate.binary(includingSignature: false))) + #expect(try await verifies(certificate, over: localeOrder)) + #expect(try await certificate.verifySignatureInEitherFieldOrder(limits: .standard)) + } + + @Test("non-ASCII field names are refused at issue and still verify in byte order") + func nonASCIIFieldNames() async throws { + // ICU root collation is not emulated past ASCII (COMP-041), so a + // certificate whose TS signature order could not be predicted is not issued. + let fields = [ + try CertificateFieldName("été"): "summer", try CertificateFieldName("age"): "30", + ] + let log = AuthLogLines() + let error = await log.record { + await #expect(throws: (any Error).self) { + try await CertificateEngine.issue( + type: try CertificateTypeID([UInt8](repeating: 0x24, count: 32)), + subject: .publicKey(try key(7).publicKey), + plaintextFields: fields, + using: ProtoWallet(rootKey: try key(11))) + } + } + #expect( + error?.localizedDescription + == "Certificate field names must use only plain ASCII letters, digits, spaces and symbols.") + #expect(log.lines.contains { $0.contains("field name") }) + + let unsigned = try Certificate( + type: try CertificateTypeID([UInt8](repeating: 0x25, count: 32)), + serialNumber: try CertificateSerialNumber([UInt8](repeating: 0x26, count: 32)), + subject: try key(7).publicKey, + certifier: try key(11).publicKey, + revocationOutpoint: CertificateEngine.disabledRevocationOutpoint, + fields: [ + try CertificateFieldName("été"): try CertificateCiphertext([1]), + try CertificateFieldName("age"): try CertificateCiphertext([2]), + ]) + await #expect(throws: (any Error).self) { + try await unsigned.signedInLocaleOrder( + using: ProtoWallet(rootKey: try key(11)), limits: .standard) + } + // A Go-style byte-order signature over such names is still accepted. + let byteOrder = try await unsigned.signed(using: ProtoWallet(rootKey: try key(11))) + #expect(try await byteOrder.verifySignatureInEitherFieldOrder(limits: .standard)) + } + + @Test("certificates signed in byte order still verify") + func byteOrderSignatureStillVerifies() async throws { + let unsigned = try Certificate( + type: try CertificateTypeID([UInt8](repeating: 0x22, count: 32)), + serialNumber: try CertificateSerialNumber([UInt8](repeating: 0x23, count: 32)), + subject: try key(7).publicKey, + certifier: try key(11).publicKey, + revocationOutpoint: CertificateEngine.disabledRevocationOutpoint, + fields: [ + try CertificateFieldName("Zip"): try CertificateCiphertext([1]), + try CertificateFieldName("age"): try CertificateCiphertext([2]), + ]) + // `Certificate.signed` signs the UTF-8 byte order, as the Go SDK does. + let byteOrder = try await unsigned.signed(using: ProtoWallet(rootKey: try key(11))) + #expect(try await byteOrder.verifySignatureInEitherFieldOrder(limits: .standard)) + let localeOrder = try await unsigned.signedInLocaleOrder( + using: ProtoWallet(rootKey: try key(11)), limits: .standard) + #expect(byteOrder.signature != localeOrder.signature) + #expect(try await localeOrder.verifySignatureInEitherFieldOrder(limits: .standard)) + + let tampered = try Certificate( + type: unsigned.type, serialNumber: unsigned.serialNumber, subject: unsigned.subject, + certifier: unsigned.certifier, revocationOutpoint: unsigned.revocationOutpoint, + fields: [ + try CertificateFieldName("Zip"): try CertificateCiphertext([9]), + try CertificateFieldName("age"): try CertificateCiphertext([2]), + ], + signature: byteOrder.signature) + #expect(try await tampered.verifySignatureInEitherFieldOrder(limits: .standard) == false) + } + + private func verifies(_ certificate: Certificate, over preimage: [UInt8]) async throws -> Bool { + try await ProtoWallet.anyone().verifySignature( + .init( + protocolID: try CertificateProtocols.signature, + keyID: try WalletKeyID(certificate.signatureKeyID), + counterparty: .publicKey(certificate.certifier), + payload: .digest(BSVHashing.sha256(preimage)), + signature: try #require(certificate.signature)) + ).valid + } + + private func unsignedCopy(of certificate: Certificate) throws -> Certificate { + try Certificate( + type: certificate.type, serialNumber: certificate.serialNumber, + subject: certificate.subject, certifier: certificate.certifier, + revocationOutpoint: certificate.revocationOutpoint, fields: certificate.fields) + } + + private func key(_ scalar: UInt8) throws -> PrivateKey { + var bytes = [UInt8](repeating: 0, count: 32) + bytes[31] = scalar + return try PrivateKey(bytes) + } +} diff --git a/Tests/BSVConformanceTests/AuthGoOracleTests.swift b/Tests/BSVConformanceTests/AuthGoOracleTests.swift index 1762d55..42b7488 100644 --- a/Tests/BSVConformanceTests/AuthGoOracleTests.swift +++ b/Tests/BSVConformanceTests/AuthGoOracleTests.swift @@ -45,6 +45,7 @@ struct AuthGoOracleTests { let peer = try privateKey(10) let certifier = try privateKey(11) let nonce = Base64Encoding.encode([UInt8](repeating: 4, count: 32)) + let sessionNonce = Base64Encoding.encode([UInt8](repeating: 5, count: 48)) let type = try CertificateTypeID([UInt8](repeating: 0x21, count: 32)) let field = try CertificateFieldName("email") let escapedField = try CertificateFieldName("<&\u{2028}") @@ -57,6 +58,7 @@ struct AuthGoOracleTests { messageType: .certificateRequest, identityKey: requester.publicKey, nonce: nonce, + initialNonce: sessionNonce, yourNonce: nonce, signature: signature.derBytes, requestedCertificates: request @@ -95,6 +97,7 @@ struct AuthGoOracleTests { messageType: .certificateResponse, identityKey: peer.publicKey, nonce: nonce, + initialNonce: sessionNonce, yourNonce: nonce, signature: signature.derBytes, certificates: [verifiable] diff --git a/Tests/BSVWalletTests/WalletIdentifierTests.swift b/Tests/BSVWalletTests/WalletIdentifierTests.swift index 4128cfe..445e282 100644 --- a/Tests/BSVWalletTests/WalletIdentifierTests.swift +++ b/Tests/BSVWalletTests/WalletIdentifierTests.swift @@ -196,8 +196,9 @@ final class WalletIdentifierTests: XCTestCase { } func testCryptoLimitsValidation() throws { - XCTAssertEqual(WalletCryptoLimits.standard.maximumPayloadByteCount, 16_777_216) - XCTAssertEqual(WalletCryptoLimits.standard.maximumCiphertextByteCount, 16_777_264) + XCTAssertEqual(WalletCryptoLimits.standard.maximumPayloadByteCount, 17_301_504) + XCTAssertEqual(WalletCryptoLimits.defaultPayloadByteCount, 17_301_504) + XCTAssertEqual(WalletCryptoLimits.standard.maximumCiphertextByteCount, 17_301_552) XCTAssertEqual(try WalletCryptoLimits(), WalletCryptoLimits.standard) XCTAssertEqual(try WalletCryptoLimits(maximumPayloadByteCount: 0).maximumCiphertextByteCount, 48) XCTAssertThrowsError(try WalletCryptoLimits(maximumPayloadByteCount: -1))