diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 36ecf32..fb74ac4 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -155,6 +155,62 @@ jobs: swift test --enable-code-coverage --filter "StreamingBenchmarkTests/$test" done + # TDF `ec-wrapped` interop with the go reference (opentdf-platform lib/ocrypto), + # no platform needed: go tests its own verifier, then opens a key access + # object and a TDFKAS.rewrap response that Swift wrote. The go → Swift + # direction (the committed go fixture) runs in the `test` job. + interop-ec-wrapped: + runs-on: macos-latest + permissions: + contents: read + defaults: + run: + shell: bash + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + + - name: Cache Swift packages + uses: actions/cache@v4 + with: + path: | + .build + ~/.swiftpm + key: ${{ runner.os }}-swift-${{ hashFiles('Package.swift') }} + restore-keys: | + ${{ runner.os }}-swift- + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version-file: scripts/interop/ec-wrapped/go.mod + cache-dependency-path: scripts/interop/ec-wrapped/go.sum + + - name: Test the go verifier + working-directory: scripts/interop/ec-wrapped + run: | + go vet ./... + go test ./... + + - name: Write a Swift fixture from an encryptFile archive + env: + OPENTDFKIT_INTEROP_OUT: ${{ runner.temp }}/swift-interop.json + run: | + swift test --filter TDFKASEncryptorTests/testWriteSwiftFixtureForGo + # The test skips without the variable; fail if it wrote nothing. + test -s "$OPENTDFKIT_INTEROP_OUT" + + - name: Open the Swift fixture with go + working-directory: scripts/interop/ec-wrapped + env: + OPENTDFKIT_INTEROP_OUT: ${{ runner.temp }}/swift-interop.json + run: go run . verify "$OPENTDFKIT_INTEROP_OUT" + benchmark: runs-on: macos-latest permissions: @@ -211,7 +267,7 @@ jobs: # GitHub-hosted macOS runners are noisy, so this step reports regressions # without blocking the workflow while the baseline stabilizes. continue-on-error: true - run: python3 scripts/parse_benchmarks.py --threshold 2.0 --baseline benchmark-baseline.json --output benchmark-baseline.json *.log + run: python3 scripts/parse_benchmarks.py --threshold 2.0 --baseline benchmark-baseline.json --output benchmark-baseline.json ./*.log - name: Save benchmark baseline if: always() diff --git a/.github/workflows/xtest.yml b/.github/workflows/xtest.yml index 83e4430..1c7392d 100644 --- a/.github/workflows/xtest.yml +++ b/.github/workflows/xtest.yml @@ -2,7 +2,8 @@ # # Pulls arkavo-org/opentdf-tests (pinned until the Swift format fix lands). # Runs native macOS platform deps (Postgres + Keycloak + platform) and pytest -# for swift × go Base TDF only. +# for swift × go Base TDF, RSA-wrapped (`tdf`) and EC-wrapped (`tdf-ecwrap`, a +# platform KAS rewrapping OpenTDFKit's `ec-wrapped` key access objects). # # Two legs run side by side (matrix `go-source`): # upstream — go CLI from opentdf/platform (pinned to PR #4063's head until @@ -371,7 +372,7 @@ jobs: set -e ./sdk/swift/dist/main/cli.sh supports tdf ./sdk/swift/dist/main/cli.sh supports hexless - ! ./sdk/swift/dist/main/cli.sh supports ecwrap || exit 1 + ./sdk/swift/dist/main/cli.sh supports ecwrap - name: Platform version working-directory: ${{ steps.run-platform.outputs.platform-working-dir }} @@ -385,7 +386,7 @@ jobs: - run: uv sync working-directory: otdftests/xtest - - name: Run community xtest (swift × go, Base TDF) + - name: Run community xtest (swift × go, Base TDF and ec-wrapped) working-directory: otdftests/xtest env: PLATFORM_DIR: "../../${{ steps.run-platform.outputs.platform-working-dir }}" @@ -423,7 +424,7 @@ jobs: --junitxml=test-results/opentdfkit-xtest.junit.xml \ --sdks-encrypt "swift@main go@${GO_CH}" \ --sdks-decrypt "swift@main go@${GO_CH}" \ - --containers tdf \ + --containers "tdf tdf-ecwrap" \ --focus swift \ -m stage1 \ -ra -v \ diff --git a/CLAUDE.md b/CLAUDE.md index 0329b3d..848971e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -125,6 +125,7 @@ swift build -c release --product OpenTDFKitCLI .build/release/OpenTDFKitCLI supports nano # exit 0 (supported) .build/release/OpenTDFKitCLI supports nano_ecdsa # exit 0 (supported) .build/release/OpenTDFKitCLI supports tdf # exit 0 (supported) +.build/release/OpenTDFKitCLI supports ecwrap # exit 0 (supported) ``` ### Environment Configuration @@ -141,6 +142,7 @@ export PLATFORMURL=http://localhost:8080 # Optional xtest parameters export XT_WITH_ECDSA_BINDING=true +export XT_WITH_ECWRAP=true # tdf: wrap to the KAS EC P-256 key (ec-wrapped) export XT_WITH_PLAINTEXT_POLICY=true export XT_WITH_ATTRIBUTES="attr1,attr2" export XT_WITH_MIME_TYPE="application/pdf" @@ -211,7 +213,7 @@ OpenTDFKit is composed of several key components that work together to implement - **PublicKeyStore**: Manages only public keys for sharing with peers. Allows secure distribution of one-time use TDF keys. -- **KASRewrapClient**: Client for interacting with KAS rewrap endpoints. Implements JWT signing (ES256), PEM parsing, and key unwrapping protocols. Supports both NanoTDF (EC key wrapping) and TDF (Archive Envelope) (RSA key wrapping) rewrap requests. Designed with protocol-based architecture for testability. Resolves transport endpoints from an `OpenTDFConfiguration` (well-known discovery via `fetchWellKnown`, or `OpenTDFConfiguration.forKasConnect`), preferring ConnectRPC `/kas.AccessService/*` and falling back to legacy REST `/kas/v2/*`; the rewrap client follows no redirects and parses Connect error envelopes. Bearer tokens are opaque (a JWT or a base64url-encoded CWT — the platform decides validation). `rewrapAndUnwrapTDF(manifest:)` is the one-call Standard TDF path: it generates the ephemeral P-256 client key, calls `rewrapTDF`, and unwraps the session-wrapped DEK with the Standard TDF HKDF salt (`standardTDFSessionSalt` = `SHA256("TDF")`, not the NanoTDF salt `unwrapKey` defaults to); it requires exactly one key access object at the KAS. `rewrapAndUnwrapTDFs(_:options:)` is the bulk path: one policy request per manifest (ids `policy-`) in a single Rewrap call, results matched by policy/KAO id, one session KEK; it returns a `BulkRewrapOutcome` per manifest in input order (`.permitted(DEK)`, `.denied`, `.failed(BulkRewrapFailure)`) and throws `BulkRewrapError` (no server text) when the call fails as a whole, e.g. every KAO failing with "could not perform access". More than 1,000 sendable TDFs (`.tooManyPolicies`) or a signed body over `BulkRewrapOptions.maxRequestBodyBytes` (3 MiB default, `.requestTooLarge`) is refused before sending; callers split the list. Every request goes through a `KASRewrapTransport` (default `URLSessionKASTransport`, which refuses redirects); pass one to `init(configuration:oauthToken:transport:)` to apply an app's own destination/TLS policy. +- **KASRewrapClient**: Client for interacting with KAS rewrap endpoints. Implements JWT signing (ES256), PEM parsing, and key unwrapping protocols. Supports both NanoTDF (EC key wrapping) and TDF (Archive Envelope) (RSA key wrapping) rewrap requests. Designed with protocol-based architecture for testability. Resolves transport endpoints from an `OpenTDFConfiguration` (well-known discovery via `fetchWellKnown`, or `OpenTDFConfiguration.forKasConnect`), preferring ConnectRPC `/kas.AccessService/*` and falling back to legacy REST `/kas/v2/*`; the rewrap client follows no redirects and parses Connect error envelopes. Bearer tokens are opaque (a JWT or a base64url-encoded CWT — the platform decides validation). `rewrapAndUnwrapTDF(manifest:)` is the one-call Standard TDF path: it generates the ephemeral P-256 client key, calls `rewrapTDF`, and unwraps the session-wrapped DEK with the Standard TDF HKDF salt (`standardTDFSessionSalt` = `SHA256("TDF")`, not the NanoTDF salt `unwrapKey` defaults to); it requires exactly one key access object at the KAS. `rewrapAndUnwrapTDFs(_:options:)` is the bulk path: one policy request per manifest (ids `policy-`) in a single Rewrap call, results matched by policy/KAO id, one session KEK; it returns a `BulkRewrapOutcome` per manifest in input order (`.permitted(DEK)`, `.denied`, `.failed(BulkRewrapFailure)`) and throws `BulkRewrapError` (no server text) when the call fails as a whole, e.g. every KAO failing with "could not perform access". More than 1,000 sendable TDFs (`.tooManyPolicies`) or a signed body over `BulkRewrapOptions.maxRequestBodyBytes` (3 MiB default, `.requestTooLarge`) is refused before sending; callers split the list. Every request goes through a `KASRewrapTransport` (default `URLSessionKASTransport`, which refuses redirects); pass one to `init(configuration:oauthToken:transport:)` to apply an app's own destination/TLS policy. Key access objects match the configured KAS by scheme, host, port **and normalized path** (trailing `/` trimmed, `/kas` ≡ no path), because a platform KAS and owner KASs share platform.arkavo.net; a KAS mounted under another prefix needs it in `kas.uri`. For a KAS that may answer later (an owner KAS behind a relay), `prepareRewrap(manifest:clientPrivateKey:options:)` signs with the init `signingKey` (the bearer token's `cnf` key), the caller's `exp` and one `requestBody` extension member, and returns the bytes (resend the same `PreparedRewrap` after a network failure); `submitRewrap` gives `.answered` on 200 or `.pending` on 202 (same-origin `Location` only, `Retry-After` delta-seconds clamped to 1–60 s, default 2); `pollRewrap(_:until:)` rechecks the handle's origin, gives `.answered`, `.expired` (410, or 404 at or after the token's `exp`) or `.deadlineReached(handle)`, sleeps no later than the deadline (polling once more at it), never polls after it, and clamps each poll's timeout to it; a 403 on this path is `.httpError`, never `.accessDenied`; `rewrap(...)` runs all three, unwraps permitted shares, and reports its default deadline (the token's `exp`) as `.expired`. A `RewrapAnswer` keeps every result (status, error, metadata, `kasWrappedKey`), the session key and the request-token digest: a denial is a result, not an error. - **KASDiscovery**: ConnectRPC/well-known discovery support. Provides `OpenTDFConfiguration`/`KasConfig`/`IdpConfig` Codable types, `KasEndpoints` resolution (Connect-preferred, REST-fallback) with HTTPS/SSRF URL validation, Connect error-envelope parsing, and `fetchWellKnown` for `/.well-known/opentdf-configuration`. @@ -219,9 +221,11 @@ OpenTDFKit is composed of several key components that work together to implement - **TDFManifest**: Complete OpenTDF schema data structures for TDF (Archive Envelope) v1.0.0. Includes manifest, payload descriptor, encryption information, key access objects, and integrity information with proper Codable conformance. -- **TDFCrypto**: RSA and AES cryptographic operations for TDF (Archive Envelope). Implements RSA-2048+ key wrapping with OAEP padding, AES-256-GCM encryption, HMAC-SHA256 for integrity and policy binding. Includes key size validation (minimum 2048 bits). +- **TDFCrypto**: RSA and AES cryptographic operations for TDF (Archive Envelope). Implements RSA-2048+ key wrapping with OAEP padding, AES-256-GCM encryption, HMAC-SHA256 for integrity and policy binding. Includes key size validation (minimum 2048 bits). Two EC wraps: `wrapSymmetricKeyWithECForKAS` is the go SDK / platform `ec-wrapped` scheme (HKDF salt `SHA256("TDF")`, PEM ephemeral key) that a KAS rewraps; `wrapSymmetricKeyWithEC` is the TDF-JSON / TDF-CBOR draft scheme (empty salt, compressed SEC1) and is not interchangeable. -- **TDFProcessor**: High-level encryption and decryption operations. Handles symmetric key generation, key wrapping, policy binding, segment signatures, and multi-KAS key reconstruction via XOR. Supports both offline decryption (with symmetric key) and KAS rewrap decryption (with RSA key pair). +- **TDFProcessor**: High-level encryption and decryption operations. Handles symmetric key generation, key wrapping, policy binding, segment signatures, and multi-KAS key reconstruction via XOR. Supports both offline decryption (with symmetric key) and KAS rewrap decryption (with RSA key pair). `TDFKasInfo.keyType` picks the key access object: `.rsa` (default) writes `wrapped`, `.ecP256` writes `ec-wrapped` and needs a non-blank `kid` and AES-256 (`TDFEncryptError` otherwise). Every entry point first loads the KAS public key as its declared type (`TDFCryptoError` on a mismatch), so a bad configuration fails before the input is read or anything is written. + +- **TDFKAS**: Pure KAS-side rewrap of a TDF `ec-wrapped` key access object and the matching client unwrap, for an on-device KAS (no network, no storage, keys as CryptoKit values). `rewrap(keyAccessObject:policyBase64:kasPrivateKey:receiverPublicKey:)` opens the key share with the KAS key, verifies the spec-form policy binding (HS256 over the manifest's base64 policy text, raw HMAC; go's legacy hex form is refused), and seals the share to the receiver under a fresh session key; `unwrap(wrappedKey:sessionPublicKey:receiverPrivateKey:)` opens it. PEM ephemeral keys only, 32-byte shares only, share wiped on every exit. A passing binding does not prove who made the key access object (anyone with the KAS public key can make one), so callers match it against their own records first and send requesters one failure code. On the KAS side, `verifyRewrapRequest(body:signingPublicKey:)` verifies a received Rewrap (≤ 64 KiB, ES256 only, no `crit`, canonical base64url, no duplicate JSON members, `exp` returned not enforced) and returns `clientPublicKey`, the policies with their key access objects and extension members; `rewrapResponseBody(sessionPublicKey:responses:)` builds the answer. Shared digests both sides must agree on: `requestTokenDigest` (SHA-256 of the JWT string), `keyAccessObjectDigest` (fixed field encoding, `schemaVersion` excluded, so the manifest's object and the forwarded one digest the same) and `publicKeyFingerprint` (SHA-256 of the uncompressed SEC1 point). `scripts/interop/ec-wrapped` (go) generates the test fixture and verifies Swift output; run its `verify` before tagging a release that touches this path. - **TDFArchive**: ZIP archive I/O using ZIPFoundation. Reads and writes TDF (Archive Envelope) containers with spec `manifest.json` and `0.payload` structure (reads legacy `0.manifest.json` too). `TDFLoader(maxPayloadSize:)` bounds the payload read (`TDFArchiveError.payloadTooLarge`). Supports both camelCase (archive) JSON encoding. diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index ac802fc..4f00277 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -2,6 +2,24 @@ This guide covers breaking changes across all OpenTDFKit versions. +## v5.2.0 - KAS-side EC rewrap and `ec-wrapped` encryption + +**What changed:** additive, except that key access object matching is now path-aware (see below) and `KASRewrapError` has new cases. + +- `TDFKAS.rewrap(keyAccessObject:policyBase64:kasPrivateKey:receiverPublicKey:)` is the KAS side of a TDF `ec-wrapped` rewrap, and `TDFKAS.unwrap(wrappedKey:sessionPublicKey:receiverPrivateKey:)` the matching client unwrap, as pure functions for an on-device KAS. Failures are `TDFKASError`. The policy binding must be the spec form (Base64 of the raw HMAC-SHA256); go's legacy hex form is refused. +- `TDFKasInfo` gains `keyType` (`.rsa` by default, `.ecP256`). With `.ecP256`, `TDFEncryptor` writes an `ec-wrapped` key access object in the go SDK / opentdf-platform scheme, which needs a `kid` and AES-256; otherwise it throws `TDFEncryptError` before writing anything. +- `TDFCrypto.wrapSymmetricKeyWithECForKAS(publicKeyPEM:symmetricKey:)` returns `KASECWrappedKey`. The existing `wrapSymmetricKeyWithEC` / `unwrapSymmetricKeyWithEC` are the TDF-JSON / TDF-CBOR draft scheme (empty salt, compressed SEC1 ephemeral key), now documented as such; their behaviour is unchanged. +- `KASRewrapClient.unwrapKey` wipes the opened key bytes before returning. +- Owner KAS, KAS side: `TDFKAS.verifyRewrapRequest(body:signingPublicKey:)`, `TDFKAS.rewrapResponseBody(sessionPublicKey:responses:)`, and the shared digests `TDFKAS.requestTokenDigest`, `TDFKAS.keyAccessObjectDigest` and `TDFKAS.publicKeyFingerprint`. +- Owner KAS, client side: `KASRewrapClient.prepareRewrap`, `submitRewrap`, `pollRewrap` and `rewrap`, for a KAS that answers `202` and is polled; they sign with the init `signingKey`, take the token's `exp` and one extension member from the caller, and return denials as results. The existing `rewrapTDF` and friends are unchanged. +- **Matching is path-aware.** A key access object now matches the configured KAS only if its normalized path does too (`/kas` is the same as no path). A KAS mounted under another prefix (for example `https://host/api/kas`) needs that prefix in the configured `kas.uri`. +- `OpenTDFKitCLI` supports `ecwrap`: with `XT_WITH_ECWRAP=true`, `tdf` encrypt fetches the KAS's EC P-256 key and its `kid` and writes an `ec-wrapped` key access object. +- Every `TDFEncryptor` entry point now loads the KAS public key before reading the input, so an unreadable or mismatched key (RSA as well as EC) throws its `TDFCryptoError` before any encryption work instead of after. The error is the same. + +### Migration Steps + +No migration is required for most callers. Existing `TDFKasInfo` callers default to `.rsa` and write the same output as before. If you match on `KASRewrapError` exhaustively, add `.invalidRewrapOptions`, `.pendingWithoutLocation` and `.unsafeLocation`. If your KAS is mounted under a prefix other than `/kas`, put that prefix in the configured KAS URL. + ## v5.1.0 - Bulk rewrap and payload cap **What changed:** `KASRewrapClient.rewrapAndUnwrapTDFs(_:options:)` rewraps up to 1,000 standard TDFs in one Rewrap call; more TDFs, or a signed request over `BulkRewrapOptions.maxRequestBodyBytes`, is refused before sending, so split the list. Every `KASRewrapClient` request now goes through a `KASRewrapTransport`; the existing `urlSession:` initializer wraps it in `URLSessionKASTransport`, so behaviour is unchanged. `TDFLoader(maxPayloadSize:)` bounds the payload read. `encryptFile` and `buildArchiveToFile` write through a temporary `.partial` file beside the output, so its directory must be writable. The archive reader now accepts only regular-file manifest and payload entries; a symlink or directory entry throws `TDFArchiveError.unsupportedEntryType(String)`. diff --git a/OpenTDFKit/KASRewrapClient.swift b/OpenTDFKit/KASRewrapClient.swift index 8a4a426..f72f8f0 100644 --- a/OpenTDFKit/KASRewrapClient.swift +++ b/OpenTDFKit/KASRewrapClient.swift @@ -439,13 +439,17 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { // MARK: - Properties - private let endpoints: KasEndpoints + let endpoints: KasEndpoints /// KAS identity url for the request-body KeyAccessObject when the NanoTDF /// header locator is unavailable (fallback only). private let kasIdentityURL: String - private let oauthToken: String + let oauthToken: String let transport: any KASRewrapTransport - private let signingKey: P256.Signing.PrivateKey + let signingKey: P256.Signing.PrivateKey + /// Waits between polls of a pending Rewrap; injectable for tests. + let sleeper: @Sendable (TimeInterval) async throws -> Void + /// The clock for Rewrap deadlines; injectable for tests. + let now: @Sendable () -> Date // MARK: - Initialization @@ -468,15 +472,34 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { /// - configuration: Resolved config, validated as in `init(configuration:oauthToken:urlSession:signingKey:)`. /// - oauthToken: Bearer token (opaque: a JWT or base64url-encoded CWT). /// - transport: Sends each request; it must not follow redirects. - public init(configuration: OpenTDFConfiguration, oauthToken: String, - transport: any KASRewrapTransport, - signingKey: P256.Signing.PrivateKey? = nil) throws + public convenience init(configuration: OpenTDFConfiguration, oauthToken: String, + transport: any KASRewrapTransport, + signingKey: P256.Signing.PrivateKey? = nil) throws + { + try self.init( + configuration: configuration, + oauthToken: oauthToken, + transport: transport, + signingKey: signingKey, + sleeper: { try await Task.sleep(nanoseconds: UInt64($0 * 1_000_000_000)) }, + now: { Date() }, + ) + } + + /// The designated initializer, with the poll sleeper and clock injectable. + init(configuration: OpenTDFConfiguration, oauthToken: String, + transport: any KASRewrapTransport, + signingKey: P256.Signing.PrivateKey?, + sleeper: @escaping @Sendable (TimeInterval) async throws -> Void, + now: @escaping @Sendable () -> Date) throws { endpoints = try KasEndpoints.from(configuration) kasIdentityURL = configuration.kas?.uri ?? "" self.oauthToken = oauthToken self.transport = transport self.signingKey = signingKey ?? P256.Signing.PrivateKey() + self.sleeper = sleeper + self.now = now } // MARK: - Public Methods @@ -733,8 +756,9 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { } /// The manifest's key access objects held by this client's KAS (matched by - /// scheme, host and effective port), in rewrap request order: the request - /// and result id `kao-` refers to element `i`. + /// scheme, host, effective port and normalized path, with `/kas` the same + /// as no path), in rewrap request order: the request and result id + /// `kao-` refers to element `i`. /// - Parameter manifest: The parsed TDF manifest containing key access entries. /// - Returns: The key access objects a `rewrapTDF` call sends. public func keyAccessObjects(in manifest: TDFManifest) -> [TDFKeyAccessObject] { @@ -989,7 +1013,10 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { /// The HTTP body of a Rewrap call: `{"signed_request_token": }`. func signedRewrapBody(requestBody: Data, signingKey: P256.Signing.PrivateKey) throws -> Data { - let signedToken = try createSignedJWT(requestBody: requestBody, signingKey: signingKey) + let now = Int(Date().timeIntervalSince1970) + let signedToken = try createSignedJWT( + requestBody: requestBody, signingKey: signingKey, issuedAt: now, expiresAt: now + 60, + ) return try JSONEncoder().encode(SignedRewrapRequest(signed_request_token: signedToken)) } @@ -1028,7 +1055,7 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { /// Map a non-2xx rewrap response to a KASRewrapError, enriching the message /// from a Connect error envelope when present. - private func mapRewrapHTTPError(status: Int, data: Data) -> KASRewrapError { + func mapRewrapHTTPError(status: Int, data: Data) -> KASRewrapError { let body = String(data: data, encoding: .utf8) ?? "" let detail = parseConnectError(body).map { "\($0.code): \($0.message)" } ?? (body.isEmpty ? "HTTP \(status)" : body) @@ -1039,6 +1066,9 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { } } + /// Whether a key access object's URL names this client's KAS: scheme and host + /// (case-insensitive), effective port, and normalized path. A platform KAS and + /// owner KASs share one host, so the path decides. private func matchesKasURL(_ otherURLString: String) -> Bool { guard let otherURL = URL(string: otherURLString), let kasURL = URL(string: kasIdentityURL), let baseScheme = kasURL.scheme?.lowercased(), @@ -1050,9 +1080,50 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { return false } return effectivePort(for: kasURL) == effectivePort(for: otherURL) + && Self.normalizedKasPath(kasURL) == Self.normalizedKasPath(otherURL) } - private func effectivePort(for url: URL) -> Int { + /// A KAS URL's path for matching: percent-encoded unreserved characters + /// decoded and other escapes upper-cased (RFC 3986 §6.2.2), trailing `/` + /// trimmed (case kept), and `/kas` the same as no path, because a platform + /// KAS is served at `/kas` for REST and at the root for Connect, + /// and discovery reports it without one. + static func normalizedKasPath(_ url: URL) -> String { + var path = normalizedPercentEncoding(url.path(percentEncoded: true)) + while path.hasSuffix("/") { + path.removeLast() + } + return path == "/kas" ? "" : path + } + + /// Decodes `%XX` escapes of unreserved characters (`A–Z a–z 0–9 - . _ ~`) + /// and upper-cases the hex of the rest, which stay encoded (an encoded `/` + /// is not a path separator). + static func normalizedPercentEncoding(_ path: String) -> String { + var output = "" + var bytes = Array(path.utf8)[...] + while let byte = bytes.first { + bytes = bytes.dropFirst() + guard byte == UInt8(ascii: "%"), bytes.count >= 2, + let value = UInt8(String(decoding: bytes.prefix(2), as: UTF8.self), radix: 16) + else { + output.unicodeScalars.append(Unicode.Scalar(byte)) + continue + } + bytes = bytes.dropFirst(2) + let scalar = Unicode.Scalar(value) + if CharacterSet(charactersIn: "-._~").contains(scalar) || (scalar.isASCII && scalar.properties.isAlphabetic) + || ("0" ... "9").contains(scalar) + { + output.unicodeScalars.append(scalar) + } else { + output += String(format: "%%%02X", value) + } + } + return output + } + + func effectivePort(for url: URL) -> Int { if let explicitPort = url.port { return explicitPort } @@ -1081,10 +1152,24 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { sessionPublicKey: Data, clientPrivateKey: Data, salt: Data? = nil, + ) throws -> SymmetricKey { + try unwrapKey( + wrappedKey: wrappedKey, + sessionPublicKey: P256.KeyAgreement.PublicKey(compressedRepresentation: sessionPublicKey), + clientPrivateKey: P256.KeyAgreement.PrivateKey(rawRepresentation: clientPrivateKey), + salt: salt, + ) + } + + /// `unwrapKey` with the keys as CryptoKit values, so no caller has to make a + /// raw copy of the private key to call it. + static func unwrapKey( + wrappedKey: Data, + sessionPublicKey publicKey: P256.KeyAgreement.PublicKey, + clientPrivateKey privateKey: P256.KeyAgreement.PrivateKey, + salt: Data?, ) throws -> SymmetricKey { // Perform ECDH with session public key - let privateKey = try P256.KeyAgreement.PrivateKey(rawRepresentation: clientPrivateKey) - let publicKey = try P256.KeyAgreement.PublicKey(compressedRepresentation: sessionPublicKey) let sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey) // Derive symmetric key using HKDF @@ -1106,7 +1191,10 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { // Use the SealedBox combined initializer which expects nonce+ciphertext+tag let sealedBox = try AES.GCM.SealedBox(combined: wrappedKey) - let decryptedKey = try AES.GCM.open(sealedBox, using: symmetricKey) + var decryptedKey = try AES.GCM.open(sealedBox, using: symmetricKey) + defer { + decryptedKey.secureZero() + } return SymmetricKey(data: decryptedKey) } @@ -1211,20 +1299,26 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { /// - Parameters: /// - requestBody: The request body data to include in claims /// - signingKey: P256 private key for signing + /// - issuedAt: The `iat` claim, Unix seconds + /// - expiresAt: The `exp` claim, Unix seconds /// - Returns: Signed JWT string in format header.payload.signature - private func createSignedJWT(requestBody: Data, signingKey: P256.Signing.PrivateKey) throws -> String { + func createSignedJWT( + requestBody: Data, + signingKey: P256.Signing.PrivateKey, + issuedAt: Int, + expiresAt: Int, + ) throws -> String { // Create header with ES256 algorithm let header = ["alg": "ES256", "typ": "JWT"] let headerJSON = try JSONSerialization.data(withJSONObject: header) let headerBase64 = headerJSON.base64URLEncodedString() // Create claims with the request body and required timestamps - let now = Int(Date().timeIntervalSince1970) let requestBodyString = String(data: requestBody, encoding: .utf8) ?? "" let claims: [String: Any] = [ "requestBody": requestBodyString, - "iat": now, - "exp": now + 60, + "iat": issuedAt, + "exp": expiresAt, ] let claimsJSON = try JSONSerialization.data(withJSONObject: claims) let claimsBase64 = claimsJSON.base64URLEncodedString() @@ -1263,6 +1357,14 @@ public enum KASRewrapError: Error, CustomStringConvertible { case multipleWrappedKeys(Int) /// Local unwrap of the session-wrapped key failed (wrong salt/key, corrupt bytes). case keyUnwrapFailed(String) + /// `prepareRewrap` options are unusable (a past `expiresAt`, an extension + /// that is not JSON or that reuses a standard `requestBody` member name). + case invalidRewrapOptions(String) + /// A KAS answered `202` without a `Location` to poll. + case pendingWithoutLocation + /// A `202`'s `Location` is not on the KAS's origin; the bearer token is not + /// sent there. + case unsafeLocation(String) public var description: String { switch self { @@ -1298,6 +1400,12 @@ public enum KASRewrapError: Error, CustomStringConvertible { "Expected exactly one wrapped key from KAS, got \(count); split-key manifests need rewrapTDF and reconstruction" case let .keyUnwrapFailed(reason): "Failed to unwrap KAS session-wrapped key: \(reason)" + case let .invalidRewrapOptions(reason): + "Invalid rewrap options: \(reason)" + case .pendingWithoutLocation: + "KAS answered 202 without a Location to poll" + case let .unsafeLocation(location): + "Refusing to poll \(location.prefix(200)): not the KAS's origin" } } } @@ -1306,6 +1414,19 @@ public enum KASRewrapError: Error, CustomStringConvertible { /// Extension for base64URL encoding extension Data { + /// Decodes base64url, unpadded or padded; `nil` for anything else, including + /// the standard alphabet's `+` and `/`. + init?(base64URLEncoded text: some StringProtocol) { + guard !text.contains("+"), !text.contains("/") else { + return nil + } + var base64 = String(text).replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + if base64.count % 4 != 0 { + base64 += String(repeating: "=", count: 4 - base64.count % 4) + } + self.init(base64Encoded: base64) + } + func base64URLEncodedString() -> String { base64EncodedString() .replacingOccurrences(of: "+", with: "-") diff --git a/OpenTDFKit/KASRewrapPending.swift b/OpenTDFKit/KASRewrapPending.swift new file mode 100644 index 0000000..d26f41f --- /dev/null +++ b/OpenTDFKit/KASRewrapPending.swift @@ -0,0 +1,405 @@ +@preconcurrency import CryptoKit +import Foundation + +// MARK: - Rewrap at a KAS that may answer later + +/// A Rewrap path for a KAS that may answer with `202` and a `Location` to poll, +/// such as an owner KAS behind a relay, as well as a platform KAS that answers +/// at once. Unlike `rewrapTDF`, it signs with the client's init `signingKey`, +/// lets the caller set the signed request token's `exp` and add one extension +/// member, and returns every result (a denial is a result, not an error). +public extension KASRewrapClient { + /// Options for `prepareRewrap`. + struct RewrapOptions: Sendable { + /// The signed request token's `exp`; `nil` means 60 seconds from now. An + /// owner KAS needs it equal to the bearer token's `exp`. + public var expiresAt: Date? + /// One extra top-level `requestBody` member, covered by the signature. + public var requestBodyExtension: RequestBodyExtension? + + public init(expiresAt: Date? = nil, requestBodyExtension: RequestBodyExtension? = nil) { + self.expiresAt = expiresAt + self.requestBodyExtension = requestBodyExtension + } + } + + /// A top-level `requestBody` member: its name, which must not be a standard + /// member's, and its JSON value. + struct RequestBodyExtension: Sendable { + public let name: String + public let json: Data + + public init(name: String, json: Data) { + self.name = name + self.json = json + } + } + + /// A signed Rewrap request as bytes. Submitting the same value again sends + /// identical bytes, so a resend after a network failure is the same request. + struct PreparedRewrap: Sendable { + /// The HTTP body, `{"signed_request_token": ""}`. + public let body: Data + public let requestToken: String + /// `TDFKAS.requestTokenDigest(requestToken)`. + public let requestTokenDigest: Data + public let expiresAt: Date + /// The key access objects sent, in `kao-` order. + let keyAccessObjects: [TDFKeyAccessObject] + } + + /// Builds and signs a Rewrap request for this KAS's key access objects in + /// `manifest`, without sending it. The policy is sent as the manifest's + /// `encryptionInformation.policy` string, unchanged. + /// - Parameters: + /// - manifest: The TDF's manifest. + /// - clientPrivateKey: The key the KAS rewraps to; its public key is sent. + /// - options: The token's `exp` and an optional extension member. + /// - Throws: `KASRewrapError.invalidTDFRequest` when no key access object is + /// this KAS's, `.invalidRewrapOptions` for a past `exp` or a bad extension. + func prepareRewrap( + manifest: TDFManifest, + clientPrivateKey: P256.KeyAgreement.PrivateKey, + options: RewrapOptions = .init(), + ) throws -> PreparedRewrap { + let entries = keyAccessObjects(in: manifest) + guard !entries.isEmpty else { + throw KASRewrapError.invalidTDFRequest("No key access entries for this KAS") + } + let unsigned = try StandardUnsignedRewrapRequest( + clientPublicKey: clientPrivateKey.publicKey.pemRepresentation, + requests: [standardPolicyRequest(manifest: manifest, keyAccessEntries: entries)], + ) + var requestBody = try JSONEncoder().encode(unsigned) + + if let member = options.requestBodyExtension { + guard !TDFKAS.standardRequestBodyMembers.contains(member.name) else { + throw KASRewrapError.invalidRewrapOptions("extension name '\(member.name)' is a standard member") + } + guard let value = try? JSONSerialization.jsonObject(with: member.json, options: [.fragmentsAllowed]), + var object = try JSONSerialization.jsonObject(with: requestBody) as? [String: Any] + else { + throw KASRewrapError.invalidRewrapOptions("extension '\(member.name)' is not JSON") + } + object[member.name] = value + requestBody = try JSONSerialization.data(withJSONObject: object) + } + + let issuedAt = Int(now().timeIntervalSince1970) + let expiresAt: Int + if let requested = options.expiresAt?.timeIntervalSince1970 { + // NumericDate up to 9999-12-31; also keeps Int(_:) from trapping. + guard requested.isFinite, requested >= 0, requested <= 253_402_300_799 else { + throw KASRewrapError.invalidRewrapOptions("expiresAt is out of range") + } + expiresAt = Int(requested) + } else { + expiresAt = issuedAt + 60 + } + guard expiresAt > issuedAt else { + throw KASRewrapError.invalidRewrapOptions("expiresAt must be in the future") + } + let token = try createSignedJWT( + requestBody: requestBody, signingKey: signingKey, issuedAt: issuedAt, expiresAt: expiresAt, + ) + return try PreparedRewrap( + body: JSONEncoder().encode(SignedRewrapRequest(signed_request_token: token)), + requestToken: token, + requestTokenDigest: TDFKAS.requestTokenDigest(token), + expiresAt: Date(timeIntervalSince1970: TimeInterval(expiresAt)), + keyAccessObjects: entries, + ) + } +} + +// MARK: - Submit and poll + +public extension KASRewrapClient { + /// A Rewrap the KAS accepted but has not answered yet: poll `location` after + /// `retryAfter` seconds. Holds no key; keep it to resume after an interruption. + struct PendingRewrap: Sendable { + /// Where to poll; always on the KAS's origin. + public let location: URL + public let retryAfter: TimeInterval + public let requestTokenDigest: Data + /// The signed request token's `exp`, which is the KAS's deadline. + public let expiresAt: Date + let keyAccessObjects: [TDFKeyAccessObject] + } + + /// What `submitRewrap` got back. + enum RewrapSubmission: Sendable { + case answered(RewrapAnswer) + case pending(PendingRewrap) + } + + /// What `pollRewrap` ended with. `expired` and `deadlineReached` are never a + /// denial: the KAS gave no answer. + enum RewrapPollOutcome: Sendable { + case answered(RewrapAnswer) + /// The KAS's deadline passed (`410`, or `404` after `expiresAt`). + case expired + /// The caller's deadline came first; poll the handle again to resume. + case deadlineReached(PendingRewrap) + } + + /// `rewrap`'s outcome. `answered` carries the unwrapped share of every + /// permitted result. + enum RewrapOutcome: Sendable { + case answered(RewrapAnswer, shares: [TDFKeyShare]) + case expired + case deadlineReached(PendingRewrap) + } + + /// A KAS's Rewrap response, every result kept: a denial is a result here, + /// so the caller can verify what the KAS sent (for example an owner KAS's + /// signed decision in `metadata`) before using any key. + struct RewrapAnswer: Sendable { + /// The digest of the signed request token this answers. + public let requestTokenDigest: Data + /// `nil` when the KAS permitted nothing. + public let sessionPublicKey: P256.KeyAgreement.PublicKey? + public let results: [KeyAccessResult] + + public struct KeyAccessResult: Sendable { + public let keyAccessObjectId: String + /// The split ID of the key access object `kao-` this answers. + public let sid: String? + /// `permit`, `fail`, or whatever the KAS sent. + public let status: String + /// The share wrapped to the client's key, decoded from base64. + public let kasWrappedKey: Data? + public let error: String? + public let metadata: [String: RewrapMetadataValue] + } + + /// Unwraps one permitted result with `TDFKAS.unwrap` (TDF session salt). + /// - Throws: `KASRewrapError.accessDenied` for a result that is not + /// `permit`, `.missingWrappedKey` / `.missingSessionKey` when the KAS + /// left them out, or `TDFKASError.keyUnwrapFailed`. + public func share( + for result: KeyAccessResult, + clientPrivateKey: P256.KeyAgreement.PrivateKey, + ) throws -> TDFKeyShare { + guard result.status == "permit" else { + throw KASRewrapError.accessDenied(result.error ?? "status=\(result.status)") + } + guard let wrappedKey = result.kasWrappedKey else { + throw KASRewrapError.missingWrappedKey + } + guard let sessionPublicKey else { + throw KASRewrapError.missingSessionKey + } + let key = try TDFKAS.unwrap( + wrappedKey: wrappedKey, + sessionPublicKey: sessionPublicKey, + receiverPrivateKey: clientPrivateKey, + ) + return TDFKeyShare(sid: result.sid, key: key) + } + } + + /// Sends a prepared Rewrap once. `200` is answered; `202` is pending, with + /// its `Location` resolved against the Rewrap URL and refused unless it is + /// on the same scheme, host and port. Never retries; resending the same + /// `PreparedRewrap` is safe. + /// - Throws: `KASRewrapError.pendingWithoutLocation`, `.unsafeLocation`, or + /// the error for any other HTTP status. A `403` is `.httpError(403, …)`, + /// never `.accessDenied`: on this path a denial is always a result. + func submitRewrap(_ prepared: PreparedRewrap) async throws -> RewrapSubmission { + let (data, response) = try await transport.send(rewrapURLRequest(body: prepared.body)) + switch response.statusCode { + case 200: + return try .answered(answer(from: data, digest: prepared.requestTokenDigest, + keyAccessObjects: prepared.keyAccessObjects)) + case 202: + guard let location = response.value(forHTTPHeaderField: "Location"), !location.isEmpty else { + throw KASRewrapError.pendingWithoutLocation + } + return try .pending(PendingRewrap( + location: sameOriginLocation(location), + retryAfter: Self.retryAfterSeconds(response.value(forHTTPHeaderField: "Retry-After")), + requestTokenDigest: prepared.requestTokenDigest, + expiresAt: prepared.expiresAt, + keyAccessObjects: prepared.keyAccessObjects, + )) + default: + throw pendingPathError(status: response.statusCode, data: data) + } + } + + /// Polls a pending Rewrap with the same bearer, waiting `Retry-After` between + /// polls, until it is answered (`200`) or expires (`410`, or `404` at or after + /// `expiresAt`). When the next wait would pass `deadline`, it waits only until + /// `deadline`, polls once more, and returns `.deadlineReached` if that poll is + /// still pending. It never polls after `deadline` (a suspended app that wakes + /// late returns at once), and each poll's timeout ends at `deadline`. + /// - Throws: `KASRewrapError.unsafeLocation` for a handle that isn't on this + /// client's KAS origin (nothing is sent), and `.httpError` for any other + /// status, including a `404` before `expiresAt` (an unknown request: show + /// the KAS as unavailable) and a `403`. + func pollRewrap(_ pending: PendingRewrap, until deadline: Date) async throws -> RewrapPollOutcome { + // The handle may come from another client: this client's bearer only goes + // to this client's KAS origin. + let location = try sameOriginLocation(pending.location.absoluteString) + var current = pending + while true { + let remaining = deadline.timeIntervalSince(now()) + guard remaining > 0 else { + return .deadlineReached(current) + } + try await sleeper(min(current.retryAfter, remaining)) + guard now() <= deadline else { + return .deadlineReached(current) + } + + var request = URLRequest(url: location) + request.httpMethod = "GET" + request.timeoutInterval = min(30, max(1, deadline.timeIntervalSince(now()))) + request.addValue("Bearer \(oauthToken)", forHTTPHeaderField: "Authorization") + let (data, response) = try await transport.send(request) + + switch response.statusCode { + case 200: + return try .answered(answer(from: data, digest: current.requestTokenDigest, + keyAccessObjects: current.keyAccessObjects)) + case 202: + current = PendingRewrap( + location: current.location, + retryAfter: Self.retryAfterSeconds(response.value(forHTTPHeaderField: "Retry-After")), + requestTokenDigest: current.requestTokenDigest, + expiresAt: current.expiresAt, + keyAccessObjects: current.keyAccessObjects, + ) + case 410: + return .expired + case 404 where now() >= current.expiresAt: + return .expired + default: + throw pendingPathError(status: response.statusCode, data: data) + } + } + } + + /// Prepares, submits and polls a Rewrap, and unwraps every permitted share. + /// `deadline` defaults to the request token's `exp`; reaching that default + /// deadline is `.expired`, because the KAS's own deadline has then passed. A + /// cancelled task throws and loses the pending handle; a caller that must + /// resume after an interruption calls the three steps itself. + func rewrap( + manifest: TDFManifest, + clientPrivateKey: P256.KeyAgreement.PrivateKey, + options: RewrapOptions = .init(), + deadline: Date? = nil, + ) async throws -> RewrapOutcome { + let prepared = try prepareRewrap(manifest: manifest, clientPrivateKey: clientPrivateKey, options: options) + let answer: RewrapAnswer + switch try await submitRewrap(prepared) { + case let .answered(immediate): + answer = immediate + case let .pending(pending): + switch try await pollRewrap(pending, until: deadline ?? prepared.expiresAt) { + case let .answered(polled): + answer = polled + case .expired: + return .expired + case let .deadlineReached(handle): + return deadline == nil ? .expired : .deadlineReached(handle) + } + } + let shares = try answer.results.filter { $0.status == "permit" }.map { + try answer.share(for: $0, clientPrivateKey: clientPrivateKey) + } + return .answered(answer, shares: shares) + } + + /// `Retry-After` as delta-seconds (ASCII digits only), clamped to 1–60, with + /// a value too large for `Int` taken as 60; anything else (an HTTP-date, a + /// sign, nothing) is the default of 2 seconds. + internal static func retryAfterSeconds(_ value: String?) -> TimeInterval { + guard let text = value?.trimmingCharacters(in: .whitespaces), !text.isEmpty, + text.utf8.allSatisfy({ (UInt8(ascii: "0") ... UInt8(ascii: "9")).contains($0) }) + else { + return 2 + } + guard let seconds = Int(text) else { + return 60 + } + return TimeInterval(min(max(seconds, 1), 60)) + } +} + +// MARK: - Helpers + +extension KASRewrapClient { + /// `location` resolved against the Rewrap URL, refused unless it keeps the + /// Rewrap URL's scheme, host and effective port and carries no user info: the + /// bearer token goes there. + func sameOriginLocation(_ location: String) throws -> URL { + guard let rewrapURL = URL(string: endpoints.rewrapURL), + let resolved = URL(string: location, relativeTo: rewrapURL)?.absoluteURL, + resolved.user == nil, resolved.password == nil, + resolved.scheme?.lowercased() == rewrapURL.scheme?.lowercased(), + resolved.host?.lowercased() == rewrapURL.host?.lowercased(), + effectivePort(for: resolved) == effectivePort(for: rewrapURL) + else { + throw KASRewrapError.unsafeLocation(location) + } + return resolved + } + + /// The error for a non-answer status on the pending path: as for `rewrapTDF`, + /// except that a `403` is `.httpError(403, …)` and never `.accessDenied`, so + /// a middlebox's refusal can't read as the KAS's decision. + func pendingPathError(status: Int, data: Data) -> KASRewrapError { + let error = mapRewrapHTTPError(status: status, data: data) + if case let .accessDenied(detail) = error { + return .httpError(status, detail) + } + return error + } + + /// Maps a `200` Rewrap response body to a `RewrapAnswer`, keeping every + /// result. Result `kao-` takes the split ID of `keyAccessObjects[i]`. A + /// result whose `kasWrappedKey` is not base64 is kept with no key (`share` + /// then throws), so the other results and its metadata survive. + /// - Throws: `KASRewrapError.emptyResponse` when no result answers a key + /// access object that was sent. + func answer(from data: Data, digest: Data, keyAccessObjects: [TDFKeyAccessObject]) throws -> RewrapAnswer { + let response = try JSONDecoder().decode(RewrapResponse.self, from: data) + let sessionPublicKey: P256.KeyAgreement.PublicKey? + if let pem = response.sessionPublicKey, !pem.isEmpty { + do { + sessionPublicKey = try TDFKAS.parseEphemeralPublicKey(pem) + } catch { + throw KASRewrapError.invalidEcPublicKey("session public key is not a PEM P-256 key") + } + } else { + sessionPublicKey = nil + } + let results = try response.responses.flatMap { policy in + try policy.results.map { result in + let wrapped = (result.kasWrappedKey ?? result.entityWrappedKey).flatMap { Data(base64Encoded: $0) } + let index = result.keyAccessObjectId.hasPrefix("kao-") + ? Int(result.keyAccessObjectId.dropFirst("kao-".count)) : nil + let sid = index.flatMap { keyAccessObjects.indices.contains($0) ? keyAccessObjects[$0].sid : nil } + return RewrapAnswer.KeyAccessResult( + keyAccessObjectId: result.keyAccessObjectId, + sid: sid, + status: result.status, + kasWrappedKey: wrapped, + error: result.error, + metadata: result.metadata ?? [:], + ) + } + } + let answersSentObject = results.contains { result in + result.keyAccessObjectId.hasPrefix("kao-") + && Int(result.keyAccessObjectId.dropFirst("kao-".count)).map(keyAccessObjects.indices.contains) == true + } + guard answersSentObject else { + throw KASRewrapError.emptyResponse + } + return RewrapAnswer(requestTokenDigest: digest, sessionPublicKey: sessionPublicKey, results: results) + } +} diff --git a/OpenTDFKit/TDF/StrictJSON.swift b/OpenTDFKit/TDF/StrictJSON.swift new file mode 100644 index 0000000..3eb5ded --- /dev/null +++ b/OpenTDFKit/TDF/StrictJSON.swift @@ -0,0 +1,197 @@ +import Foundation + +/// Checks JSON that Foundation has already parsed for duplicate object member +/// names, which Foundation's parsers resolve silently (first wins), while +/// RFC 7515 §10.12 and RFC 7519 §4 require a JOSE recipient to reject them, and +/// another parser (a relay's) may resolve them differently. Member names are +/// compared after unescaping, so `"a"` and `"a"` are the same name. +enum StrictJSON { + /// Deeper nesting than this is treated as a duplicate (refused), so the scan + /// can't exhaust the stack. + static let maxDepth = 512 + + /// `true` when any object in `data` repeats a member name, or when the + /// input can't be scanned. + static func hasDuplicateMembers(_ data: Data) -> Bool { + var scanner = Scanner(bytes: Array(data)) + guard let duplicate = try? scanner.scanValue(depth: 0) else { + return true + } + return duplicate + } + + private struct ScanError: Error {} + + private struct Scanner { + let bytes: [UInt8] + var index = 0 + + init(bytes: [UInt8]) { + self.bytes = bytes + } + + /// Scans one value; returns whether a duplicate member was found in it. + mutating func scanValue(depth: Int) throws -> Bool { + guard depth <= StrictJSON.maxDepth else { + throw ScanError() + } + skipWhitespace() + guard index < bytes.count else { + throw ScanError() + } + switch bytes[index] { + case UInt8(ascii: "{"): + return try scanObject(depth: depth) + case UInt8(ascii: "["): + return try scanArray(depth: depth) + case UInt8(ascii: "\""): + _ = try scanString() + return false + default: + while index < bytes.count, !Self.isDelimiter(bytes[index]) { + index += 1 + } + return false + } + } + + mutating func scanObject(depth: Int) throws -> Bool { + index += 1 + var names = Set() + skipWhitespace() + if peek() == UInt8(ascii: "}") { + index += 1 + return false + } + while true { + skipWhitespace() + guard peek() == UInt8(ascii: "\"") else { + throw ScanError() + } + if try !names.insert(scanString()).inserted { + return true + } + skipWhitespace() + guard peek() == UInt8(ascii: ":") else { + throw ScanError() + } + index += 1 + if try scanValue(depth: depth + 1) { + return true + } + skipWhitespace() + switch peek() { + case UInt8(ascii: ","): + index += 1 + case UInt8(ascii: "}"): + index += 1 + return false + default: + throw ScanError() + } + } + } + + mutating func scanArray(depth: Int) throws -> Bool { + index += 1 + skipWhitespace() + if peek() == UInt8(ascii: "]") { + index += 1 + return false + } + while true { + if try scanValue(depth: depth + 1) { + return true + } + skipWhitespace() + switch peek() { + case UInt8(ascii: ","): + index += 1 + case UInt8(ascii: "]"): + index += 1 + return false + default: + throw ScanError() + } + } + } + + /// Scans a string starting at its opening quote and returns it unescaped. + mutating func scanString() throws -> String { + index += 1 + var utf8: [UInt8] = [] + while index < bytes.count { + let byte = bytes[index] + index += 1 + switch byte { + case UInt8(ascii: "\""): + guard let text = String(bytes: utf8, encoding: .utf8) else { + throw ScanError() + } + return text + case UInt8(ascii: "\\"): + guard index < bytes.count else { + throw ScanError() + } + let escape = bytes[index] + index += 1 + switch escape { + case UInt8(ascii: "\""), UInt8(ascii: "\\"), UInt8(ascii: "/"): + utf8.append(escape) + case UInt8(ascii: "b"): utf8.append(0x08) + case UInt8(ascii: "f"): utf8.append(0x0C) + case UInt8(ascii: "n"): utf8.append(0x0A) + case UInt8(ascii: "r"): utf8.append(0x0D) + case UInt8(ascii: "t"): utf8.append(0x09) + case UInt8(ascii: "u"): + var scalar = try scanHex4() + if (0xD800 ... 0xDBFF).contains(scalar) { + guard peek() == UInt8(ascii: "\\"), peek(1) == UInt8(ascii: "u") else { + throw ScanError() + } + index += 2 + let low = try scanHex4() + guard (0xDC00 ... 0xDFFF).contains(low) else { + throw ScanError() + } + scalar = 0x10000 + ((scalar - 0xD800) << 10) + (low - 0xDC00) + } + guard let unicode = Unicode.Scalar(scalar) else { + throw ScanError() + } + utf8.append(contentsOf: Array(String(Character(unicode)).utf8)) + default: + throw ScanError() + } + default: + utf8.append(byte) + } + } + throw ScanError() + } + + mutating func scanHex4() throws -> UInt32 { + guard index + 4 <= bytes.count, + let value = UInt32(String(decoding: bytes[index ..< index + 4], as: UTF8.self), radix: 16) + else { + throw ScanError() + } + index += 4 + return value + } + + mutating func skipWhitespace() { + while index < bytes.count, [0x20, 0x09, 0x0A, 0x0D].contains(bytes[index]) { + index += 1 + } + } + + func peek(_ offset: Int = 0) -> UInt8? { + index + offset < bytes.count ? bytes[index + offset] : nil + } + + static func isDelimiter(_ byte: UInt8) -> Bool { + [UInt8(ascii: ","), UInt8(ascii: "}"), UInt8(ascii: "]"), 0x20, 0x09, 0x0A, 0x0D].contains(byte) + } + } +} diff --git a/OpenTDFKit/TDF/TDFCrypto.swift b/OpenTDFKit/TDF/TDFCrypto.swift index ee9c3fd..5aa572a 100644 --- a/OpenTDFKit/TDF/TDFCrypto.swift +++ b/OpenTDFKit/TDF/TDFCrypto.swift @@ -338,6 +338,11 @@ public enum TDFCrypto { /// Wrap a symmetric key using EC (ECIES: ECDH + HKDF + AES-GCM). /// This generates an ephemeral key pair and uses ECDH with the recipient's public key. + /// + /// This is the TDF-JSON / TDF-CBOR draft scheme: an **empty** HKDF salt and a + /// base64 compressed SEC1 ephemeral key. It is not the go SDK / opentdf-platform + /// `ec-wrapped` scheme, which a platform KAS and `TDFKAS.rewrap` expect; use + /// `wrapSymmetricKeyWithECForKAS` for that. /// - Parameters: /// - publicKeyPEM: The recipient's EC public key in PEM format /// - symmetricKey: The symmetric key to wrap @@ -358,7 +363,8 @@ public enum TDFCrypto { } } - /// Unwrap a symmetric key using EC (ECIES: ECDH + HKDF + AES-GCM). + /// Unwrap a symmetric key using EC (ECIES: ECDH + HKDF + AES-GCM), in the + /// TDF-JSON / TDF-CBOR draft scheme (empty HKDF salt); see `wrapSymmetricKeyWithEC`. /// - Parameters: /// - privateKeyPEM: The recipient's PEM-encoded EC private key /// - wrappedKey: The wrapped key data (base64-encoded nonce + ciphertext + tag) @@ -377,7 +383,8 @@ public enum TDFCrypto { ) } - /// Unwrap a symmetric key using EC (ECIES: ECDH + HKDF + AES-GCM). + /// Unwrap a symmetric key using EC (ECIES: ECDH + HKDF + AES-GCM), in the + /// TDF-JSON / TDF-CBOR draft scheme (empty HKDF salt); see `wrapSymmetricKeyWithEC`. /// - Parameters: /// - privateKey: The recipient's private key for ECDH /// - wrappedKey: The wrapped key data (base64-encoded nonce + ciphertext + tag) @@ -437,6 +444,50 @@ public enum TDFCrypto { return SymmetricKey(data: decryptedKey) } + // MARK: - EC Key Wrapping for a KAS (`ec-wrapped`) + + /// Wraps a key share to a KAS P-256 public key in the go SDK / opentdf-platform + /// `ec-wrapped` scheme (go SDK `generateWrapKeyWithEC`): a fresh ephemeral + /// P-256 key, ECDH, HKDF-SHA256 with salt `SHA256("TDF")`, empty info and a + /// 32-byte output, AES-256-GCM. A platform KAS with EC enabled, and `TDFKAS.rewrap`, + /// can rewrap the result. + /// + /// This is not the scheme of `wrapSymmetricKeyWithEC`, which the TDF-JSON and + /// TDF-CBOR containers use (empty salt, compressed SEC1 ephemeral key). + /// - Parameters: + /// - publicKeyPEM: The KAS's P-256 public key, PEM SubjectPublicKeyInfo. + /// - symmetricKey: The key share to wrap (the DEK for a single-split TDF). + /// - Returns: The base64 wrapped key and the PEM ephemeral public key. + public static func wrapSymmetricKeyWithECForKAS( + publicKeyPEM: String, + symmetricKey: SymmetricKey, + ) throws -> KASECWrappedKey { + let kasPublicKey = try loadECPublicKeyP256(fromPEM: publicKeyPEM) + let ephemeralPrivateKey = P256.KeyAgreement.PrivateKey() + let wrapKey = try deriveKASWrapKey(ephemeralPrivateKey, kasPublicKey) + // Seal straight from the key's own storage, so no copy of the share is left behind. + let sealed = try symmetricKey.withUnsafeBytes { try AES.GCM.seal($0, using: wrapKey) } + return KASECWrappedKey( + wrappedKey: sealed.combined!.base64EncodedString(), + ephemeralPublicKeyPEM: ephemeralPrivateKey.publicKey.pemRepresentation, + ) + } + + /// ECDH, then HKDF-SHA256 with salt `SHA256("TDF")`, empty info, 32 bytes: + /// the go SDK's `tdfSalt()` scheme, used for the `ec-wrapped` key access + /// object wrap and for the rewrap session alike (`TDFKAS`). + static func deriveKASWrapKey( + _ privateKey: P256.KeyAgreement.PrivateKey, + _ publicKey: P256.KeyAgreement.PublicKey, + ) throws -> SymmetricKey { + try privateKey.sharedSecretFromKeyAgreement(with: publicKey).hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: KASRewrapClient.standardTDFSessionSalt, + sharedInfo: Data(), + outputByteCount: 32, + ) + } + // MARK: - P-256 EC Wrapping private static func wrapWithP256(publicKeyPEM: String, symmetricKey: SymmetricKey) throws -> ECWrappedKeyResult { @@ -596,14 +647,25 @@ public enum TDFCrypto { } } -/// Result of EC key wrapping containing wrapped key and ephemeral public key +/// Result of `TDFCrypto.wrapSymmetricKeyWithEC` (the TDF-JSON / TDF-CBOR draft +/// scheme): the wrapped key and the ephemeral public key public struct ECWrappedKeyResult: Sendable { - /// The wrapped symmetric key (nonce + ciphertext + tag) + /// The wrapped symmetric key, base64 (nonce + ciphertext + tag) public let wrappedKey: String - /// The ephemeral public key in PEM format + /// The ephemeral public key, base64 compressed SEC1 (not PEM) public let ephemeralPublicKey: String } +/// A key share wrapped to a KAS by `TDFCrypto.wrapSymmetricKeyWithECForKAS`, in the +/// go SDK / opentdf-platform `ec-wrapped` scheme. +public struct KASECWrappedKey: Sendable { + /// Base64 of nonce (12) ‖ ciphertext ‖ tag (16); the key access object's `wrappedKey`. + public let wrappedKey: String + /// The ephemeral P-256 public key, PEM SubjectPublicKeyInfo; the key access + /// object's `ephemeralPublicKey`. + public let ephemeralPublicKeyPEM: String +} + /// Supported EC curves for TDF3 EC key wrapping public enum TDFECCurve: String, Sendable { case p256 = "ec:secp256r1" diff --git a/OpenTDFKit/TDF/TDFKAS.swift b/OpenTDFKit/TDF/TDFKAS.swift new file mode 100644 index 0000000..65f4917 --- /dev/null +++ b/OpenTDFKit/TDF/TDFKAS.swift @@ -0,0 +1,258 @@ +@preconcurrency import CryptoKit +import Foundation + +// MARK: - TDFKAS + +/// The KAS side of a TDF `ec-wrapped` rewrap, and the matching client unwrap, +/// as pure functions: no network, no storage, keys passed as values. +/// +/// The scheme is the go SDK's and the opentdf-platform KAS's: ECDH on P-256, +/// HKDF-SHA256 with salt `SHA256("TDF")` (`KASRewrapClient.standardTDFSessionSalt`), +/// empty info and a 32-byte output, then AES-256-GCM with the wrapped key laid +/// out as nonce (12) ‖ ciphertext ‖ tag (16). +/// +/// A key access object wraps its split's **key share**. For a TDF with a single +/// split the share is the DEK; with several splits the shares are XORed +/// (`TDFDecryptor.combineKeyShares`). +public enum TDFKAS { + /// Size of every key share this path accepts. + static let shareByteCount = 32 + + /// Smallest wrapped key that can hold a share: nonce (12) + 1 byte + tag (16). + private static let minimumWrappedKeyCount = 12 + 1 + 16 + + /// A key share sealed to a receiver by `rewrap`. + public struct RewrapResult: Sendable { + /// nonce (12) ‖ ciphertext ‖ tag (16). + public let wrappedKey: Data + /// The fresh session public key the receiver needs to open `wrappedKey`. + public let sessionPublicKey: P256.KeyAgreement.PublicKey + + public init(wrappedKey: Data, sessionPublicKey: P256.KeyAgreement.PublicKey) { + self.wrappedKey = wrappedKey + self.sessionPublicKey = sessionPublicKey + } + } + + /// The KAS side of a rewrap: opens the key share in an `ec-wrapped` key + /// access object, verifies the policy binding, and seals the share to the + /// receiver under a fresh session key. The binding is checked before + /// anything is sealed, and the opened share is wiped on every exit. + /// + /// **What success proves.** Anyone holding the KAS *public* key can wrap a + /// key of their choosing to it and compute a valid binding over a policy of + /// their choosing, and `rewrap` will accept that. A passing binding proves + /// only that `policyBase64` belongs to this key access object, not who made + /// it. Match the key access object and policy against your own records + /// before calling, and decide access yourself: this function evaluates no + /// attributes and does not check the object's `url` or `kid`. + /// + /// **Do not forward which step failed.** `.keyUnwrapFailed` versus + /// `.policyBindingRefused` tells the caller whether a submitted ciphertext + /// authenticated under the KAS key. Keep that for your own audit; answer a + /// requester with one failure code for every error. + /// + /// - Parameters: + /// - keyAccessObject: An `ec-wrapped` key access object with a PEM P-256 + /// `ephemeralPublicKey`, as the go SDK and `TDFEncryptor` write it. + /// - policyBase64: The manifest's `encryptionInformation.policy` string, + /// unchanged. The binding is an HMAC over this base64 text, not over the + /// decoded JSON. + /// - kasPrivateKey: The KAS private key the object was wrapped to. + /// - receiverPublicKey: The receiver's P-256 public key. + /// - Returns: The sealed share and the session public key. + /// - Throws: `TDFKASError`; a CryptoKit error only if sealing itself fails. + public static func rewrap( + keyAccessObject: TDFKeyAccessObject, + policyBase64: String, + kasPrivateKey: P256.KeyAgreement.PrivateKey, + receiverPublicKey: P256.KeyAgreement.PublicKey, + ) throws -> RewrapResult { + guard keyAccessObject.type == .ecWrapped else { + throw TDFKASError.unsupportedKeyAccessType(keyAccessObject.type.rawValue) + } + guard let ephemeralPEM = keyAccessObject.ephemeralPublicKey, + !ephemeralPEM.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + else { + throw TDFKASError.missingEphemeralPublicKey + } + let ephemeralPublicKey = try parseEphemeralPublicKey(ephemeralPEM) + guard let wrappedKey = Data(base64Encoded: keyAccessObject.wrappedKey) else { + throw TDFKASError.invalidWrappedKeyEncoding + } + + var share = try openShare(wrappedKey, kasPrivateKey: kasPrivateKey, ephemeralPublicKey: ephemeralPublicKey) + defer { + share.secureZero() + } + guard share.count == shareByteCount else { + throw TDFKASError.keyUnwrapFailed + } + try verifyPolicyBinding(keyAccessObject.policyBinding, policyBase64: policyBase64, share: share) + + let sessionPrivateKey = P256.KeyAgreement.PrivateKey() + let sealed = try AES.GCM.seal(share, using: TDFCrypto.deriveKASWrapKey(sessionPrivateKey, receiverPublicKey)) + return RewrapResult(wrappedKey: sealed.combined!, sessionPublicKey: sessionPrivateKey.publicKey) + } + + /// Opens a rewrapped key share on the client, for a response that did not + /// come from an HTTP rewrap (for example, one relayed from an on-device KAS). + /// `KASRewrapClient` uses the same implementation for HTTP responses. + /// - Parameters: + /// - wrappedKey: nonce (12) ‖ ciphertext ‖ tag (16), as returned by `rewrap`. + /// - sessionPublicKey: The KAS's session public key for this response. + /// - receiverPrivateKey: The private half of the key the share was sealed to. + /// - Returns: The 32-byte key share. + /// - Throws: `TDFKASError.keyUnwrapFailed` for any failure, including a + /// share that is not 32 bytes. + public static func unwrap( + wrappedKey: Data, + sessionPublicKey: P256.KeyAgreement.PublicKey, + receiverPrivateKey: P256.KeyAgreement.PrivateKey, + ) throws -> SymmetricKey { + let share: SymmetricKey + do { + share = try KASRewrapClient.unwrapKey( + wrappedKey: wrappedKey, + sessionPublicKey: sessionPublicKey, + clientPrivateKey: receiverPrivateKey, + salt: KASRewrapClient.standardTDFSessionSalt, + ) + } catch { + throw TDFKASError.keyUnwrapFailed + } + guard share.bitCount == shareByteCount * 8 else { + throw TDFKASError.keyUnwrapFailed + } + return share + } + + // MARK: Scheme + + /// Parses a PEM P-256 public key the way the platform KAS does (go's + /// `pem.Decode`): any line length and line ending, spaces and tabs inside + /// the body, and text after the END line are accepted. + static func parseEphemeralPublicKey(_ text: String) throws -> P256.KeyAgreement.PublicKey { + let begin = "-----BEGIN PUBLIC KEY-----" + let end = "-----END PUBLIC KEY-----" + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard trimmed.hasPrefix(begin) else { + throw TDFKASError.ephemeralKeyNotPEM + } + // Search for END only after BEGIN: the markers' dashes can overlap. + let bodyStart = trimmed.index(trimmed.startIndex, offsetBy: begin.count) + guard let endRange = trimmed.range(of: end, range: bodyStart ..< trimmed.endIndex) else { + throw TDFKASError.invalidEphemeralPublicKey + } + let body = trimmed[bodyStart ..< endRange.lowerBound].filter { !$0.isWhitespace } + guard let der = Data(base64Encoded: String(body)) else { + throw TDFKASError.invalidEphemeralPublicKey + } + do { + return try P256.KeyAgreement.PublicKey(derRepresentation: der) + } catch { + throw TDFKASError.invalidEphemeralPublicKey + } + } + + /// Opens nonce ‖ ciphertext ‖ tag with the KAS key. Every failure is + /// `.keyUnwrapFailed`, so the caller cannot tell which step failed. + private static func openShare( + _ wrappedKey: Data, + kasPrivateKey: P256.KeyAgreement.PrivateKey, + ephemeralPublicKey: P256.KeyAgreement.PublicKey, + ) throws -> Data { + guard wrappedKey.count >= minimumWrappedKeyCount else { + throw TDFKASError.keyUnwrapFailed + } + do { + let key = try TDFCrypto.deriveKASWrapKey(kasPrivateKey, ephemeralPublicKey) + return try AES.GCM.open(AES.GCM.SealedBox(combined: wrappedKey), using: key) + } catch { + throw TDFKASError.keyUnwrapFailed + } + } + + /// Spec-form binding only: `alg` is `HS256` (empty means `HS256`, OpenTDF + /// spec PR #70) and `hash` is Base64 of the raw 32-byte + /// `HMAC-SHA256(share, policyBase64)`, compared in constant time. go's + /// legacy `Base64(hex(HMAC))` form is refused. + private static func verifyPolicyBinding( + _ binding: TDFPolicyBinding, + policyBase64: String, + share: Data, + ) throws { + guard binding.alg == "HS256" || binding.alg.isEmpty, + let expected = Data(base64Encoded: binding.hash), + expected.count == SHA256.byteCount, + HMAC.isValidAuthenticationCode( + expected, + authenticating: Data(policyBase64.utf8), + using: SymmetricKey(data: share), + ) + else { + throw TDFKASError.policyBindingRefused + } + } +} + +// MARK: - Errors + +/// Failures of `TDFKAS`. No description contains key material, a key share or +/// an HMAC. +public enum TDFKASError: Error, CustomStringConvertible, Equatable { + /// The key access object's `type` is not `ec-wrapped`. + case unsupportedKeyAccessType(String) + /// The key access object has no `ephemeralPublicKey`, or an empty one. + case missingEphemeralPublicKey + /// The `ephemeralPublicKey` is not PEM. + case ephemeralKeyNotPEM + /// The `ephemeralPublicKey` is PEM but not a P-256 public key. + case invalidEphemeralPublicKey + /// The `wrappedKey` is not standard base64. + case invalidWrappedKeyEncoding + /// The wrapped key did not open, or did not hold a 32-byte key share. + case keyUnwrapFailed + /// The policy binding is absent, malformed, not `HS256`, or does not match. + case policyBindingRefused + /// A received Rewrap body is over 64 KiB. + case requestTooLarge + /// A received Rewrap is not in the expected shape; the value names the part + /// (never its content). + case malformedRewrapRequest(String) + /// The signed request token's `alg` is not `ES256`. + case unsupportedRequestAlgorithm(String) + /// The signed request token does not verify under the given key. + case requestSignatureInvalid + /// A Rewrap response result is inconsistent; the value names the problem. + case invalidResult(String) + + public var description: String { + switch self { + case let .unsupportedKeyAccessType(type): + "Key access object type '\(type)' is not supported; expected 'ec-wrapped'" + case .missingEphemeralPublicKey: + "Key access object has no ephemeral public key" + case .ephemeralKeyNotPEM: + "Ephemeral public key is not PEM; the TDF-JSON / TDF-CBOR EC scheme (compressed SEC1, empty salt) is not served here" + case .invalidEphemeralPublicKey: + "Ephemeral public key is not a P-256 public key" + case .invalidWrappedKeyEncoding: + "Wrapped key is not valid base64" + case .keyUnwrapFailed: + "Key unwrap failed" + case .policyBindingRefused: + "Policy binding refused" + case .requestTooLarge: + "Rewrap request is larger than 64 KiB" + case let .malformedRewrapRequest(part): + "Rewrap request is malformed: \(part)" + case let .unsupportedRequestAlgorithm(alg): + "Signed request token algorithm '\(alg.prefix(16))' is not supported; expected ES256" + case .requestSignatureInvalid: + "Signed request token signature is invalid" + case let .invalidResult(problem): + "Invalid Rewrap result: \(problem)" + } + } +} diff --git a/OpenTDFKit/TDF/TDFKASDigests.swift b/OpenTDFKit/TDF/TDFKASDigests.swift new file mode 100644 index 0000000..9a58c3e --- /dev/null +++ b/OpenTDFKit/TDF/TDFKASDigests.swift @@ -0,0 +1,60 @@ +@preconcurrency import CryptoKit +import Foundation + +// MARK: - Shared digests + +/// Digests that a KAS and its client must compute identically, for example an +/// owner KAS's signed decision record and the receiver that verifies it. Both +/// sides call these functions; neither hashes JSON bytes, which are not stable +/// across encoders. +public extension TDFKAS { + /// SHA-256 of a signed request token: the compact JWT string's UTF-8 bytes + /// (the `signed_request_token` value, not the HTTP body). + static func requestTokenDigest(_ token: String) -> Data { + Data(SHA256.hash(data: Data(token.utf8))) + } + + /// SHA-256 of a key access object's fields in a fixed encoding, so the object + /// in a TDF's manifest and the one a client forwards in a Rewrap request + /// (which drops `schemaVersion` and reorders keys) digest the same. + /// + /// The input is the tag `OpenTDFKit/kao-digest/v1`, then `type`, `url`, + /// `protocol`, `wrappedKey`, `policyBinding.alg` (empty means `HS256`), + /// `policyBinding.hash`, `kid`, `sid`, `encryptedMetadata` and + /// `ephemeralPublicKey`, in that order. Each field is one presence byte + /// (`0` absent, `1` present), then, when present, a 4-byte big-endian length + /// and its UTF-8 bytes. `schemaVersion` is not included. + static func keyAccessObjectDigest(_ kao: TDFKeyAccessObject) -> Data { + var input = Data("OpenTDFKit/kao-digest/v1".utf8) + let alg = kao.policyBinding.alg.isEmpty ? "HS256" : kao.policyBinding.alg + let fields: [String?] = [ + kao.type.rawValue, + kao.url, + kao.protocolValue.rawValue, + kao.wrappedKey, + alg, + kao.policyBinding.hash, + kao.kid, + kao.sid, + kao.encryptedMetadata, + kao.ephemeralPublicKey, + ] + for field in fields { + guard let field else { + input.append(0) + continue + } + let bytes = Data(field.utf8) + input.append(1) + withUnsafeBytes(of: UInt32(bytes.count).bigEndian) { input.append(contentsOf: $0) } + input.append(bytes) + } + return Data(SHA256.hash(data: input)) + } + + /// SHA-256 of a P-256 public key's 65-byte uncompressed SEC1 point + /// (`04 ‖ X ‖ Y`), whatever encoding the key arrived in. + static func publicKeyFingerprint(_ key: P256.KeyAgreement.PublicKey) -> Data { + Data(SHA256.hash(data: key.x963Representation)) + } +} diff --git a/OpenTDFKit/TDF/TDFKASRequest.swift b/OpenTDFKit/TDF/TDFKASRequest.swift new file mode 100644 index 0000000..cacc48a --- /dev/null +++ b/OpenTDFKit/TDF/TDFKASRequest.swift @@ -0,0 +1,212 @@ +@preconcurrency import CryptoKit +import Foundation + +// MARK: - Verify a received Rewrap (KAS side) + +public extension TDFKAS { + /// Largest Rewrap body `verifyRewrapRequest` reads: 64 KiB, the owner-KAS relay's limit. + static let maxRewrapRequestBytes = 65536 + + /// `requestBody` members that are part of the Rewrap request itself; every + /// other top-level member is an extension. + internal static let standardRequestBodyMembers: Set = [ + "clientPublicKey", "requests", "keyAccess", "policy", "algorithm", "schemaVersion", + ] + + /// A Rewrap request whose signed request token verified. + struct RewrapRequest: Sendable { + /// The compact JWT as received. + public let requestToken: String + /// `TDFKAS.requestTokenDigest(requestToken)`. + public let requestTokenDigest: Data + public let issuedAt: Date? + /// The token's `exp`, returned and not enforced: a KAS decides with its + /// own clock, and can still answer an expired request with a signed denial. + public let expiresAt: Date + /// The key the KAS rewraps each permitted share to. + public let clientPublicKey: P256.KeyAgreement.PublicKey + public let policies: [Policy] + /// Top-level `requestBody` members other than the standard ones, by name, + /// each re-serialized as JSON with sorted keys and unescaped slashes: + /// equal to the member as JSON, not byte-identical to how it was sent. + /// They are covered by the signature. + public let extensions: [String: Data] + + public struct Policy: Sendable { + public let policyId: String + /// The policy body as sent; the binding `TDFKAS.rewrap` checks is over + /// this text. + public let policyBase64: String + public let keyAccessObjects: [KeyAccessEntry] + } + + public struct KeyAccessEntry: Sendable { + public let id: String + public let keyAccessObject: TDFKeyAccessObject + } + } + + /// Verifies a received Rewrap body, `{"signed_request_token": ""}`, + /// under `signingPublicKey` (for an owner KAS, the bearer token's `cnf` key) + /// and parses its `requestBody`. + /// + /// Checks, in order: the body is at most 64 KiB; it holds a string + /// `signed_request_token` of three canonical (unpadded) base64url parts; the + /// header's `alg` is `ES256` and it has no `crit`; the raw 64-byte signature + /// verifies over `header.payload` as received; the claims hold a string + /// `requestBody`, a numeric `exp` and, if present, a numeric `iat`; no JSON + /// object anywhere repeats a member name; and `requestBody` holds a PEM P-256 + /// `clientPublicKey` and a non-empty `requests` array, each with + /// `policy.id`, a base64 `policy.body` and non-empty key access objects. + /// The token's `exp` is returned, not enforced. + /// - Throws: `TDFKASError.requestTooLarge`, `.malformedRewrapRequest`, + /// `.unsupportedRequestAlgorithm` or `.requestSignatureInvalid`. + static func verifyRewrapRequest( + body: Data, + signingPublicKey: P256.Signing.PublicKey, + ) throws -> RewrapRequest { + guard body.count <= maxRewrapRequestBytes else { + throw TDFKASError.requestTooLarge + } + guard let envelope = try? JSONSerialization.jsonObject(with: body) as? [String: Any], + !StrictJSON.hasDuplicateMembers(body), + let token = envelope["signed_request_token"] as? String + else { + throw TDFKASError.malformedRewrapRequest("signed_request_token") + } + let parts = token.split(separator: ".", omittingEmptySubsequences: false) + guard parts.count == 3, + let headerData = canonicalBase64URL(parts[0]), + let header = try? JSONSerialization.jsonObject(with: headerData) as? [String: Any], + !StrictJSON.hasDuplicateMembers(headerData) + else { + throw TDFKASError.malformedRewrapRequest("header") + } + guard header["crit"] == nil else { + throw TDFKASError.malformedRewrapRequest("crit") + } + guard let alg = header["alg"] as? String else { + throw TDFKASError.malformedRewrapRequest("alg") + } + guard alg == "ES256" else { + throw TDFKASError.unsupportedRequestAlgorithm(alg) + } + guard let signatureData = canonicalBase64URL(parts[2]) else { + throw TDFKASError.malformedRewrapRequest("signature") + } + guard signatureData.count == 64, + let signature = try? P256.Signing.ECDSASignature(rawRepresentation: signatureData), + signingPublicKey.isValidSignature(signature, for: Data("\(parts[0]).\(parts[1])".utf8)) + else { + throw TDFKASError.requestSignatureInvalid + } + guard let claimsData = canonicalBase64URL(parts[1]), + !StrictJSON.hasDuplicateMembers(claimsData), + let claims = try? JSONDecoder().decode(TokenClaims.self, from: claimsData) + else { + throw TDFKASError.malformedRewrapRequest("claims") + } + + let requestBodyData = Data(claims.requestBody.utf8) + guard let requestBody = try? JSONSerialization.jsonObject(with: requestBodyData) as? [String: Any], + !StrictJSON.hasDuplicateMembers(requestBodyData) + else { + throw TDFKASError.malformedRewrapRequest("requestBody") + } + guard let clientPEM = requestBody["clientPublicKey"] as? String, + let clientPublicKey = try? parseEphemeralPublicKey(clientPEM) + else { + throw TDFKASError.malformedRewrapRequest("clientPublicKey") + } + guard let standard = try? JSONDecoder().decode(StandardBody.self, from: requestBodyData), + !standard.requests.isEmpty + else { + throw TDFKASError.malformedRewrapRequest("requests") + } + let policies = try standard.requests.map { request in + guard Data(base64Encoded: request.policy.body) != nil else { + throw TDFKASError.malformedRewrapRequest("policy.body") + } + guard !request.keyAccessObjects.isEmpty else { + throw TDFKASError.malformedRewrapRequest("keyAccessObjects") + } + return RewrapRequest.Policy( + policyId: request.policy.id, + policyBase64: request.policy.body, + keyAccessObjects: request.keyAccessObjects.map { + RewrapRequest.KeyAccessEntry(id: $0.keyAccessObjectId, keyAccessObject: $0.keyAccessObject) + }, + ) + } + + var extensions: [String: Data] = [:] + for (name, value) in requestBody where !standardRequestBodyMembers.contains(name) { + guard let json = try? JSONSerialization.data( + withJSONObject: value, options: [.fragmentsAllowed, .sortedKeys, .withoutEscapingSlashes], + ) else { + throw TDFKASError.malformedRewrapRequest("extension") + } + extensions[name] = json + } + + return RewrapRequest( + requestToken: token, + requestTokenDigest: requestTokenDigest(token), + issuedAt: claims.iat.map { Date(timeIntervalSince1970: $0) }, + expiresAt: Date(timeIntervalSince1970: claims.exp), + clientPublicKey: clientPublicKey, + policies: policies, + extensions: extensions, + ) + } +} + +// MARK: - Wire types + +/// A JWS part decoded only if it is canonical base64url: no padding and no +/// stray bits, so one token has exactly one spelling and one digest. +private func canonicalBase64URL(_ part: Substring) -> Data? { + guard let data = Data(base64URLEncoded: part), data.base64URLEncodedString() == part else { + return nil + } + return data +} + +private struct TokenClaims: Decodable { + let requestBody: String + let exp: Double + let iat: Double? + + private enum CodingKeys: String, CodingKey { + case requestBody + case exp + case iat + } + + /// `iat` may be absent, but if present it must be a number (not `null`). + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + requestBody = try container.decode(String.self, forKey: .requestBody) + exp = try container.decode(Double.self, forKey: .exp) + iat = container.contains(.iat) ? try container.decode(Double.self, forKey: .iat) : nil + } +} + +private struct StandardBody: Decodable { + struct Request: Decodable { + struct Policy: Decodable { + let id: String + let body: String + } + + struct Wrapper: Decodable { + let keyAccessObjectId: String + let keyAccessObject: TDFKeyAccessObject + } + + let policy: Policy + let keyAccessObjects: [Wrapper] + } + + let requests: [Request] +} diff --git a/OpenTDFKit/TDF/TDFKASResponse.swift b/OpenTDFKit/TDF/TDFKASResponse.swift new file mode 100644 index 0000000..e71b527 --- /dev/null +++ b/OpenTDFKit/TDF/TDFKASResponse.swift @@ -0,0 +1,114 @@ +@preconcurrency import CryptoKit +import Foundation + +// MARK: - Build a Rewrap response (KAS side) + +public extension TDFKAS { + /// A key access object's outcome in a Rewrap response. + enum ResultStatus: String, Sendable { + case permit + case fail + } + + /// One key access object's result: a permit carries the share wrapped to the + /// client's key (`TDFKAS.rewrap`'s `wrappedKey`); a fail carries none. + struct KeyAccessResult: Sendable { + public let keyAccessObjectId: String + public let status: ResultStatus + public let kasWrappedKey: Data? + public let error: String? + /// Passed through to the client as is (for example an owner KAS's signed + /// decision record). + public let metadata: [String: KASRewrapClient.RewrapMetadataValue] + + public init( + keyAccessObjectId: String, + status: ResultStatus, + kasWrappedKey: Data?, + error: String?, + metadata: [String: KASRewrapClient.RewrapMetadataValue], + ) { + self.keyAccessObjectId = keyAccessObjectId + self.status = status + self.kasWrappedKey = kasWrappedKey + self.error = error + self.metadata = metadata + } + } + + /// The results for one policy request. + struct PolicyResponse: Sendable { + public let policyId: String + public let results: [KeyAccessResult] + + public init(policyId: String, results: [KeyAccessResult]) { + self.policyId = policyId + self.results = results + } + } + + /// Builds the Rewrap response body `KASRewrapClient` parses: + /// `{"sessionPublicKey": , "responses": [{"policyId", "results": + /// [{"keyAccessObjectId", "status", "kasWrappedKey", "error", "metadata"}]}]}`. + /// `status` is `permit` or `fail`, `kasWrappedKey` is standard base64, and + /// absent fields (and empty metadata) are omitted. + /// - Parameter sessionPublicKey: `TDFKAS.rewrap`'s session key; `nil` when + /// nothing was permitted. + /// - Throws: `TDFKASError.invalidResult` for a permit without a wrapped key + /// or without a session key, or a fail with a wrapped key. + static func rewrapResponseBody( + sessionPublicKey: P256.KeyAgreement.PublicKey?, + responses: [PolicyResponse], + ) throws -> Data { + let wire = try WireResponse( + sessionPublicKey: sessionPublicKey?.pemRepresentation, + responses: responses.map { response in + try WireResponse.Policy( + policyId: response.policyId, + results: response.results.map { result in + switch (result.status, result.kasWrappedKey) { + case (.permit, nil): + throw TDFKASError.invalidResult("permit without kasWrappedKey") + case (.permit, .some) where sessionPublicKey == nil: + throw TDFKASError.invalidResult("permit without sessionPublicKey") + case (.fail, .some): + throw TDFKASError.invalidResult("fail with kasWrappedKey") + default: + break + } + return WireResponse.Result( + keyAccessObjectId: result.keyAccessObjectId, + status: result.status.rawValue, + kasWrappedKey: result.kasWrappedKey?.base64EncodedString(), + error: result.error, + metadata: result.metadata.isEmpty ? nil : result.metadata, + ) + }, + ) + }, + ) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return try encoder.encode(wire) + } +} + +// MARK: - Wire types + +private struct WireResponse: Encodable { + struct Policy: Encodable { + let policyId: String + let results: [Result] + } + + struct Result: Encodable { + let keyAccessObjectId: String + let status: String + let kasWrappedKey: String? + let error: String? + let metadata: [String: KASRewrapClient.RewrapMetadataValue]? + } + + let sessionPublicKey: String? + let responses: [Policy] +} diff --git a/OpenTDFKit/TDF/TDFProcessor.swift b/OpenTDFKit/TDF/TDFProcessor.swift index 6fd3fe1..82a1e4b 100644 --- a/OpenTDFKit/TDF/TDFProcessor.swift +++ b/OpenTDFKit/TDF/TDFProcessor.swift @@ -2,16 +2,34 @@ import CryptoKit import Foundation public struct TDFKasInfo: Sendable { + /// The kind of key the KAS holds, which decides how the DEK is wrapped. + public enum KeyType: Sendable, Equatable { + /// RSA (2048 bits or more): a `wrapped` key access object, RSA-OAEP. + case rsa + /// EC P-256: an `ec-wrapped` key access object in the go SDK / + /// opentdf-platform scheme. Needs a `kid` and AES-256. + case ecP256 + } + public let url: URL + /// The KAS public key, PEM SubjectPublicKeyInfo, of the kind `keyType` names. public let publicKeyPEM: String public let kid: String? public let schemaVersion: String? - - public init(url: URL, publicKeyPEM: String, kid: String? = nil, schemaVersion: String? = nil) { + public let keyType: KeyType + + public init( + url: URL, + publicKeyPEM: String, + kid: String? = nil, + schemaVersion: String? = nil, + keyType: KeyType = .rsa, + ) { self.url = url self.publicKeyPEM = publicKeyPEM self.kid = kid self.schemaVersion = schemaVersion + self.keyType = keyType } } @@ -97,6 +115,7 @@ public struct TDFEncryptor { configuration: TDFEncryptionConfiguration, chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, ) throws -> TDFEncryptionResult { + try validate(configuration) let symmetricKey = try TDFCrypto.generateSymmetricKey(size: configuration.keySize) let payloadData: Data let streamingResult: StreamingTDFCrypto.StreamingEncryptionResult @@ -112,11 +131,7 @@ public struct TDFEncryptor { ) } - let policyBinding = TDFCrypto.policyBinding(policy: configuration.policy.json, symmetricKey: symmetricKey) - let wrappedKey = try TDFCrypto.wrapSymmetricKeyWithRSA( - publicKeyPEM: configuration.kas.publicKeyPEM, - symmetricKey: symmetricKey, - ) + let kasObject = try makeKeyAccessObject(kas: configuration.kas, policy: configuration.policy, symmetricKey: symmetricKey) let method = TDFMethodDescriptor( algorithm: configuration.keySize.algorithm, @@ -147,19 +162,6 @@ public struct TDFEncryptor { segments: segments, ) - let kasObject = TDFKeyAccessObject( - type: .wrapped, - url: configuration.kas.url.absoluteString, - protocolValue: .kas, - wrappedKey: wrappedKey, - policyBinding: policyBinding, - encryptedMetadata: nil, - kid: configuration.kas.kid, - sid: nil, - schemaVersion: configuration.kas.schemaVersion ?? "1.0", - ephemeralPublicKey: nil, - ) - let encryptionInformation = TDFEncryptionInformation( type: .split, keyAccess: [kasObject], @@ -205,6 +207,7 @@ public struct TDFEncryptor { configuration: TDFEncryptionConfiguration, segmentSizes: [Int], ) throws -> TDFEncryptionResult { + try validate(configuration) guard !segmentSizes.isEmpty else { throw StreamingCryptoError.invalidSegmentSize } @@ -224,11 +227,7 @@ public struct TDFEncryptor { ) } - let policyBinding = TDFCrypto.policyBinding(policy: configuration.policy.json, symmetricKey: symmetricKey) - let wrappedKey = try TDFCrypto.wrapSymmetricKeyWithRSA( - publicKeyPEM: configuration.kas.publicKeyPEM, - symmetricKey: symmetricKey, - ) + let kasObject = try makeKeyAccessObject(kas: configuration.kas, policy: configuration.policy, symmetricKey: symmetricKey) let method = TDFMethodDescriptor( algorithm: configuration.keySize.algorithm, @@ -259,19 +258,6 @@ public struct TDFEncryptor { segments: segments, ) - let kasObject = TDFKeyAccessObject( - type: .wrapped, - url: configuration.kas.url.absoluteString, - protocolValue: .kas, - wrappedKey: wrappedKey, - policyBinding: policyBinding, - encryptedMetadata: nil, - kid: configuration.kas.kid, - sid: nil, - schemaVersion: configuration.kas.schemaVersion ?? "1.0", - ephemeralPublicKey: nil, - ) - let encryptionInformation = TDFEncryptionInformation( type: .split, keyAccess: [kasObject], @@ -312,6 +298,7 @@ public struct TDFEncryptor { } public func encrypt(plaintext: Data, configuration: TDFEncryptionConfiguration) throws -> TDFEncryptionResult { + try validate(configuration) let symmetricKey = try TDFCrypto.generateSymmetricKey(size: configuration.keySize) let (iv, ciphertext, tag) = try TDFCrypto.encryptPayload(plaintext: plaintext, symmetricKey: symmetricKey) @@ -349,6 +336,7 @@ public struct TDFEncryptor { configuration: TDFEncryptionConfiguration, segmentSize: Int, ) throws -> TDFEncryptionResult { + try validate(configuration) guard segmentSize > 0 else { throw StreamingCryptoError.invalidSegmentSize } @@ -398,6 +386,65 @@ public struct TDFEncryptor { ) } + /// Refuses a configuration no KAS could rewrap, before the input is read or + /// anything is written: the KAS public key must load as its declared + /// `keyType` (a `TDFCryptoError` otherwise), and an `.ecP256` KAS needs a + /// `kid` (the platform finds EC keys by `kid` alone) and AES-256 (the go SDK + /// only reconstructs a 32-byte key, and `TDFKAS.rewrap` only accepts + /// 32-byte shares). + private func validate(_ configuration: TDFEncryptionConfiguration) throws { + let kas = configuration.kas + switch kas.keyType { + case .rsa: + _ = try TDFCrypto.loadRSAPublicKey(fromPEM: kas.publicKeyPEM) + case .ecP256: + _ = try TDFCrypto.loadECPublicKeyP256(fromPEM: kas.publicKeyPEM) + guard let kid = kas.kid, !kid.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw TDFEncryptError.ecKasRequiresKeyID + } + guard configuration.keySize == .bits256 else { + throw TDFEncryptError.ecKasRequiresAES256 + } + } + } + + /// Wraps the DEK to the KAS and binds the policy (spec form) into one key + /// access object: `wrapped` (RSA-OAEP) or `ec-wrapped` (the go SDK scheme, + /// PEM ephemeral key) by `kas.keyType`. + private func makeKeyAccessObject( + kas: TDFKasInfo, + policy: TDFPolicy, + symmetricKey: SymmetricKey, + ) throws -> TDFKeyAccessObject { + let policyBinding = TDFCrypto.policyBinding(policy: policy.json, symmetricKey: symmetricKey) + let type: TDFKeyAccessObject.AccessType + let wrappedKey: String + let ephemeralPublicKey: String? + switch kas.keyType { + case .rsa: + type = .wrapped + wrappedKey = try TDFCrypto.wrapSymmetricKeyWithRSA(publicKeyPEM: kas.publicKeyPEM, symmetricKey: symmetricKey) + ephemeralPublicKey = nil + case .ecP256: + let wrapped = try TDFCrypto.wrapSymmetricKeyWithECForKAS(publicKeyPEM: kas.publicKeyPEM, symmetricKey: symmetricKey) + type = .ecWrapped + wrappedKey = wrapped.wrappedKey + ephemeralPublicKey = wrapped.ephemeralPublicKeyPEM + } + return TDFKeyAccessObject( + type: type, + url: kas.url.absoluteString, + protocolValue: .kas, + wrappedKey: wrappedKey, + policyBinding: policyBinding, + encryptedMetadata: nil, + kid: kas.kid, + sid: nil, + schemaVersion: kas.schemaVersion ?? "1.0", + ephemeralPublicKey: ephemeralPublicKey, + ) + } + /// Wrap the DEK, bind the policy and assemble the manifest around an encrypted payload. private func makeResult( payloadData: Data, @@ -409,8 +456,7 @@ public struct TDFEncryptor { iv: Data, tag: Data, ) throws -> TDFEncryptionResult { - let policyBinding = TDFCrypto.policyBinding(policy: configuration.policy.json, symmetricKey: symmetricKey) - let wrappedKey = try TDFCrypto.wrapSymmetricKeyWithRSA(publicKeyPEM: configuration.kas.publicKeyPEM, symmetricKey: symmetricKey) + let kasObject = try makeKeyAccessObject(kas: configuration.kas, policy: configuration.policy, symmetricKey: symmetricKey) let rootSignature = TDFCrypto.rootSignatureBase64( rawSegmentSignatures: rawSegmentSignatures, @@ -433,19 +479,6 @@ public struct TDFEncryptor { segments: segments, ) - let kasObject = TDFKeyAccessObject( - type: .wrapped, - url: configuration.kas.url.absoluteString, - protocolValue: .kas, - wrappedKey: wrappedKey, - policyBinding: policyBinding, - encryptedMetadata: nil, - kid: configuration.kas.kid, - sid: nil, - schemaVersion: configuration.kas.schemaVersion ?? "1.0", - ephemeralPublicKey: nil, - ) - let encryptionInformation = TDFEncryptionInformation( type: .split, keyAccess: [kasObject], @@ -718,9 +751,9 @@ public struct TDFDecryptor { private func segmentSignature(_ encryptedSegment: Data, algorithm: String, symmetricKey: SymmetricKey) throws -> Data { switch algorithm.uppercased() { case "GMAC": - return Data(encryptedSegment.suffix(16)) + Data(encryptedSegment.suffix(16)) case "HS256": - return Data(HMAC.authenticationCode(for: encryptedSegment, using: symmetricKey)) + Data(HMAC.authenticationCode(for: encryptedSegment, using: symmetricKey)) default: throw TDFDecryptError.unsupportedIntegrityAlgorithm(algorithm) } @@ -737,6 +770,23 @@ public struct TDFDecryptor { } } +/// A configuration `TDFEncryptor` refuses before encrypting. +public enum TDFEncryptError: Error, CustomStringConvertible, Equatable { + /// An `.ecP256` KAS has no `kid`; no platform KAS could find its key. + case ecKasRequiresKeyID + /// An `.ecP256` KAS with a key size other than AES-256. + case ecKasRequiresAES256 + + public var description: String { + switch self { + case .ecKasRequiresKeyID: + "An EC P-256 KAS needs a key ID (kid); a KAS finds EC keys by kid" + case .ecKasRequiresAES256: + "An EC P-256 KAS needs AES-256; other OpenTDF SDKs only read a 32-byte key" + } + } +} + public enum TDFDecryptError: Error, CustomStringConvertible, Equatable { case missingKeyAccess case malformedPayload diff --git a/OpenTDFKitCLI/main.swift b/OpenTDFKitCLI/main.swift index d2b6d4c..16cda6a 100644 --- a/OpenTDFKitCLI/main.swift +++ b/OpenTDFKitCLI/main.swift @@ -151,13 +151,14 @@ struct OpenTDFKitCLI { or TDF_OAUTH_TOKEN_PATH); PLATFORMURL selects the well-known root. Features (for supports command): - nano, nano_ecdsa, nano_collection, tdf, json, cbor, hexless, etc. + nano, nano_ecdsa, nano_collection, tdf, json, cbor, hexless, ecwrap, etc. Environment Variables: CLIENTID OAuth client ID CLIENTSECRET OAuth client secret KASURL KAS endpoint URL PLATFORMURL Platform endpoint URL + XT_WITH_ECWRAP true: tdf encrypt wraps to the KAS EC P-256 key (ec-wrapped) Examples: OpenTDFKitCLI encrypt input.txt output.ntdf nano @@ -549,13 +550,19 @@ struct OpenTDFKitCLI { // MARK: - Standard TDF Helpers - /// Build Standard TDF encryption config. + /// Build the TDF encryption config. /// - /// KAS RSA public key resolution: - /// 1. `TDF_KAS_PUBLIC_KEY` / `TDF_KAS_PUBLIC_KEY_PATH` (offline override) + /// `XT_WITH_ECWRAP=true` (the xtest `tdf-ecwrap` container) wraps the DEK to + /// the KAS's EC P-256 key as an `ec-wrapped` key access object; otherwise to + /// its RSA key as `wrapped`. + /// + /// KAS public key resolution: + /// 1. `TDF_KAS_PUBLIC_KEY` / `TDF_KAS_PUBLIC_KEY_PATH` (offline override; its + /// kind must match the mode, and EC needs `TDF_KAS_KID`) /// 2. Live fetch via client-credentials + Connect/REST PublicKey (Stage-1 / xtest) private static func buildTDFConfiguration(for inputURL: URL) async throws -> TDFEncryptionConfiguration { let env = ProcessInfo.processInfo.environment + let ecWrap = env["XT_WITH_ECWRAP"] == "true" guard let kasURLString = env["TDF_KAS_URL"] ?? env["KASURL"], let kasURL = URL(string: kasURLString) else { throw CLIError.missingEnvironmentVariable("TDF_KAS_URL or KASURL") @@ -580,16 +587,26 @@ struct OpenTDFKitCLI { clientID: clientID, clientSecret: clientSecret, ) - let fetched = try await Commands.fetchKASRSAPublicKey( - kasURL: kasURL, - platformURL: platformURL, - token: token, - ) - publicKeyPEM = fetched.pem - if kid == nil { - kid = fetched.kid + if ecWrap { + let fetched = try await Commands.fetchKASPublicKey(kasURL: kasURL, token: token) + publicKeyPEM = try P256.KeyAgreement.PublicKey(compressedRepresentation: fetched.compressedKey) + .pemRepresentation + if kid == nil { + kid = fetched.kid + } + print("Fetched KAS EC P-256 public key (kid=\(kid ?? "none"))") + } else { + let fetched = try await Commands.fetchKASRSAPublicKey( + kasURL: kasURL, + platformURL: platformURL, + token: token, + ) + publicKeyPEM = fetched.pem + if kid == nil { + kid = fetched.kid + } + print("Fetched KAS RSA public key (kid=\(kid ?? "none"))") } - print("Fetched KAS RSA public key (kid=\(kid ?? "none"))") } let policyData = try loadPolicyData() @@ -600,6 +617,7 @@ struct OpenTDFKitCLI { publicKeyPEM: publicKeyPEM, kid: kid, schemaVersion: env["TDF_KAS_SCHEMA_VERSION"], + keyType: ecWrap ? .ecP256 : .rsa, ) let policy = try TDFPolicy(json: policyData) @@ -758,10 +776,15 @@ struct OpenTDFKitCLI { return 0 case "connectrpc": return 0 - case "tdf-ecwrap", "assertions", "assertion_verification", + case "ecwrap", "tdf-ecwrap": + // XT_WITH_ECWRAP=true: encrypt writes an ec-wrapped key access object + // (go SDK scheme) to the KAS's P-256 key; decrypt always rewraps with + // an EC P-256 session key. + return 0 + case "assertions", "assertion_verification", "attribute_traversal", "audit_logging", "autoconfigure", "better-messages-2024", "bulk_rewrap", "dpop", "dpop_nonce_challenge", - "ecwrap", "hexaflexible", "kasallowlist", "key_management", + "hexaflexible", "kasallowlist", "key_management", "mechanism-rsa-4096", "mechanism-ec-curves-384-521", "mechanism-xwing", "mechanism-secpmlkem", "mechanism-mlkem", "nano_attribute_bug", "nano_policymode_plaintext", "ns_grants", diff --git a/OpenTDFKitTests/KASRewrapMatchingTests.swift b/OpenTDFKitTests/KASRewrapMatchingTests.swift new file mode 100644 index 0000000..b8bcf14 --- /dev/null +++ b/OpenTDFKitTests/KASRewrapMatchingTests.swift @@ -0,0 +1,99 @@ +@preconcurrency import CryptoKit +import Foundation +@testable import OpenTDFKit +import XCTest + +/// Path-aware key access object matching: a platform KAS and owner KASs share +/// one host, so a client selects only the objects whose URL is its own KAS, +/// path included (`/kas` counts as no path). +final class KASRewrapMatchingTests: XCTestCase { + private static let owner = "https://platform.arkavo.net/owner-kas/v1/routes/01HZXK3Q8R4M5N6P7Q8R9S0T1V" + + func testPlatformClientSelectsPlatformKAOsOnly() throws { + XCTAssertEqual( + try Self.selected(by: "https://platform.arkavo.net", + from: ["https://platform.arkavo.net/kas", "https://platform.arkavo.net", Self.owner]), + ["https://platform.arkavo.net/kas", "https://platform.arkavo.net"], + ) + } + + func testKasPathClientSelectsPlatformKAOsOnly() throws { + XCTAssertEqual( + try Self.selected(by: "https://platform.arkavo.net/kas", + from: ["https://platform.arkavo.net/kas", "https://platform.arkavo.net", Self.owner]), + ["https://platform.arkavo.net/kas", "https://platform.arkavo.net"], + ) + } + + func testOwnerClientSelectsOwnKAOOnly() throws { + XCTAssertEqual( + try Self.selected(by: Self.owner, + from: ["https://platform.arkavo.net/kas", "https://platform.arkavo.net", Self.owner]), + [Self.owner], + ) + } + + func testTrailingSlashesIgnored() throws { + XCTAssertEqual( + try Self.selected(by: "https://platform.arkavo.net", from: ["https://platform.arkavo.net/kas/"]), + ["https://platform.arkavo.net/kas/"], + ) + XCTAssertEqual(try Self.selected(by: Self.owner, from: [Self.owner + "/"]), [Self.owner + "/"]) + } + + func testPathIsCaseSensitiveHostIsNot() throws { + XCTAssertEqual( + try Self.selected(by: "https://platform.arkavo.net", from: ["https://PLATFORM.arkavo.net/kas"]), + ["https://PLATFORM.arkavo.net/kas"], + ) + let shouted = Self.owner.replacingOccurrences(of: "/owner-kas/", with: "/OWNER-KAS/") + XCTAssertEqual(try Self.selected(by: Self.owner, from: [shouted]), []) + } + + /// The cost the spec names: a KAS mounted under another prefix needs that + /// prefix in the client's configured URL. + func testOtherPrefixDoesNotMatchPathlessClient() throws { + XCTAssertEqual(try Self.selected(by: "https://platform.arkavo.net", + from: ["https://platform.arkavo.net/api/kas"]), []) + XCTAssertEqual(try Self.selected(by: "https://platform.arkavo.net/api/kas", + from: ["https://platform.arkavo.net/api/kas"]), + ["https://platform.arkavo.net/api/kas"]) + } + + /// Percent-encoded unreserved characters are the same path (RFC 3986 6.2.2.2); + /// an encoded slash is not. + func testPercentEncodedUnreservedPathMatches() throws { + XCTAssertEqual(try Self.selected(by: "https://platform.arkavo.net", + from: ["https://platform.arkavo.net/%6bas", "https://platform.arkavo.net/%6Bas"]), + ["https://platform.arkavo.net/%6bas", "https://platform.arkavo.net/%6Bas"]) + let encodedO = Self.owner.replacingOccurrences(of: "/owner-kas/", with: "/%6Fwner-kas/") + XCTAssertEqual(try Self.selected(by: Self.owner, from: [encodedO]), [encodedO]) + let encodedSlash = Self.owner.replacingOccurrences(of: "/owner-kas/v1/", with: "/owner-kas%2Fv1/") + XCTAssertEqual(try Self.selected(by: Self.owner, from: [encodedSlash]), []) + } + + // MARK: - Helpers + + /// URLs of the key access objects a client configured with `uri` selects. + static func selected(by uri: String, from urls: [String]) throws -> [String] { + let client = try KASRewrapClient(configuration: .forKasConnect(uri), oauthToken: "token") + return try client.keyAccessObjects(in: manifest(kaoURLs: urls)).map(\.url) + } + + static func manifest(kaoURLs: [String]) throws -> TDFManifest { + let rsaPEM = try TDFSegmentedPayloadTests.makeRSAPublicKeyPEM() + let kas = try TDFKasInfo(url: XCTUnwrap(URL(string: "https://kas.example.com")), publicKeyPEM: rsaPEM) + let policy = try TDFPolicy(json: Data(#"{"uuid":"u","body":{"dataAttributes":[],"dissem":["a@b.c"]}}"#.utf8)) + var manifest = try TDFEncryptor().encrypt( + plaintext: Data("x".utf8), + configuration: TDFEncryptionConfiguration(kas: kas, policy: policy), + ).container.manifest + let template = manifest.encryptionInformation.keyAccess[0] + manifest.encryptionInformation.keyAccess = kaoURLs.map { url in + var kao = template + kao.url = url + return kao + } + return manifest + } +} diff --git a/OpenTDFKitTests/KASRewrapPendingTests.swift b/OpenTDFKitTests/KASRewrapPendingTests.swift new file mode 100644 index 0000000..36948cf --- /dev/null +++ b/OpenTDFKitTests/KASRewrapPendingTests.swift @@ -0,0 +1,629 @@ +@preconcurrency import CryptoKit +import Foundation +@testable import OpenTDFKit +import XCTest + +/// `KASRewrapClient`'s path for a KAS that may answer later (an owner KAS): +/// prepare a signed request, submit it, and poll a pending answer. +final class KASRewrapPendingTests: XCTestCase { + static let ownerURL = "https://platform.arkavo.net/owner-kas/v1/routes/01HZXK3Q8R4M5N6P7Q8R9S0T1V" + let signingKey = P256.Signing.PrivateKey() + let clientKey = P256.KeyAgreement.PrivateKey() + let kasKey = P256.KeyAgreement.PrivateKey() + + // MARK: - prepareRewrap + + func testPreparedRequestVerifiesOnThePhone() throws { + let expiresAt = Date().addingTimeInterval(900) + let prepared = try makeClient().prepareRewrap( + manifest: makeManifest(), clientPrivateKey: clientKey, options: .init(expiresAt: expiresAt), + ) + let request = try TDFKAS.verifyRewrapRequest(body: prepared.body, signingPublicKey: signingKey.publicKey) + XCTAssertEqual(request.requestTokenDigest, prepared.requestTokenDigest) + XCTAssertEqual(request.requestToken, prepared.requestToken) + XCTAssertEqual(request.expiresAt, prepared.expiresAt) + XCTAssertEqual(Int(prepared.expiresAt.timeIntervalSince1970), Int(expiresAt.timeIntervalSince1970)) + XCTAssertEqual(request.clientPublicKey.x963Representation, clientKey.publicKey.x963Representation) + } + + func testPolicyForwardedVerbatim() throws { + let manifest = try makeManifest() + let prepared = try makeClient().prepareRewrap(manifest: manifest, clientPrivateKey: clientKey) + let request = try TDFKAS.verifyRewrapRequest(body: prepared.body, signingPublicKey: signingKey.publicKey) + XCTAssertEqual(request.policies.first?.policyBase64, manifest.encryptionInformation.policy) + } + + /// Signed with the init `signingKey` (an owner KAS's `cnf` key), not the + /// client's ECDH key as `rewrapTDF` does. + func testSignedWithInitSigningKeyNotClientKey() throws { + let prepared = try makeClient().prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + let clientSigningKey = try P256.Signing.PrivateKey(rawRepresentation: clientKey.rawRepresentation) + XCTAssertThrowsError(try TDFKAS.verifyRewrapRequest( + body: prepared.body, signingPublicKey: clientSigningKey.publicKey, + )) { + XCTAssertEqual($0 as? TDFKASError, .requestSignatureInvalid) + } + } + + func testDefaultExpIsSixtySeconds() throws { + let prepared = try makeClient().prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + let request = try TDFKAS.verifyRewrapRequest(body: prepared.body, signingPublicKey: signingKey.publicKey) + let issuedAt = try XCTUnwrap(request.issuedAt) + XCTAssertEqual(request.expiresAt.timeIntervalSince(issuedAt), 60) + } + + func testCallerExp() throws { + let expiresAt = Date(timeIntervalSince1970: (Date().timeIntervalSince1970 + 900).rounded(.down)) + let prepared = try makeClient().prepareRewrap( + manifest: makeManifest(), clientPrivateKey: clientKey, options: .init(expiresAt: expiresAt), + ) + let request = try TDFKAS.verifyRewrapRequest(body: prepared.body, signingPublicKey: signingKey.publicKey) + XCTAssertEqual(request.expiresAt, expiresAt) + } + + func testPastExpRefused() throws { + XCTAssertThrowsError(try makeClient().prepareRewrap( + manifest: makeManifest(), clientPrivateKey: clientKey, + options: .init(expiresAt: Date().addingTimeInterval(-1)), + )) { assertInvalidOptions($0) } + } + + func testExtensionCoveredBySignature() throws { + let json = Data(#"{"v":1,"attempt_id":"QUJD","nonce":"REVG","tdf_digest":"R0hJ"}"#.utf8) + let prepared = try makeClient().prepareRewrap( + manifest: makeManifest(), clientPrivateKey: clientKey, + options: .init(requestBodyExtension: .init(name: "arkavo", json: json)), + ) + let request = try TDFKAS.verifyRewrapRequest(body: prepared.body, signingPublicKey: signingKey.publicKey) + let sent = try XCTUnwrap(JSONSerialization.jsonObject(with: json) as? NSDictionary) + let received = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(request.extensions["arkavo"])) + as? NSDictionary) + XCTAssertEqual(received, sent) + } + + func testExtensionNameCollisionRefused() throws { + for name in ["clientPublicKey", "requests", "keyAccess", "policy", "algorithm", "schemaVersion"] { + XCTAssertThrowsError(try makeClient().prepareRewrap( + manifest: makeManifest(), clientPrivateKey: clientKey, + options: .init(requestBodyExtension: .init(name: name, json: Data("{}".utf8))), + )) { assertInvalidOptions($0) } + } + } + + func testExtensionMustBeJSON() throws { + XCTAssertThrowsError(try makeClient().prepareRewrap( + manifest: makeManifest(), clientPrivateKey: clientKey, + options: .init(requestBodyExtension: .init(name: "arkavo", json: Data("not json".utf8))), + )) { assertInvalidOptions($0) } + } + + func testOnlyThisKASKAOsSent() throws { + var manifest = try makeManifest() + var platformKAO = manifest.encryptionInformation.keyAccess[0] + platformKAO.url = "https://platform.arkavo.net/kas" + manifest.encryptionInformation.keyAccess.insert(platformKAO, at: 0) + let prepared = try makeClient().prepareRewrap(manifest: manifest, clientPrivateKey: clientKey) + let request = try TDFKAS.verifyRewrapRequest(body: prepared.body, signingPublicKey: signingKey.publicKey) + XCTAssertEqual(request.policies.first?.keyAccessObjects.map(\.keyAccessObject.url), [Self.ownerURL]) + } + + // MARK: - submitRewrap / pollRewrap + + func testImmediate200IsAnswered() async throws { + let encryption = try makeEncryption() + let transport = try ScriptedTransport([.init(200, body: permitBody(for: encryption, plusFail: true))]) + let client = try makeClient(transport: transport) + let prepared = try client.prepareRewrap(manifest: encryption.container.manifest, clientPrivateKey: clientKey) + guard case let .answered(answer) = try await client.submitRewrap(prepared) else { + return XCTFail("expected answered") + } + XCTAssertEqual(answer.requestTokenDigest, prepared.requestTokenDigest) + XCTAssertEqual(answer.results.map(\.status), ["permit", "fail"]) + XCTAssertEqual(answer.results[1].error, "ACCESS_DENIED") + XCTAssertNotNil(answer.sessionPublicKey) + } + + func testDenyOnlyAnswerParses() async throws { + let deny = try TDFKAS.rewrapResponseBody(sessionPublicKey: nil, responses: [ + .init(policyId: "policy", results: [ + .init(keyAccessObjectId: "kao-0", status: .fail, kasWrappedKey: nil, error: "ACCESS_REVOKED", + metadata: ["arkavo.decision": .string("c2lnbmVk")]), + ]), + ]) + let client = try makeClient(transport: ScriptedTransport([.init(200, body: deny)])) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + guard case let .answered(answer) = try await client.submitRewrap(prepared) else { + return XCTFail("expected answered") + } + XCTAssertNil(answer.sessionPublicKey) + XCTAssertEqual(answer.results.first?.metadata["arkavo.decision"], .string("c2lnbmVk")) + XCTAssertEqual(answer.results.first?.sid, nil) + } + + func testPendingThenAnswered() async throws { + let encryption = try makeEncryption() + let transport = try ScriptedTransport([ + .init(202, headers: ["Location": "/owner-kas/v1/requests/abc", "Retry-After": "3"]), + .init(202, headers: ["Retry-After": "5"]), + .init(200, body: permitBody(for: encryption)), + ]) + let clock = TestClock() + let client = try makeClient(transport: transport, clock: clock) + let prepared = try client.prepareRewrap(manifest: encryption.container.manifest, clientPrivateKey: clientKey) + guard case let .pending(pending) = try await client.submitRewrap(prepared) else { + return XCTFail("expected pending") + } + XCTAssertEqual(pending.location.absoluteString, "https://platform.arkavo.net/owner-kas/v1/requests/abc") + XCTAssertEqual(pending.retryAfter, 3) + guard case .answered = try await client.pollRewrap(pending, until: clock.start.addingTimeInterval(600)) else { + return XCTFail("expected answered") + } + XCTAssertEqual(clock.sleeps, [3, 5]) + let requests = await transport.requests + XCTAssertEqual(requests.map(\.method), ["POST", "GET", "GET"]) + for poll in requests.dropFirst() { + XCTAssertEqual(poll.url, "https://platform.arkavo.net/owner-kas/v1/requests/abc") + XCTAssertEqual(poll.authorization, "Bearer owner-kas-token") + XCTAssertNil(poll.body) + } + } + + func testGoneIsExpired() async throws { + let outcome = try await pollOutcome(after: [.init(410)]) + guard case .expired = outcome else { return XCTFail("expected expired, got \(outcome)") } + } + + func test404AfterExpIsExpired() async throws { + let outcome = try await pollOutcome(after: [.init(404)], retryAfter: "60", expiresIn: 60) + guard case .expired = outcome else { return XCTFail("expected expired, got \(outcome)") } + } + + func test404BeforeExpThrows() async throws { + do { + let outcome = try await pollOutcome(after: [.init(404)], retryAfter: "30", expiresIn: 900) + XCTFail("expected a throw, got \(outcome)") + } catch let KASRewrapError.httpError(status, _) { + XCTAssertEqual(status, 404) + } + } + + /// When the next wait would pass the deadline, the client sleeps to the + /// deadline and polls once more, then hands back the handle. + func testDeadlineReachedReturnsHandleAndResumes() async throws { + let encryption = try makeEncryption() + let transport = try ScriptedTransport([ + .init(202, headers: ["Location": "/owner-kas/v1/requests/abc", "Retry-After": "10"]), + .init(202, headers: ["Retry-After": "10"]), + .init(200, body: permitBody(for: encryption)), + ]) + let clock = TestClock() + let client = try makeClient(transport: transport, clock: clock) + let prepared = try client.prepareRewrap(manifest: encryption.container.manifest, clientPrivateKey: clientKey) + guard case let .pending(pending) = try await client.submitRewrap(prepared) else { + return XCTFail("expected pending") + } + guard case let .deadlineReached(handle) = try await client.pollRewrap( + pending, until: clock.start.addingTimeInterval(5), + ) else { + return XCTFail("expected deadlineReached") + } + XCTAssertEqual(clock.sleeps, [5], "slept only to the deadline") + let methods = await transport.requests.map(\.method) + XCTAssertEqual(methods, ["POST", "GET"], "one last poll at the deadline") + guard case .answered = try await client.pollRewrap(handle, until: clock.start.addingTimeInterval(100)) else { + return XCTFail("expected answered after resuming") + } + XCTAssertEqual(clock.sleeps, [5, 10]) + } + + /// An iPhone suspended mid-wait wakes after the deadline: no poll is sent. + func testOversleepPastDeadlineDoesNotPoll() async throws { + let transport = ScriptedTransport([ + .init(202, headers: ["Location": "/owner-kas/v1/requests/abc", "Retry-After": "2"]), + ]) + let clock = TestClock(oversleep: 3) + let client = try makeClient(transport: transport, clock: clock) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + guard case let .pending(pending) = try await client.submitRewrap(prepared) else { + return XCTFail("expected pending") + } + guard case .deadlineReached = try await client.pollRewrap(pending, until: clock.start.addingTimeInterval(5)) + else { + return XCTFail("expected deadlineReached") + } + let count = await transport.requests.count + XCTAssertEqual(count, 1, "only the POST; no poll after the deadline") + } + + func testPollTimeoutClampedToDeadline() async throws { + let transport = ScriptedTransport([ + .init(202, headers: ["Location": "/owner-kas/v1/requests/abc", "Retry-After": "2"]), + .init(202, headers: ["Retry-After": "60"]), + .init(202, headers: ["Retry-After": "60"]), + ]) + let clock = TestClock() + let client = try makeClient(transport: transport, clock: clock) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + guard case let .pending(pending) = try await client.submitRewrap(prepared) else { + return XCTFail("expected pending") + } + _ = try await client.pollRewrap(pending, until: clock.start.addingTimeInterval(10)) + let timeouts = await transport.requests.dropFirst().map(\.timeout) + XCTAssertEqual(timeouts, [8, 1], "8 s left at the first poll; the floor of 1 s at the deadline") + } + + func testRewrapDefaultDeadlineIsExpired() async throws { + let clock = TestClock() + let transport = ScriptedTransport([ + .init(202, headers: ["Location": "/owner-kas/v1/requests/abc", "Retry-After": "60"]), + .init(202, headers: ["Retry-After": "60"]), + ]) + let outcome = try await makeClient(transport: transport, clock: clock).rewrap( + manifest: makeManifest(), clientPrivateKey: clientKey, + options: .init(expiresAt: clock.start.addingTimeInterval(30)), + ) + guard case .expired = outcome else { return XCTFail("expected expired, got \(outcome)") } + } + + func testPollRefusesHandleFromAnotherClient() async throws { + let ownerTransport = ScriptedTransport([.init(202, headers: ["Location": "/owner-kas/v1/requests/abc"])]) + let owner = try makeClient(transport: ownerTransport) + let prepared = try owner.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + guard case let .pending(pending) = try await owner.submitRewrap(prepared) else { + return XCTFail("expected pending") + } + let otherTransport = ScriptedTransport([.init(200)]) + let other = try KASRewrapClient( + configuration: .forKasConnect("https://other.example/owner-kas/v1/routes/01HZXK3Q8R4M5N6P7Q8R9S0T1V"), + oauthToken: "other-token", transport: otherTransport, signingKey: signingKey, + sleeper: { _ in }, now: { Date() }, + ) + do { + _ = try await other.pollRewrap(pending, until: Date().addingTimeInterval(600)) + XCTFail("expected unsafeLocation") + } catch KASRewrapError.unsafeLocation { + let count = await otherTransport.requests.count + XCTAssertEqual(count, 0, "the other client's bearer goes nowhere") + } + } + + func testPoll202WithNewLocationIgnored() async throws { + let encryption = try makeEncryption() + let transport = try ScriptedTransport([ + .init(202, headers: ["Location": "/owner-kas/v1/requests/abc", "Retry-After": "1"]), + .init(202, headers: ["Location": "https://evil.example/x", "Retry-After": "1"]), + .init(200, body: permitBody(for: encryption)), + ]) + let client = try makeClient(transport: transport) + let prepared = try client.prepareRewrap(manifest: encryption.container.manifest, clientPrivateKey: clientKey) + guard case let .pending(pending) = try await client.submitRewrap(prepared) else { + return XCTFail("expected pending") + } + guard case .answered = try await client.pollRewrap(pending, until: Date().addingTimeInterval(600)) else { + return XCTFail("expected answered") + } + let urls = await transport.requests.dropFirst().map(\.url) + XCTAssertEqual(urls, Array(repeating: "https://platform.arkavo.net/owner-kas/v1/requests/abc", count: 2)) + } + + func test403IsHTTPErrorNotDenial() async throws { + let client = try makeClient(transport: ScriptedTransport([.init(403, body: Data("blocked".utf8))])) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + do { + _ = try await client.submitRewrap(prepared) + XCTFail("expected a throw") + } catch let KASRewrapError.httpError(status, _) { + XCTAssertEqual(status, 403) + } + do { + _ = try await pollOutcome(after: [.init(403)]) + XCTFail("expected a throw") + } catch let KASRewrapError.httpError(status, _) { + XCTAssertEqual(status, 403) + } + } + + func testEmptyAnswerThrows() async throws { + for body in [#"{"responses":[]}"#, + #"{"responses":[{"policyId":"policy","results":[{"keyAccessObjectId":"kao-7","status":"fail"}]}]}"#] + { + let client = try makeClient(transport: ScriptedTransport([.init(200, body: Data(body.utf8))])) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + do { + _ = try await client.submitRewrap(prepared) + XCTFail("expected emptyResponse for \(body)") + } catch KASRewrapError.emptyResponse {} + } + } + + func testMalformedWrappedKeyKeepsResult() async throws { + let session = P256.KeyAgreement.PrivateKey().publicKey.pemRepresentation + let object: [String: Any] = [ + "sessionPublicKey": session, + "responses": [["policyId": "policy", "results": [ + ["keyAccessObjectId": "kao-0", "status": "permit", "kasWrappedKey": "!!!", + "metadata": ["arkavo.decision": "ZGVj"]], + ]]], + ] + let client = try makeClient(transport: ScriptedTransport([ + .init(200, body: JSONSerialization.data(withJSONObject: object)), + ])) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + guard case let .answered(answer) = try await client.submitRewrap(prepared) else { + return XCTFail("expected answered") + } + XCTAssertNil(answer.results.first?.kasWrappedKey) + XCTAssertEqual(answer.results.first?.metadata["arkavo.decision"], .string("ZGVj")) + XCTAssertThrowsError(try answer.share(for: answer.results[0], clientPrivateKey: clientKey)) + } + + func testOutOfRangeExpiresAtRefused() throws { + for seconds in [Double.infinity, 1e300, Double.nan, -1e300, -Double.infinity] { + XCTAssertThrowsError(try makeClient().prepareRewrap( + manifest: makeManifest(), clientPrivateKey: clientKey, + options: .init(expiresAt: Date(timeIntervalSince1970: seconds)), + )) { assertInvalidOptions($0) } + } + } + + func testRetryAfterIsClamped() { + XCTAssertEqual(KASRewrapClient.retryAfterSeconds("7"), 7) + XCTAssertEqual(KASRewrapClient.retryAfterSeconds("0"), 1) + XCTAssertEqual(KASRewrapClient.retryAfterSeconds("-5"), 2) + XCTAssertEqual(KASRewrapClient.retryAfterSeconds("999"), 60) + XCTAssertEqual(KASRewrapClient.retryAfterSeconds("Wed, 21 Oct 2015 07:28:00 GMT"), 2) + XCTAssertEqual(KASRewrapClient.retryAfterSeconds(nil), 2) + XCTAssertEqual(KASRewrapClient.retryAfterSeconds(" 4 "), 4) + XCTAssertEqual(KASRewrapClient.retryAfterSeconds("99999999999999999999"), 60, "overflow clamps to the cap") + XCTAssertEqual(KASRewrapClient.retryAfterSeconds("+5"), 2, "delta-seconds is digits only") + XCTAssertEqual(KASRewrapClient.retryAfterSeconds("٣"), 2, "ASCII digits only") + } + + func testLocationOriginRules() async throws { + let allowed = [ + "/owner-kas/v1/requests/a": "https://platform.arkavo.net/owner-kas/v1/requests/a", + "https://platform.arkavo.net/owner-kas/v1/requests/a": "https://platform.arkavo.net/owner-kas/v1/requests/a", + "https://PLATFORM.arkavo.net:443/owner-kas/v1/requests/a": + "https://PLATFORM.arkavo.net:443/owner-kas/v1/requests/a", + ] + for (location, resolved) in allowed { + let client = try makeClient(transport: ScriptedTransport([.init(202, headers: ["Location": location])])) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + guard case let .pending(pending) = try await client.submitRewrap(prepared) else { + return XCTFail("expected pending for \(location)") + } + XCTAssertEqual(pending.location.absoluteString, resolved) + } + for location in ["https://evil.example/x", "//evil.example/x", "http://platform.arkavo.net/x", + "https://platform.arkavo.net:8443/x", "https://evil@platform.arkavo.net/x", + "https://u:p@platform.arkavo.net/x", "https://platform.arkavo.net\\@evil.example/x"] + { + let transport = ScriptedTransport([.init(202, headers: ["Location": location])]) + let client = try makeClient(transport: transport) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + do { + _ = try await client.submitRewrap(prepared) + XCTFail("expected unsafeLocation for \(location)") + } catch KASRewrapError.unsafeLocation { + let count = await transport.requests.count + XCTAssertEqual(count, 1, "nothing is sent to \(location)") + } + } + } + + func testPendingWithoutLocationThrows() async throws { + let client = try makeClient(transport: ScriptedTransport([.init(202, headers: ["Retry-After": "2"])])) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + do { + _ = try await client.submitRewrap(prepared) + XCTFail("expected pendingWithoutLocation") + } catch KASRewrapError.pendingWithoutLocation {} + } + + func testResubmitSendsIdenticalBytes() async throws { + let pending = ScriptedTransport.Reply(202, headers: ["Location": "/owner-kas/v1/requests/a"]) + let transport = ScriptedTransport([pending, pending]) + let client = try makeClient(transport: transport) + let prepared = try client.prepareRewrap(manifest: makeManifest(), clientPrivateKey: clientKey) + _ = try await client.submitRewrap(prepared) + _ = try await client.submitRewrap(prepared) + let bodies = await transport.requests.map(\.body) + XCTAssertEqual(bodies.count, 2) + XCTAssertEqual(bodies[0], bodies[1]) + XCTAssertEqual(bodies[0], prepared.body) + } + + func testRewrapUnwrapsPermittedShares() async throws { + let encryption = try makeEncryption() + let client = try makeClient(transport: ScriptedTransport([.init(200, body: permitBody(for: encryption))])) + guard case let .answered(answer, shares) = try await client.rewrap( + manifest: encryption.container.manifest, clientPrivateKey: clientKey, + ) else { + return XCTFail("expected answered") + } + XCTAssertEqual(answer.results.count, 1) + XCTAssertEqual(shares.count, 1) + XCTAssertEqual(shares.first.map { Self.bytes($0.key) }, Self.bytes(encryption.symmetricKey)) + } + + func testAnswerShareRefusesFailResult() async throws { + let encryption = try makeEncryption() + let client = try makeClient(transport: ScriptedTransport([ + .init(200, body: permitBody(for: encryption, plusFail: true)), + ])) + let prepared = try client.prepareRewrap(manifest: encryption.container.manifest, clientPrivateKey: clientKey) + guard case let .answered(answer) = try await client.submitRewrap(prepared) else { + return XCTFail("expected answered") + } + XCTAssertThrowsError(try answer.share(for: answer.results[1], clientPrivateKey: clientKey)) + XCTAssertEqual( + try Self.bytes(answer.share(for: answer.results[0], clientPrivateKey: clientKey).key), + Self.bytes(encryption.symmetricKey), + ) + } + + // MARK: - Helpers + + func makeClient( + transport: any KASRewrapTransport = URLSessionKASTransport(), + clock: TestClock = TestClock(), + ) throws -> KASRewrapClient { + try KASRewrapClient( + configuration: .forKasConnect(Self.ownerURL), + oauthToken: "owner-kas-token", + transport: transport, + signingKey: signingKey, + sleeper: { clock.sleep($0) }, + now: { clock.now }, + ) + } + + /// Submits a request that is answered 202, then polls once into `replies`. + func pollOutcome( + after replies: [ScriptedTransport.Reply], + retryAfter: String = "2", + expiresIn: TimeInterval = 900, + ) async throws -> KASRewrapClient.RewrapPollOutcome { + let clock = TestClock() + let transport = ScriptedTransport( + [.init(202, headers: ["Location": "/owner-kas/v1/requests/abc", "Retry-After": retryAfter])] + replies, + ) + let client = try makeClient(transport: transport, clock: clock) + let prepared = try client.prepareRewrap( + manifest: makeManifest(), clientPrivateKey: clientKey, + options: .init(expiresAt: clock.start.addingTimeInterval(expiresIn)), + ) + guard case let .pending(pending) = try await client.submitRewrap(prepared) else { + throw KASRewrapError.invalidResponse + } + return try await client.pollRewrap(pending, until: clock.start.addingTimeInterval(expiresIn + 600)) + } + + /// A Rewrap response permitting the encryption's key access object, rewrapped + /// by `TDFKAS` to `clientKey`, and optionally a second, failed result. + func permitBody(for encryption: TDFEncryptionResult, plusFail: Bool = false) throws -> Data { + let manifest = encryption.container.manifest + let rewrapped = try TDFKAS.rewrap( + keyAccessObject: manifest.encryptionInformation.keyAccess[0], + policyBase64: manifest.encryptionInformation.policy, + kasPrivateKey: kasKey, + receiverPublicKey: clientKey.publicKey, + ) + var results = [TDFKAS.KeyAccessResult(keyAccessObjectId: "kao-0", status: .permit, + kasWrappedKey: rewrapped.wrappedKey, error: nil, + metadata: ["arkavo.decision": .string("YWxsb3c")])] + if plusFail { + results.append(.init(keyAccessObjectId: "kao-1", status: .fail, kasWrappedKey: nil, + error: "ACCESS_DENIED", metadata: [:])) + } + return try TDFKAS.rewrapResponseBody( + sessionPublicKey: rewrapped.sessionPublicKey, + responses: [.init(policyId: "policy", results: results)], + ) + } + + static func bytes(_ key: SymmetricKey) -> Data { + key.withUnsafeBytes { Data($0) } + } + + /// A TDF with one `ec-wrapped` key access object for the owner KAS. + func makeManifest() throws -> TDFManifest { + try makeEncryption().container.manifest + } + + func makeEncryption(plaintext: Data = Data("owner-held".utf8)) throws -> TDFEncryptionResult { + let kas = try TDFKasInfo( + url: XCTUnwrap(URL(string: Self.ownerURL)), + publicKeyPEM: kasKey.publicKey.pemRepresentation, + kid: "e1", + keyType: .ecP256, + ) + let policy = try TDFPolicy(json: Data( + #"{"uuid":"a1","body":{"dataAttributes":[],"dissem":[],"arkavo.owner-held":{"v":1}}}"#.utf8, + )) + return try TDFEncryptor().encrypt(plaintext: plaintext, configuration: TDFEncryptionConfiguration(kas: kas, policy: policy)) + } + + func assertInvalidOptions(_ error: Error, line: UInt = #line) { + guard case .invalidRewrapOptions = error as? KASRewrapError else { + return XCTFail("expected invalidRewrapOptions, got \(error)", line: line) + } + } +} + +/// Replays scripted HTTP replies in order and records each request. +actor ScriptedTransport: KASRewrapTransport { + struct Reply: Sendable { + let status: Int + let headers: [String: String] + let body: Data + + init(_ status: Int, headers: [String: String] = [:], body: Data = Data()) { + self.status = status + self.headers = headers + self.body = body + } + } + + struct Recorded: Sendable { + let method: String + let url: String + let authorization: String? + let body: Data? + let timeout: TimeInterval + } + + private var replies: [Reply] + private(set) var requests: [Recorded] = [] + + init(_ replies: [Reply]) { + self.replies = replies + } + + func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + requests.append(Recorded( + method: request.httpMethod ?? "GET", + url: request.url?.absoluteString ?? "", + authorization: request.value(forHTTPHeaderField: "Authorization"), + body: request.httpBody, + timeout: request.timeoutInterval, + )) + guard !replies.isEmpty else { + throw URLError(.badServerResponse) + } + let reply = replies.removeFirst() + let response = HTTPURLResponse(url: request.url!, statusCode: reply.status, httpVersion: "HTTP/1.1", + headerFields: reply.headers)! + return (reply.body, response) + } +} + +/// A clock that only moves when the client sleeps, recording each sleep. With +/// `oversleep` above 1 it wakes late, like an app suspended mid-wait. +final class TestClock: @unchecked Sendable { + let start = Date() + private let oversleep: Double + + init(oversleep: Double = 1) { + self.oversleep = oversleep + } + + private let lock = NSLock() + private var elapsed: TimeInterval = 0 + private var recorded: [TimeInterval] = [] + + var now: Date { + lock.withLock { start.addingTimeInterval(elapsed) } + } + + var sleeps: [TimeInterval] { + lock.withLock { recorded } + } + + func sleep(_ duration: TimeInterval) { + lock.withLock { + elapsed += duration * oversleep + recorded.append(duration) + } + } +} diff --git a/OpenTDFKitTests/OwnerKASEndToEndTests.swift b/OpenTDFKitTests/OwnerKASEndToEndTests.swift new file mode 100644 index 0000000..57cfef7 --- /dev/null +++ b/OpenTDFKitTests/OwnerKASEndToEndTests.swift @@ -0,0 +1,173 @@ +@preconcurrency import CryptoKit +import Foundation +@testable import OpenTDFKit +import XCTest + +/// The receiver's `KASRewrapClient` against an owner KAS: a fake relay that +/// queues the Rewrap and, on a later poll, lets the "phone" answer it with +/// `TDFKAS.verifyRewrapRequest`, `TDFKAS.rewrap` and `TDFKAS.rewrapResponseBody`. +final class OwnerKASEndToEndTests: XCTestCase { + static let ownerURL = "https://platform.arkavo.net/owner-kas/v1/routes/01HZXK3Q8R4M5N6P7Q8R9S0T1V" + let kasKey = P256.KeyAgreement.PrivateKey() + let cnfKey = P256.Signing.PrivateKey() + let clientKey = P256.KeyAgreement.PrivateKey() + let plaintext = Data("a photo, say".utf8) + + func testOwnerAllowEndToEnd() async throws { + let encryption = try encrypt() + let manifestKAO = encryption.container.manifest.encryptionInformation.keyAccess[0] + let relay = FakeOwnerKAS(kasKey: kasKey, cnfKey: cnfKey.publicKey, + expectedKAODigest: TDFKAS.keyAccessObjectDigest(manifestKAO), allow: true) + let clock = TestClock() + let extensionJSON = Data(#"{"v":1,"attempt_id":"QUJD","nonce":"REVG","tdf_digest":"R0hJ"}"#.utf8) + + let outcome = try await makeClient(transport: relay, clock: clock).rewrap( + manifest: encryption.container.manifest, + clientPrivateKey: clientKey, + options: .init(expiresAt: clock.start.addingTimeInterval(900), + requestBodyExtension: .init(name: "arkavo", json: extensionJSON)), + ) + + guard case let .answered(answer, shares) = outcome else { + return XCTFail("expected answered, got \(outcome)") + } + let phone = await relay.phoneSaw + XCTAssertEqual(answer.requestTokenDigest, phone?.requestTokenDigest, "both sides report one digest") + XCTAssertEqual(phone?.extensionNames, ["arkavo"]) + XCTAssertEqual(phone?.kaoDigestMatched, true) + XCTAssertEqual(answer.results.first?.metadata["arkavo.decision"], .string("YWxsb3c")) + XCTAssertEqual(shares.count, 1) + let dek = try XCTUnwrap(shares.first?.key) + XCTAssertEqual(try TDFDecryptor().decrypt(container: encryption.container, symmetricKey: dek), plaintext) + XCTAssertEqual(clock.sleeps, [1, 1], "a 202 on submit and one on the first poll") + } + + func testOwnerDenyEndToEnd() async throws { + let encryption = try encrypt() + let manifestKAO = encryption.container.manifest.encryptionInformation.keyAccess[0] + let relay = FakeOwnerKAS(kasKey: kasKey, cnfKey: cnfKey.publicKey, + expectedKAODigest: TDFKAS.keyAccessObjectDigest(manifestKAO), allow: false) + let clock = TestClock() + let outcome = try await makeClient(transport: relay, clock: clock).rewrap( + manifest: encryption.container.manifest, + clientPrivateKey: clientKey, + options: .init(expiresAt: clock.start.addingTimeInterval(900)), + ) + guard case let .answered(answer, shares) = outcome else { + return XCTFail("expected answered, got \(outcome)") + } + XCTAssertTrue(shares.isEmpty) + XCTAssertNil(answer.sessionPublicKey) + XCTAssertEqual(answer.results.map(\.status), ["fail"]) + XCTAssertEqual(answer.results.first?.error, "ACCESS_DENIED") + XCTAssertEqual(answer.results.first?.metadata["arkavo.decision"], .string("ZGVueQ")) + } + + // MARK: - Helpers + + func makeClient(transport: any KASRewrapTransport, clock: TestClock) throws -> KASRewrapClient { + try KASRewrapClient( + configuration: .forKasConnect(Self.ownerURL), + oauthToken: "owner-kas-token", + transport: transport, + signingKey: cnfKey, + sleeper: { clock.sleep($0) }, + now: { clock.now }, + ) + } + + func encrypt() throws -> TDFEncryptionResult { + let kas = try TDFKasInfo( + url: XCTUnwrap(URL(string: Self.ownerURL)), + publicKeyPEM: kasKey.publicKey.pemRepresentation, + kid: "e1", + keyType: .ecP256, + ) + let policy = try TDFPolicy(json: Data( + #"{"uuid":"asset-1","body":{"dataAttributes":[],"dissem":[],"arkavo.owner-held":{"v":1}}}"#.utf8, + )) + return try TDFEncryptor().encrypt( + plaintext: plaintext, + configuration: TDFEncryptionConfiguration(kas: kas, policy: policy, mimeType: "image/heic"), + ) + } +} + +/// A relay plus owner phone in one fake transport. The relay answers the Rewrap +/// POST with 202 and the first poll with 202; on the second poll the phone +/// verifies the queued request, checks the key access object against the +/// digest recorded at protect time, and answers. +actor FakeOwnerKAS: KASRewrapTransport { + struct PhoneView: Sendable { + let requestTokenDigest: Data + let extensionNames: [String] + let kaoDigestMatched: Bool + } + + private let kasKey: P256.KeyAgreement.PrivateKey + private let cnfKey: P256.Signing.PublicKey + private let expectedKAODigest: Data + private let allow: Bool + private var queued: Data? + private var polls = 0 + private(set) var phoneSaw: PhoneView? + + init(kasKey: P256.KeyAgreement.PrivateKey, cnfKey: P256.Signing.PublicKey, expectedKAODigest: Data, allow: Bool) { + self.kasKey = kasKey + self.cnfKey = cnfKey + self.expectedKAODigest = expectedKAODigest + self.allow = allow + } + + func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let url = try XCTUnwrap(request.url) + if request.httpMethod == "POST" { + XCTAssertTrue(url.path.hasSuffix("/owner-kas/v1/routes/01HZXK3Q8R4M5N6P7Q8R9S0T1V/kas.AccessService/Rewrap")) + queued = request.httpBody + return reply(url, 202, ["Location": "/owner-kas/v1/requests/r1", "Retry-After": "1"]) + } + XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer owner-kas-token") + polls += 1 + if polls == 1 { + return reply(url, 202, ["Retry-After": "1"]) + } + return try reply(url, 200, [:], body: answer()) + } + + private func answer() throws -> Data { + let request = try TDFKAS.verifyRewrapRequest(body: XCTUnwrap(queued), signingPublicKey: cnfKey) + let policy = try XCTUnwrap(request.policies.first) + let entry = try XCTUnwrap(policy.keyAccessObjects.first) + let matched = TDFKAS.keyAccessObjectDigest(entry.keyAccessObject) == expectedKAODigest + phoneSaw = PhoneView(requestTokenDigest: request.requestTokenDigest, + extensionNames: request.extensions.keys.sorted(), kaoDigestMatched: matched) + + guard allow, matched else { + return try TDFKAS.rewrapResponseBody(sessionPublicKey: nil, responses: [ + .init(policyId: policy.policyId, results: [ + .init(keyAccessObjectId: entry.id, status: .fail, kasWrappedKey: nil, + error: matched ? "ACCESS_DENIED" : "BINDING_MISMATCH", + metadata: ["arkavo.decision": .string("ZGVueQ")]), + ]), + ]) + } + let rewrapped = try TDFKAS.rewrap( + keyAccessObject: entry.keyAccessObject, + policyBase64: policy.policyBase64, + kasPrivateKey: kasKey, + receiverPublicKey: request.clientPublicKey, + ) + return try TDFKAS.rewrapResponseBody(sessionPublicKey: rewrapped.sessionPublicKey, responses: [ + .init(policyId: policy.policyId, results: [ + .init(keyAccessObjectId: entry.id, status: .permit, kasWrappedKey: rewrapped.wrappedKey, + error: nil, metadata: ["arkavo.decision": .string("YWxsb3c")]), + ]), + ]) + } + + private func reply(_ url: URL, _ status: Int, _ headers: [String: String], + body: Data = Data()) -> (Data, HTTPURLResponse) + { + (body, HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)!) + } +} diff --git a/OpenTDFKitTests/StrictJSONTests.swift b/OpenTDFKitTests/StrictJSONTests.swift new file mode 100644 index 0000000..16c0934 --- /dev/null +++ b/OpenTDFKitTests/StrictJSONTests.swift @@ -0,0 +1,36 @@ +import Foundation +@testable import OpenTDFKit +import XCTest + +/// `StrictJSON.hasDuplicateMembers`: duplicate member names anywhere, compared +/// after unescaping, with no false positives from arrays or string content. +final class StrictJSONTests: XCTestCase { + func testDetectsDuplicates() { + for json in [ + #"{"a":1,"a":2}"#, + #"{"a":1,"a":2}"#, + #"{"x":{"b":true,"b":false}}"#, + #"[{"k":"v"},{"k":"v","k":"w"}]"#, + #"{"🔒":1,"🔒":2}"#, + ] { + XCTAssertTrue(StrictJSON.hasDuplicateMembers(Data(json.utf8)), json) + } + } + + func testNoFalsePositives() { + for json in [ + #"{"a":[{"a":1},{"a":2}],"b":"{\"a\":1,\"a\":2}"}"#, + #"{"a":1,"A":2,"a ":3}"#, + #"[1,2.5e3,true,false,null,"s"]"#, + #"{}"#, + #"{"esc":"\"\\\/\b\f\n\r\té"}"#, + ] { + XCTAssertFalse(StrictJSON.hasDuplicateMembers(Data(json.utf8)), json) + } + } + + func testTooDeepIsRefused() { + let deep = String(repeating: "[", count: 600) + String(repeating: "]", count: 600) + XCTAssertTrue(StrictJSON.hasDuplicateMembers(Data(deep.utf8))) + } +} diff --git a/OpenTDFKitTests/TDFKASDigestTests.swift b/OpenTDFKitTests/TDFKASDigestTests.swift new file mode 100644 index 0000000..a3ccc15 --- /dev/null +++ b/OpenTDFKitTests/TDFKASDigestTests.swift @@ -0,0 +1,155 @@ +@preconcurrency import CryptoKit +import Foundation +@testable import OpenTDFKit +import XCTest + +/// The digests the owner's phone and the receiver both compute: the request +/// token digest, the key access object digest and the public-key fingerprint. +final class TDFKASDigestTests: XCTestCase { + func testRequestTokenDigestIsSHA256OfTokenBytes() { + XCTAssertEqual(TDFKAS.requestTokenDigest("a.b.c"), Data(SHA256.hash(data: Data("a.b.c".utf8)))) + } + + /// The encoding written out here, field by field, independently of the + /// implementation. + func testKAODigestKnownVector() { + let kao = Self.fullKAO() + var expected = Data("OpenTDFKit/kao-digest/v1".utf8) + for value in ["ec-wrapped", "https://h/owner-kas/v1/routes/R", "kas", "d3JhcHBlZA==", "HS256", + "aGFzaA==", "e1", "s1", "bWV0YQ==", "-----BEGIN PUBLIC KEY-----\nAAAA\n-----END PUBLIC KEY-----\n"] + { + let bytes = Data(value.utf8) + expected.append(1) + expected.append(contentsOf: withUnsafeBytes(of: UInt32(bytes.count).bigEndian) { Array($0) }) + expected.append(bytes) + } + XCTAssertEqual(TDFKAS.keyAccessObjectDigest(kao), Data(SHA256.hash(data: expected))) + } + + func testKAODigestIgnoresSchemaVersion() { + var withVersion = Self.fullKAO() + withVersion.schemaVersion = "1.0" + var withoutVersion = Self.fullKAO() + withoutVersion.schemaVersion = nil + XCTAssertEqual(TDFKAS.keyAccessObjectDigest(withVersion), TDFKAS.keyAccessObjectDigest(withoutVersion)) + } + + func testKAODigestEmptyAlgIsHS256() { + var empty = Self.fullKAO() + empty.policyBinding.alg = "" + XCTAssertEqual(TDFKAS.keyAccessObjectDigest(empty), TDFKAS.keyAccessObjectDigest(Self.fullKAO())) + } + + func testKAODigestChangesWithEachIncludedField() { + let mutations: [(inout TDFKeyAccessObject) -> Void] = [ + { $0.type = .wrapped }, + { $0.url = "https://h/owner-kas/v1/routes/S" }, + { $0.wrappedKey = "b3RoZXI=" }, + { $0.policyBinding.alg = "GMAC" }, + { $0.policyBinding.hash = "b3RoZXI=" }, + { $0.kid = "e2" }, + { $0.sid = "s2" }, + { $0.encryptedMetadata = "b3RoZXI=" }, + { $0.ephemeralPublicKey = "other" }, + ] + var digests: Set = [TDFKAS.keyAccessObjectDigest(Self.fullKAO())] + for mutate in mutations { + var kao = Self.fullKAO() + mutate(&kao) + digests.insert(TDFKAS.keyAccessObjectDigest(kao)) + } + // `protocol` has a single value (`kas`), so it cannot be mutated here; the + // known vector covers its place in the encoding. + XCTAssertEqual(digests.count, mutations.count + 1) + } + + func testKAODigestAbsentVersusEmptyDiffer() { + var absent = Self.fullKAO() + absent.kid = nil + var empty = Self.fullKAO() + empty.kid = "" + XCTAssertNotEqual(TDFKAS.keyAccessObjectDigest(absent), TDFKAS.keyAccessObjectDigest(empty)) + } + + /// The object in the file and the one the client forwards in its Rewrap + /// request (which drops `schemaVersion` and reorders keys) digest the same. + func testKAODigestSameForManifestAndForwardedKAO() throws { + let kasKey = P256.KeyAgreement.PrivateKey() + let kas = try TDFKasInfo( + url: XCTUnwrap(URL(string: "https://kas.example.com/kas")), + publicKeyPEM: kasKey.publicKey.pemRepresentation, + kid: "e1", + keyType: .ecP256, + ) + let policy = try TDFPolicy(json: Data(#"{"uuid":"u","body":{"dataAttributes":[],"dissem":["a@b.c"]}}"#.utf8)) + let manifest = try TDFEncryptor().encrypt( + plaintext: Data("x".utf8), + configuration: TDFEncryptionConfiguration(kas: kas, policy: policy), + ).container.manifest + let manifestKAO = manifest.encryptionInformation.keyAccess[0] + XCTAssertEqual(manifestKAO.schemaVersion, "1.0") + + let client = try KASRewrapClient( + configuration: .forKasConnect("https://kas.example.com"), + oauthToken: "token", + ) + let entry = try client.standardPolicyRequest(manifest: manifest, keyAccessEntries: [manifestKAO]) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(entry)) as? [String: Any]) + let wrapper = try XCTUnwrap((json["keyAccessObjects"] as? [[String: Any]])?.first) + let forwardedJSON = try JSONSerialization.data(withJSONObject: XCTUnwrap(wrapper["keyAccessObject"])) + let forwarded = try JSONDecoder().decode(TDFKeyAccessObject.self, from: forwardedJSON) + XCTAssertNil(forwarded.schemaVersion, "the client drops schemaVersion") + + XCTAssertEqual(TDFKAS.keyAccessObjectDigest(forwarded), TDFKAS.keyAccessObjectDigest(manifestKAO)) + } + + /// The same, for an object with every digest field set, `sid` and + /// `encryptedMetadata` included. + func testKAODigestSameForForwardedKAOWithAllFields() throws { + let manifestKAO = Self.fullKAO() + let client = try KASRewrapClient(configuration: .forKasConnect("https://h"), oauthToken: "token") + var manifest = try KASRewrapMatchingTests.manifest(kaoURLs: ["https://h/kas"]) + manifest.encryptionInformation.keyAccess = [manifestKAO] + let entry = try client.standardPolicyRequest(manifest: manifest, keyAccessEntries: [manifestKAO]) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(entry)) as? [String: Any]) + let wrapper = try XCTUnwrap((json["keyAccessObjects"] as? [[String: Any]])?.first) + let forwarded = try JSONDecoder().decode( + TDFKeyAccessObject.self, + from: JSONSerialization.data(withJSONObject: XCTUnwrap(wrapper["keyAccessObject"])), + ) + XCTAssertEqual(forwarded.sid, "s1") + XCTAssertEqual(forwarded.encryptedMetadata, "bWV0YQ==") + XCTAssertEqual(TDFKAS.keyAccessObjectDigest(forwarded), TDFKAS.keyAccessObjectDigest(manifestKAO)) + } + + func testFingerprintIndependentOfKeyEncoding() throws { + let key = P256.KeyAgreement.PrivateKey().publicKey + let expected = Data(SHA256.hash(data: key.x963Representation)) + let parsed = try [ + P256.KeyAgreement.PublicKey(pemRepresentation: key.pemRepresentation), + P256.KeyAgreement.PublicKey(derRepresentation: key.derRepresentation), + P256.KeyAgreement.PublicKey(x963Representation: key.x963Representation), + P256.KeyAgreement.PublicKey(compressedRepresentation: key.compressedRepresentation), + ] + for candidate in parsed { + XCTAssertEqual(TDFKAS.publicKeyFingerprint(candidate), expected) + } + } + + // MARK: - Helpers + + static func fullKAO() -> TDFKeyAccessObject { + TDFKeyAccessObject( + type: .ecWrapped, + url: "https://h/owner-kas/v1/routes/R", + protocolValue: .kas, + wrappedKey: "d3JhcHBlZA==", + policyBinding: TDFPolicyBinding(alg: "HS256", hash: "aGFzaA=="), + encryptedMetadata: "bWV0YQ==", + kid: "e1", + sid: "s1", + schemaVersion: "1.0", + ephemeralPublicKey: "-----BEGIN PUBLIC KEY-----\nAAAA\n-----END PUBLIC KEY-----\n", + ) + } +} diff --git a/OpenTDFKitTests/TDFKASEncryptorTests.swift b/OpenTDFKitTests/TDFKASEncryptorTests.swift new file mode 100644 index 0000000..82f2a93 --- /dev/null +++ b/OpenTDFKitTests/TDFKASEncryptorTests.swift @@ -0,0 +1,321 @@ +@preconcurrency import CryptoKit +import Foundation +@testable import OpenTDFKit +import Security +import XCTest + +/// `TDFEncryptor` with an `.ecP256` KAS writes a TDF `ec-wrapped` key access +/// object that `TDFKAS.rewrap` opens, from every encrypt entry point. +final class TDFKASEncryptorTests: XCTestCase { + private var tempDirectory: URL! + + override func setUpWithError() throws { + tempDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("TDFKASEncryptorTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tempDirectory, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + try? FileManager.default.removeItem(at: tempDirectory) + } + + // MARK: - Interop link (d) + + // Interop link (d): the encryptor writes the go KAO scheme. These tests prove + // the encryptor writes a PEM ephemeral key only while `TDFKAS.rewrap` accepts + // PEM alone; keep this comment true if rewrap's parsing ever changes. + + func testEncryptPlaintextWritesECWrappedKAO() throws { + let (kas, kasKey) = Self.makeECKas() + let plaintext = Data("hello, owner".utf8) + let result = try TDFEncryptor().encrypt(plaintext: plaintext, configuration: Self.configuration(kas)) + try Self.assertECWrappedKAO(result.container.manifest) + XCTAssertEqual(try Self.openThroughKAS(result.container, kasKey: kasKey), plaintext) + } + + func testEncryptSegmentedWritesECWrappedKAO() throws { + let (kas, kasKey) = Self.makeECKas() + let plaintext = Self.plaintext(count: 5000) + let result = try TDFEncryptor().encrypt( + plaintext: plaintext, + configuration: Self.configuration(kas), + segmentSize: 1024, + ) + try Self.assertECWrappedKAO(result.container.manifest) + XCTAssertEqual(try Self.openThroughKAS(result.container, kasKey: kasKey), plaintext) + } + + func testEncryptFileWritesECWrappedKAO() throws { + let (kas, kasKey) = Self.makeECKas() + let plaintext = Self.plaintext(count: 5000) + let (input, output) = try writeInput(plaintext) + _ = try TDFEncryptor().encryptFile(inputURL: input, outputURL: output, configuration: Self.configuration(kas)) + let container = try TDFLoader().load(from: output) + try Self.assertECWrappedKAO(container.manifest) + XCTAssertEqual(try Self.openThroughKAS(container, kasKey: kasKey), plaintext) + } + + func testEncryptFileMultiSegmentWritesECWrappedKAO() throws { + let (kas, kasKey) = Self.makeECKas() + let plaintext = Self.plaintext(count: 5000) + let (input, output) = try writeInput(plaintext) + _ = try TDFEncryptor().encryptFileMultiSegment( + inputURL: input, + outputURL: output, + configuration: Self.configuration(kas), + segmentSizes: [1024, 1024, 2952], + ) + let container = try TDFLoader().load(from: output) + try Self.assertECWrappedKAO(container.manifest) + XCTAssertEqual(try Self.openThroughKAS(container, kasKey: kasKey), plaintext) + } + + // MARK: - Refusals + + func testECKasWithoutKidIsRefused() throws { + for kid in [nil, "", " \t"] as [String?] { + let (kas, _) = Self.makeECKas(kid: kid) + try assertEveryEntryPointRefuses(Self.configuration(kas)) { + XCTAssertEqual($0 as? TDFEncryptError, .ecKasRequiresKeyID, "kid \(String(describing: kid))") + } + } + } + + func testECKasWithAES128IsRefused() throws { + let (kas, _) = Self.makeECKas() + let configuration = try TDFEncryptionConfiguration(kas: kas, policy: Self.policy(), keySize: .bits128) + try assertEveryEntryPointRefuses(configuration) { + XCTAssertEqual($0 as? TDFEncryptError, .ecKasRequiresAES256) + } + } + + func testKeyTypeAndPEMMismatchThrows() throws { + for kas in try Self.mismatchedKasInfos() { + try assertEveryEntryPointRefuses(Self.configuration(kas)) { + XCTAssertTrue($0 is TDFCryptoError, "expected a key error, got \($0)") + } + } + } + + /// A key type that does not match its PEM is refused before the input is + /// read: with an input file that does not exist, the key error still wins. + func testKeyTypeAndPEMMismatchIsRefusedBeforeReadingInput() throws { + let missing = tempDirectory.appendingPathComponent("missing.txt") + let output = tempDirectory.appendingPathComponent("out.tdf") + for kas in try Self.mismatchedKasInfos() { + let configuration = try Self.configuration(kas) + XCTAssertThrowsError(try TDFEncryptor().encryptFile( + inputURL: missing, + outputURL: output, + configuration: configuration, + )) { + XCTAssertTrue($0 is TDFCryptoError, "expected a key error, got \($0)") + } + XCTAssertThrowsError(try TDFEncryptor().encryptFileMultiSegment( + inputURL: missing, + outputURL: output, + configuration: configuration, + segmentSizes: [1], + )) { + XCTAssertTrue($0 is TDFCryptoError, "expected a key error, got \($0)") + } + } + } + + /// The default key type is RSA and writes today's `wrapped` key access object. + func testRSAKasOutputIsUnchanged() throws { + let url = try XCTUnwrap(URL(string: "https://kas.example.com")) + let (publicKeyPEM, privateKey) = try TDFSegmentedPayloadTests.makeRSAKeyPair() + let kas = TDFKasInfo(url: url, publicKeyPEM: publicKeyPEM, kid: "r1") + XCTAssertEqual(kas.keyType, .rsa) + let result = try TDFEncryptor().encrypt(plaintext: Data("x".utf8), configuration: Self.configuration(kas)) + let encryption = result.container.manifest.encryptionInformation + let kao = try XCTUnwrap(encryption.keyAccess.first) + XCTAssertEqual(encryption.keyAccess.count, 1) + XCTAssertEqual(kao.type, .wrapped) + XCTAssertNil(kao.ephemeralPublicKey) + XCTAssertEqual(kao.url, "https://kas.example.com") + XCTAssertEqual(kao.kid, "r1") + XCTAssertEqual(kao.schemaVersion, "1.0") + let policyJSON = try XCTUnwrap(Data(base64Encoded: encryption.policy)) + XCTAssertEqual( + kao.policyBinding.hash, + TDFCrypto.policyBinding(policy: policyJSON, symmetricKey: result.symmetricKey).hash, + ) + var error: Unmanaged? + let dek = try SecKeyCreateDecryptedData( + privateKey, + .rsaEncryptionOAEPSHA1, + XCTUnwrap(Data(base64Encoded: kao.wrappedKey)) as CFData, + &error, + ) as Data? + XCTAssertEqual(dek, result.symmetricKey.withUnsafeBytes { Data($0) }) + } + + // MARK: - Swift → go check + + /// Writes a key access object and a `TDFKAS.rewrap` response to + /// `OPENTDFKIT_INTEROP_OUT`, in `GoFixture`'s shape, for + /// `scripts/interop/ec-wrapped` (`go run . verify `) to open with go. + /// The key access object and policy are copied byte for byte from the + /// `manifest.json` an `encryptFile` archive holds, so go reads what ships. + /// Skipped unless that variable is set; required before a release is tagged. + func testWriteSwiftFixtureForGo() throws { + guard let path = ProcessInfo.processInfo.environment["OPENTDFKIT_INTEROP_OUT"], !path.isEmpty else { + throw XCTSkip("Set OPENTDFKIT_INTEROP_OUT to write the Swift → go interop fixture") + } + let (kas, kasKey) = Self.makeECKas() + let (input, output) = try writeInput(Data("interop".utf8)) + let result = try TDFEncryptor().encryptFile( + inputURL: input, + outputURL: output, + configuration: Self.configuration(kas), + ) + + let manifestJSON = try TDFArchiveReader(url: output).manifestData() + let manifest = try XCTUnwrap(JSONSerialization.jsonObject(with: manifestJSON) as? [String: Any]) + let encryption = try XCTUnwrap(manifest["encryptionInformation"] as? [String: Any]) + let kaoObject = try XCTUnwrap((encryption["keyAccess"] as? [[String: Any]])?.first) + let policyBase64 = try XCTUnwrap(encryption["policy"] as? String) + + let receiver = P256.KeyAgreement.PrivateKey() + let rewrapped = try TDFKAS.rewrap( + keyAccessObject: JSONDecoder().decode( + TDFKeyAccessObject.self, + from: JSONSerialization.data(withJSONObject: kaoObject), + ), + policyBase64: policyBase64, + kasPrivateKey: kasKey, + receiverPublicKey: receiver.publicKey, + ) + let fixture: [String: Any] = [ + "kasPrivateKeyPEM": kasKey.pemRepresentation, + "policyBase64": policyBase64, + "kao": kaoObject, + "dekBase64": result.symmetricKey.withUnsafeBytes { Data($0) }.base64EncodedString(), + "receiverPrivateKeyPEM": receiver.pemRepresentation, + "response": [ + "wrappedKeyBase64": rewrapped.wrappedKey.base64EncodedString(), + "sessionPublicKeyPEM": rewrapped.sessionPublicKey.pemRepresentation, + ], + ] + try JSONSerialization.data(withJSONObject: fixture, options: [.prettyPrinted, .sortedKeys]) + .write(to: URL(fileURLWithPath: path)) + } + + // MARK: - Helpers + + static func makeECKas(kid: String? = "e1") -> (TDFKasInfo, P256.KeyAgreement.PrivateKey) { + let kasKey = P256.KeyAgreement.PrivateKey() + let kas = TDFKasInfo( + url: URL(string: "https://kas.example.com")!, + publicKeyPEM: kasKey.publicKey.pemRepresentation, + kid: kid, + keyType: .ecP256, + ) + return (kas, kasKey) + } + + static func policy() throws -> TDFPolicy { + try TDFPolicy(json: Data( + #"{"uuid":"\#(UUID().uuidString)","body":{"dataAttributes":[],"dissem":["user@example.com"]}}"#.utf8, + )) + } + + static func configuration(_ kas: TDFKasInfo) throws -> TDFEncryptionConfiguration { + try TDFEncryptionConfiguration(kas: kas, policy: policy()) + } + + static func plaintext(count: Int) -> Data { + Data((0 ..< count).map { UInt8(truncatingIfNeeded: $0 &* 31 &+ 7) }) + } + + static func assertECWrappedKAO( + _ manifest: TDFManifest, + file: StaticString = #filePath, + line: UInt = #line, + ) throws { + let keyAccess = manifest.encryptionInformation.keyAccess + XCTAssertEqual(keyAccess.count, 1, file: file, line: line) + let kao = try XCTUnwrap(keyAccess.first, file: file, line: line) + XCTAssertEqual(kao.type, .ecWrapped, file: file, line: line) + XCTAssertEqual(kao.kid, "e1", file: file, line: line) + XCTAssertEqual(kao.schemaVersion, "1.0", file: file, line: line) + XCTAssertTrue( + kao.ephemeralPublicKey?.hasPrefix("-----BEGIN PUBLIC KEY-----") ?? false, + "ephemeral key is PEM", + file: file, + line: line, + ) + } + + /// Rewraps the container's key access object at the KAS, unwraps it as the + /// receiver, and decrypts the payload with the result. + static func openThroughKAS(_ container: TDFContainer, kasKey: P256.KeyAgreement.PrivateKey) throws -> Data { + let encryption = container.manifest.encryptionInformation + let receiver = P256.KeyAgreement.PrivateKey() + let rewrapped = try TDFKAS.rewrap( + keyAccessObject: encryption.keyAccess[0], + policyBase64: encryption.policy, + kasPrivateKey: kasKey, + receiverPublicKey: receiver.publicKey, + ) + let dek = try TDFKAS.unwrap( + wrappedKey: rewrapped.wrappedKey, + sessionPublicKey: rewrapped.sessionPublicKey, + receiverPrivateKey: receiver, + ) + return try TDFDecryptor().decrypt(container: container, symmetricKey: dek) + } + + /// `.ecP256` with an RSA PEM, and `.rsa` with an EC PEM. + static func mismatchedKasInfos() throws -> [TDFKasInfo] { + let url = try XCTUnwrap(URL(string: "https://kas.example.com")) + return try [ + TDFKasInfo(url: url, publicKeyPEM: TDFSegmentedPayloadTests.makeRSAPublicKeyPEM(), kid: "e1", keyType: .ecP256), + TDFKasInfo(url: url, publicKeyPEM: P256.KeyAgreement.PrivateKey().publicKey.pemRepresentation, kid: "r1"), + ] + } + + /// Runs all four `TDFEncryptor` entry points with `configuration`; each must + /// throw an error `check` accepts, and the file entry points write nothing. + private func assertEveryEntryPointRefuses( + _ configuration: TDFEncryptionConfiguration, + file: StaticString = #filePath, + line: UInt = #line, + check: (Error) -> Void, + ) throws { + let plaintext = Self.plaintext(count: 100) + let encryptor = TDFEncryptor() + XCTAssertThrowsError( + try encryptor.encrypt(plaintext: plaintext, configuration: configuration), + file: file, line: line, check, + ) + XCTAssertThrowsError( + try encryptor.encrypt(plaintext: plaintext, configuration: configuration, segmentSize: 64), + file: file, line: line, check, + ) + let (input, output) = try writeInput(plaintext) + XCTAssertThrowsError( + try encryptor.encryptFile(inputURL: input, outputURL: output, configuration: configuration), + file: file, line: line, check, + ) + XCTAssertThrowsError( + try encryptor.encryptFileMultiSegment( + inputURL: input, + outputURL: output, + configuration: configuration, + segmentSizes: [64, 36], + ), + file: file, line: line, check, + ) + XCTAssertFalse(FileManager.default.fileExists(atPath: output.path), "nothing is written", file: file, line: line) + } + + private func writeInput(_ plaintext: Data) throws -> (input: URL, output: URL) { + let name = UUID().uuidString + let input = tempDirectory.appendingPathComponent("\(name).txt") + try plaintext.write(to: input) + return (input, tempDirectory.appendingPathComponent("\(name).tdf")) + } +} diff --git a/OpenTDFKitTests/TDFKASGoFixture.swift b/OpenTDFKitTests/TDFKASGoFixture.swift new file mode 100644 index 0000000..e7257fc --- /dev/null +++ b/OpenTDFKitTests/TDFKASGoFixture.swift @@ -0,0 +1,58 @@ +import Foundation +@testable import OpenTDFKit + +/// A TDF `ec-wrapped` fixture produced by go, for interop tests. +/// +/// Generated with `scripts/interop/ec-wrapped` (`go run . generate`) using +/// `github.com/opentdf/platform/lib/ocrypto` v0.14.0. The key access object is +/// written the way the go SDK's `generateWrapKeyWithEC` writes it, with a +/// spec-form policy binding; the response is sealed the way the platform KAS +/// seals a rewrap response (`FromPublicPEMWithSalt(…, TDFSalt(), nil)`). +/// The keys are test-only. Paste regenerated output verbatim. +enum TDFKASGoFixture { + static let json = #""" + { + "kasPrivateKeyPEM": "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQghweFQhphb8Lrauj4\ngJFzdsntNFr4l1ShW7xEzRfT3i+hRANCAASntnUsgzAEhJwwIigaz2hJ5BhCUTD8\nIwr6amBePzDhBfUr5c+KeqqHjQDBzMewqbmnWb4YqpWwHBB41ZmEknPS\n-----END PRIVATE KEY-----\n", + "policyBase64": "eyJ1dWlkIjoiNTk3MGFiYTA0MDMzN2M1MDI2NjY3OGU1MGUxNmYyNmEiLCJib2R5Ijp7ImRhdGFBdHRyaWJ1dGVzIjpbXSwiZGlzc2VtIjpbImludGVyb3BAZXhhbXBsZS5jb20iXX19", + "kao": { + "type": "ec-wrapped", + "url": "https://kas.example.com", + "protocol": "kas", + "wrappedKey": "hZAhO9vauzJcmEE7gDcHrtPVB23hocMuSahynpk/LuUb5nHA2Bf2oNv5KIFc+sFsyGWheONfXZzO/md2", + "policyBinding": { + "alg": "HS256", + "hash": "x9uIIft5a5NWqoh11ZyDgkiPEFs1W9NBfJpjgYYsy8g=" + }, + "kid": "e1", + "schemaVersion": "1.0", + "ephemeralPublicKey": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEcwk8wg5dqdX6AkKV0tKJAZUOTpIm\n+VC7DVP/q7jVsaCMsGaKydfehJXeE1xA70D5emk0eHnXRGgDTtkHxqd5JQ==\n-----END PUBLIC KEY-----\n" + }, + "dekBase64": "ipNR5VUgfpWh/DjgDOxhEn91u5ssZFtH0F+sh99YJjk=", + "receiverPrivateKeyPEM": "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgl9QYa3BirblQa2nc\nFF+0sdnx8OKE1ZFcfVdX8bR9FY2hRANCAATI0d+F2ppE5jV2w5QooAS2y2t6bXzr\no+fog3ozbW2VTDN52MB5/zC97eLMmO9tJukTrZpxTl7xkr6AkvVuCKWB\n-----END PRIVATE KEY-----\n", + "response": { + "wrappedKeyBase64": "SACl2IFUyamGDbRzPX77ygYfdkLbrJY6Qu1QPoXGXV5O2pglyc9es1Z7RbMO1ax5sAwKY0pp+R7d+pTv", + "sessionPublicKeyPEM": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEVyorF3XWehWzEPezbbaekVn8Ul/Y\nK5o4zvdc13+THoEUYYHnXQweLD5ENaOog/qJHU/duHXqKF/Qh8ED19TFqA==\n-----END PUBLIC KEY-----\n" + } + } + """# +} + +/// The decoded form of `TDFKASGoFixture.json`. The Swift → go check +/// (`TDFKASEncryptorTests.testWriteSwiftFixtureForGo`) writes the same shape. +struct GoFixture: Decodable { + struct Response: Decodable { + let wrappedKeyBase64: String + let sessionPublicKeyPEM: String + } + + let kasPrivateKeyPEM: String + let policyBase64: String + let kao: TDFKeyAccessObject + let dekBase64: String + let receiverPrivateKeyPEM: String + let response: Response + + static func load() throws -> GoFixture { + try JSONDecoder().decode(GoFixture.self, from: Data(TDFKASGoFixture.json.utf8)) + } +} diff --git a/OpenTDFKitTests/TDFKASRequestTests.swift b/OpenTDFKitTests/TDFKASRequestTests.swift new file mode 100644 index 0000000..3128a3b --- /dev/null +++ b/OpenTDFKitTests/TDFKASRequestTests.swift @@ -0,0 +1,295 @@ +@preconcurrency import CryptoKit +import Foundation +@testable import OpenTDFKit +import XCTest + +/// `TDFKAS.verifyRewrapRequest`: the owner KAS verifies a received Rewrap +/// under the bearer token's `cnf` key and parses it. Requests here are built +/// by hand, independently of `KASRewrapClient`. +final class TDFKASRequestTests: XCTestCase { + private let signingKey = P256.Signing.PrivateKey() + private let clientKey = P256.KeyAgreement.PrivateKey() + private let now = Int(Date().timeIntervalSince1970) + + func testValidRequestVerifies() throws { + let kao = TDFKASDigestTests.fullKAO() + let (body, token) = try signedRequest(requestBody: requestBody(kao: kao), exp: now + 900, iat: now) + let request = try TDFKAS.verifyRewrapRequest(body: body, signingPublicKey: signingKey.publicKey) + + XCTAssertEqual(request.requestToken, token) + XCTAssertEqual(request.requestTokenDigest, TDFKAS.requestTokenDigest(token)) + XCTAssertEqual(request.expiresAt, Date(timeIntervalSince1970: TimeInterval(now + 900))) + XCTAssertEqual(request.issuedAt, Date(timeIntervalSince1970: TimeInterval(now))) + XCTAssertEqual(request.clientPublicKey.x963Representation, clientKey.publicKey.x963Representation) + XCTAssertEqual(request.policies.count, 1) + let policy = try XCTUnwrap(request.policies.first) + XCTAssertEqual(policy.policyId, "policy") + XCTAssertEqual(policy.policyBase64, Self.policyBase64) + XCTAssertEqual(policy.keyAccessObjects.map(\.id), ["kao-0"]) + XCTAssertEqual( + TDFKAS.keyAccessObjectDigest(policy.keyAccessObjects[0].keyAccessObject), + TDFKAS.keyAccessObjectDigest(kao), + ) + XCTAssertEqual(Array(request.extensions.keys), ["arkavo"]) + try assertJSONEqual(request.extensions["arkavo"], Self.arkavoExtension) + } + + func testExtensionRoundTripsUnicodeAndSlashes() throws { + let note: [String: Any] = ["v": 1, "note": "é/ü \u{1F512}"] + var bodyObject = try requestBody(kao: TDFKASDigestTests.fullKAO()) + bodyObject["arkavo"] = note + let (body, _) = try signedRequest(requestBody: bodyObject, exp: now + 60, iat: now) + let request = try TDFKAS.verifyRewrapRequest(body: body, signingPublicKey: signingKey.publicKey) + try assertJSONEqual(request.extensions["arkavo"], note) + } + + func testOtherSigningKeyRefused() throws { + let (body, _) = try signedRequest(requestBody: requestBody(), exp: now + 60, iat: now) + assertRefused(body, key: P256.Signing.PrivateKey().publicKey, .requestSignatureInvalid) + } + + func testPayloadChangedAfterSigningRefused() throws { + let (_, token) = try signedRequest(requestBody: requestBody(), exp: now + 60, iat: now) + var parts = token.split(separator: ".").map(String.init) + var claims = try XCTUnwrap(JSONSerialization.jsonObject(with: Self.base64URLDecode(parts[1])) as? [String: Any]) + claims["exp"] = now + 61 + parts[1] = try Self.base64URL(JSONSerialization.data(withJSONObject: claims)) + try assertRefused(Self.wrap(parts.joined(separator: ".")), key: signingKey.publicKey, .requestSignatureInvalid) + } + + func testSignatureChangedRefused() throws { + let (_, token) = try signedRequest(requestBody: requestBody(), exp: now + 60, iat: now) + var parts = token.split(separator: ".").map(String.init) + var signature = Self.base64URLDecode(parts[2]) + signature[10] ^= 0x01 + parts[2] = Self.base64URL(signature) + try assertRefused(Self.wrap(parts.joined(separator: ".")), key: signingKey.publicKey, .requestSignatureInvalid) + } + + func testAlgNoneAndHS256Refused() throws { + for alg in ["none", "HS256"] { + let (body, _) = try signedRequest(requestBody: requestBody(), header: ["alg": alg, "typ": "JWT"], + exp: now + 60, iat: now) + assertRefused(body, key: signingKey.publicKey, .unsupportedRequestAlgorithm(alg)) + } + } + + func testOversizedBodyRefused() { + assertRefused(Data(repeating: 0x20, count: 65537), key: signingKey.publicKey, .requestTooLarge) + } + + func testMalformedShapesRefused() throws { + var badClientKey = try requestBody() + badClientKey["clientPublicKey"] = "not a key" + var noRequests = try requestBody() + noRequests["requests"] = [Any]() + var badPolicy = try requestBody() + badPolicy["requests"] = try [["policy": ["id": "policy", "body": "!!!"], + "keyAccessObjects": Self.kaoWrappers(TDFKASDigestTests.fullKAO())]] + var noWrappedKey = try Self.jsonObject(TDFKASDigestTests.fullKAO()) + noWrappedKey.removeValue(forKey: "wrappedKey") + var badKAO = try requestBody() + badKAO["requests"] = [["policy": ["id": "policy", "body": Self.policyBase64], + "keyAccessObjects": [["keyAccessObjectId": "kao-0", "keyAccessObject": noWrappedKey]]]] + var noKAOs = try requestBody() + noKAOs["requests"] = [["policy": ["id": "policy", "body": Self.policyBase64], "keyAccessObjects": [Any]()]] + + for requestBody in [badClientKey, noRequests, badPolicy, badKAO, noKAOs] { + let (body, _) = try signedRequest(requestBody: requestBody, exp: now + 60, iat: now) + assertMalformed(body) + } + assertMalformed(Data(#"{"other":"x"}"#.utf8)) + try assertMalformed(Self.wrap("only.two")) + assertMalformed(Data("not json".utf8)) + } + + /// The phone must parse an expired request so it can sign REQUEST_EXPIRED. + func testOverlappingPEMMarkersInClientKeyRefused() throws { + var bodyObject = try requestBody() + bodyObject["clientPublicKey"] = "-----BEGIN PUBLIC KEY-----END PUBLIC KEY-----" + let (body, _) = try signedRequest(requestBody: bodyObject, exp: now + 60, iat: now) + assertMalformed(body) + } + + func testExpiredTokenStillParses() throws { + let (body, _) = try signedRequest(requestBody: requestBody(), exp: now - 3600, iat: now - 4500) + let request = try TDFKAS.verifyRewrapRequest(body: body, signingPublicKey: signingKey.publicKey) + XCTAssertEqual(request.expiresAt, Date(timeIntervalSince1970: TimeInterval(now - 3600))) + } + + func testStandardMembersAreNotExtensions() throws { + var bodyObject = try requestBody() + bodyObject["algorithm"] = "ec:secp256r1" + bodyObject["keyAccess"] = ["url": "https://h"] + bodyObject["policy"] = "e30=" + bodyObject["schemaVersion"] = "1.0.0" + let (body, _) = try signedRequest(requestBody: bodyObject, exp: now + 60, iat: nil) + let request = try TDFKAS.verifyRewrapRequest(body: body, signingPublicKey: signingKey.publicKey) + XCTAssertEqual(Array(request.extensions.keys), ["arkavo"]) + XCTAssertNil(request.issuedAt) + } + + // MARK: - Strict JOSE / JSON (RFC 7515 §4.1.11, §10.12; RFC 7519 §4) + + func testDuplicateHeaderMemberRefused() throws { + let (body, _) = try signedRaw(header: #"{"alg":"ES256","alg":"none"}"#, claims: claimsJSON()) + assertMalformed(body) + } + + func testDuplicateClaimRefused() throws { + let claims = try claimsJSON().replacingOccurrences(of: #""exp":"#, with: #""exp":1,"exp":"#) + let (body, _) = try signedRaw(header: #"{"alg":"ES256"}"#, claims: claims) + assertMalformed(body) + } + + func testDuplicateRequestBodyMemberRefused() throws { + let pem = clientKey.publicKey.pemRepresentation + let duplicated = try XCTUnwrap(String(data: JSONSerialization.data(withJSONObject: requestBody()), encoding: .utf8)) + .replacingOccurrences(of: "{", with: "{\"clientPublicKey\":\(Self.jsonString(pem)),", options: [], range: nil) + let (body, _) = try signedRaw(header: #"{"alg":"ES256"}"#, claims: claimsJSON(requestBody: duplicated)) + assertMalformed(body) + } + + func testDuplicateEnvelopeMemberRefused() throws { + let (_, token) = try signedRequest(requestBody: requestBody(), exp: now + 60, iat: now) + let body = Data("{\"signed_request_token\":\(Self.jsonString(token)),\"signed_request_token\":\"x.y.z\"}".utf8) + assertMalformed(body) + } + + func testCritHeaderRefused() throws { + let (body, _) = try signedRaw(header: #"{"alg":"ES256","crit":["x"],"x":true}"#, claims: claimsJSON()) + assertMalformed(body) + } + + func testNonCanonicalBase64URLRefused() throws { + let (_, token) = try signedRequest(requestBody: requestBody(), exp: now + 60, iat: now) + let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") + let last = try XCTUnwrap(token.last) + let index = try XCTUnwrap(alphabet.firstIndex(of: last)) + let slack = String(token.dropLast()) + String(alphabet[index ^ 0x01]) + XCTAssertEqual(Self.base64URLDecode(String(slack.split(separator: ".")[2])), + Self.base64URLDecode(String(token.split(separator: ".")[2])), + "the slack bits do not change the decoded signature") + for variant in [token + "=", slack] { + try assertMalformed(Self.wrap(variant)) + } + } + + func testNullIatRefused() throws { + let claims = try claimsJSON().replacingOccurrences(of: #""exp":"#, with: #""iat":null,"exp":"#) + let (body, _) = try signedRaw(header: #"{"alg":"ES256"}"#, claims: claims) + assertMalformed(body) + } + + func testExtensionBytesAreSortedWithoutEscapedSlashes() throws { + var bodyObject = try requestBody() + bodyObject["arkavo"] = ["b": "x/y", "a": 1] + let (body, _) = try signedRequest(requestBody: bodyObject, exp: now + 60, iat: now) + let request = try TDFKAS.verifyRewrapRequest(body: body, signingPublicKey: signingKey.publicKey) + XCTAssertEqual(request.extensions["arkavo"].map { String(decoding: $0, as: UTF8.self) }, #"{"a":1,"b":"x/y"}"#) + } + + // MARK: - Helpers + + static let policyBase64 = Data(#"{"uuid":"u","body":{"dataAttributes":[],"dissem":[]}}"#.utf8).base64EncodedString() + static var arkavoExtension: [String: Any] { + ["v": 1, "attempt_id": "QUJD", "nonce": "REVG", "tdf_digest": "R0hJ"] + } + + func requestBody(kao: TDFKeyAccessObject = TDFKASDigestTests.fullKAO()) throws -> [String: Any] { + try [ + "clientPublicKey": clientKey.publicKey.pemRepresentation, + "requests": [["policy": ["id": "policy", "body": Self.policyBase64], + "keyAccessObjects": Self.kaoWrappers(kao)]], + "arkavo": Self.arkavoExtension, + ] + } + + static func kaoWrappers(_ kao: TDFKeyAccessObject) throws -> [[String: Any]] { + try [["keyAccessObjectId": "kao-0", "keyAccessObject": jsonObject(kao)]] + } + + static func jsonObject(_ kao: TDFKeyAccessObject) throws -> [String: Any] { + try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(kao)) as? [String: Any]) + } + + /// `{"signed_request_token": }` signed with `signingKey`. + func signedRequest( + requestBody: [String: Any], + header: [String: Any] = ["alg": "ES256", "typ": "JWT"], + exp: Int, + iat: Int?, + ) throws -> (body: Data, token: String) { + let requestBodyString = try XCTUnwrap(String( + data: JSONSerialization.data(withJSONObject: requestBody), + encoding: .utf8, + )) + var claims: [String: Any] = ["requestBody": requestBodyString, "exp": exp] + if let iat { + claims["iat"] = iat + } + let signingInput = try Self.base64URL(JSONSerialization.data(withJSONObject: header)) + "." + + Self.base64URL(JSONSerialization.data(withJSONObject: claims)) + let signature = try signingKey.signature(for: Data(signingInput.utf8)).rawRepresentation + let token = signingInput + "." + Self.base64URL(signature) + return try (Self.wrap(token), token) + } + + /// Claims JSON written by hand: `requestBody` (as a JSON string) and `exp`. + func claimsJSON(requestBody: String? = nil) throws -> String { + let bodyText = try requestBody + ?? XCTUnwrap(String(data: JSONSerialization.data(withJSONObject: self.requestBody()), encoding: .utf8)) + return "{\"requestBody\":\(Self.jsonString(bodyText)),\"exp\":\(now + 60)}" + } + + /// A token over a hand-written header and claims, signed with `signingKey`. + func signedRaw(header: String, claims: String) throws -> (body: Data, token: String) { + let signingInput = Self.base64URL(Data(header.utf8)) + "." + Self.base64URL(Data(claims.utf8)) + let signature = try signingKey.signature(for: Data(signingInput.utf8)).rawRepresentation + let token = signingInput + "." + Self.base64URL(signature) + return try (Self.wrap(token), token) + } + + static func jsonString(_ text: String) -> String { + String(decoding: try! JSONEncoder().encode(text), as: UTF8.self) + } + + static func wrap(_ token: String) throws -> Data { + try JSONSerialization.data(withJSONObject: ["signed_request_token": token]) + } + + static func base64URL(_ data: Data) -> String { + data.base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + } + + static func base64URLDecode(_ text: String) -> Data { + var base64 = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4) + return Data(base64Encoded: base64)! + } + + func assertJSONEqual(_ json: Data?, _ expected: [String: Any], line: UInt = #line) throws { + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(json, line: line)) as? NSDictionary, + line: line) + XCTAssertEqual(object, expected as NSDictionary, line: line) + } + + func assertRefused(_ body: Data, key: P256.Signing.PublicKey, _ expected: TDFKASError, line: UInt = #line) { + XCTAssertThrowsError(try TDFKAS.verifyRewrapRequest(body: body, signingPublicKey: key), line: line) { + XCTAssertEqual($0 as? TDFKASError, expected, line: line) + } + } + + func assertMalformed(_ body: Data, line: UInt = #line) { + XCTAssertThrowsError(try TDFKAS.verifyRewrapRequest(body: body, signingPublicKey: signingKey.publicKey), + line: line) + { error in + guard case .malformedRewrapRequest = error as? TDFKASError else { + return XCTFail("expected malformedRewrapRequest, got \(error)", line: line) + } + } + } +} diff --git a/OpenTDFKitTests/TDFKASResponseTests.swift b/OpenTDFKitTests/TDFKASResponseTests.swift new file mode 100644 index 0000000..da806f0 --- /dev/null +++ b/OpenTDFKitTests/TDFKASResponseTests.swift @@ -0,0 +1,107 @@ +@preconcurrency import CryptoKit +import Foundation +@testable import OpenTDFKit +import XCTest + +/// `TDFKAS.rewrapResponseBody`: the owner KAS's Rewrap response, for ALLOW and +/// DENY alike, in the shape `KASRewrapClient` parses. +final class TDFKASResponseTests: XCTestCase { + typealias Value = KASRewrapClient.RewrapMetadataValue + + func testPermitAndFailShape() throws { + let session = P256.KeyAgreement.PrivateKey().publicKey + let wrapped = Data((0 ..< 60).map { UInt8($0) }) + let body = try TDFKAS.rewrapResponseBody(sessionPublicKey: session, responses: [ + TDFKAS.PolicyResponse(policyId: "policy", results: [ + TDFKAS.KeyAccessResult(keyAccessObjectId: "kao-0", status: .permit, kasWrappedKey: wrapped, + error: nil, metadata: ["arkavo.decision": .string("ZGVj")]), + TDFKAS.KeyAccessResult(keyAccessObjectId: "kao-1", status: .fail, kasWrappedKey: nil, + error: "ACCESS_DENIED", metadata: [:]), + ]), + ]) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: body) as? [String: Any]) + XCTAssertEqual(json["sessionPublicKey"] as? String, session.pemRepresentation) + let response = try XCTUnwrap((json["responses"] as? [[String: Any]])?.first) + XCTAssertEqual(response["policyId"] as? String, "policy") + let results = try XCTUnwrap(response["results"] as? [[String: Any]]) + XCTAssertEqual(results[0]["keyAccessObjectId"] as? String, "kao-0") + XCTAssertEqual(results[0]["status"] as? String, "permit") + XCTAssertEqual(results[0]["kasWrappedKey"] as? String, wrapped.base64EncodedString()) + XCTAssertNil(results[0]["error"]) + XCTAssertEqual((results[0]["metadata"] as? [String: Any])?["arkavo.decision"] as? String, "ZGVj") + XCTAssertEqual(results[1]["status"] as? String, "fail") + XCTAssertNil(results[1]["kasWrappedKey"]) + XCTAssertEqual(results[1]["error"] as? String, "ACCESS_DENIED") + XCTAssertNil(results[1]["metadata"], "empty metadata is omitted") + } + + func testMetadataAllValueTypes() throws { + let metadata: [String: Value] = [ + "s": .string("x/é"), "n": .number(42), "b": .bool(true), "z": .null, + "a": .array([.string("one"), .number(2)]), "o": .object(["k": .bool(false)]), + ] + let body = try TDFKAS.rewrapResponseBody(sessionPublicKey: nil, responses: [ + TDFKAS.PolicyResponse(policyId: "policy", results: [ + TDFKAS.KeyAccessResult(keyAccessObjectId: "kao-0", status: .fail, kasWrappedKey: nil, + error: "ACCESS_DENIED", metadata: metadata), + ]), + ]) + let decoded = try JSONDecoder().decode(Wire.self, from: body) + XCTAssertEqual(decoded.responses[0].results[0].metadata, metadata) + } + + func testDenyWithoutSessionKey() throws { + let body = try TDFKAS.rewrapResponseBody(sessionPublicKey: nil, responses: [ + TDFKAS.PolicyResponse(policyId: "policy", results: [ + TDFKAS.KeyAccessResult(keyAccessObjectId: "kao-0", status: .fail, kasWrappedKey: nil, + error: "ACCESS_REVOKED", metadata: [:]), + ]), + ]) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: body) as? [String: Any]) + XCTAssertNil(json["sessionPublicKey"]) + } + + func testInvalidCombinationsRefused() { + let cases = [ + TDFKAS.KeyAccessResult(keyAccessObjectId: "kao-0", status: .permit, kasWrappedKey: nil, + error: nil, metadata: [:]), + TDFKAS.KeyAccessResult(keyAccessObjectId: "kao-0", status: .fail, kasWrappedKey: Data([1]), + error: "ACCESS_DENIED", metadata: [:]), + ] + for result in cases { + XCTAssertThrowsError(try TDFKAS.rewrapResponseBody( + sessionPublicKey: P256.KeyAgreement.PrivateKey().publicKey, + responses: [TDFKAS.PolicyResponse(policyId: "policy", results: [result])], + )) { error in + guard case .invalidResult = error as? TDFKASError else { + return XCTFail("expected invalidResult, got \(error)") + } + } + } + } + + func testPermitWithoutSessionKeyRefused() { + XCTAssertThrowsError(try TDFKAS.rewrapResponseBody(sessionPublicKey: nil, responses: [ + TDFKAS.PolicyResponse(policyId: "policy", results: [ + TDFKAS.KeyAccessResult(keyAccessObjectId: "kao-0", status: .permit, kasWrappedKey: Data([1]), + error: nil, metadata: [:]), + ]), + ])) { error in + guard case .invalidResult = error as? TDFKASError else { + return XCTFail("expected invalidResult, got \(error)") + } + } + } + + private struct Wire: Decodable { + struct Response: Decodable { + struct Result: Decodable { + let metadata: [String: Value]? + } + + let results: [Result] + } + + let responses: [Response] + } +} diff --git a/OpenTDFKitTests/TDFKASTests.swift b/OpenTDFKitTests/TDFKASTests.swift new file mode 100644 index 0000000..ba619d3 --- /dev/null +++ b/OpenTDFKitTests/TDFKASTests.swift @@ -0,0 +1,462 @@ +@preconcurrency import CryptoKit +import Foundation +@testable import OpenTDFKit +import XCTest + +/// `TDFKAS`: the KAS-side rewrap of a TDF `ec-wrapped` key access object and +/// the matching client unwrap, checked against a fixture produced by go. +final class TDFKASTests: XCTestCase { + // MARK: - Unwrap + + /// Interop link (a): `unwrap` opens a response sealed the way the platform + /// KAS seals it, so it uses the go session scheme. + func testUnwrapOpensGoSealedResponse() throws { + let fixture = try GoFixture.load() + let share = try TDFKAS.unwrap( + wrappedKey: XCTUnwrap(Data(base64Encoded: fixture.response.wrappedKeyBase64)), + sessionPublicKey: P256.KeyAgreement.PublicKey(pemRepresentation: fixture.response.sessionPublicKeyPEM), + receiverPrivateKey: P256.KeyAgreement.PrivateKey(pemRepresentation: fixture.receiverPrivateKeyPEM), + ) + XCTAssertEqual(Self.bytes(share), Data(base64Encoded: fixture.dekBase64)) + } + + func testUnwrapWithAnotherReceiverKeyFails() throws { + let fixture = try GoFixture.load() + let wrappedKey = try XCTUnwrap(Data(base64Encoded: fixture.response.wrappedKeyBase64)) + let sessionPublicKey = try P256.KeyAgreement.PublicKey(pemRepresentation: fixture.response.sessionPublicKeyPEM) + XCTAssertThrowsError(try TDFKAS.unwrap( + wrappedKey: wrappedKey, + sessionPublicKey: sessionPublicKey, + receiverPrivateKey: P256.KeyAgreement.PrivateKey(), + )) { error in + XCTAssertEqual(error as? TDFKASError, .keyUnwrapFailed) + } + } + + func testUnwrapRefusesNon32ByteShare() throws { + let receiver = P256.KeyAgreement.PrivateKey() + let (wrappedKey, sessionPublicKey) = try Self.sealWithTDFSalt( + Data((0 ..< 16).map { _ in UInt8.random(in: 0 ... 255) }), + to: receiver.publicKey, + ) + XCTAssertThrowsError(try TDFKAS.unwrap( + wrappedKey: wrappedKey, + sessionPublicKey: sessionPublicKey, + receiverPrivateKey: receiver, + )) { error in + XCTAssertEqual(error as? TDFKASError, .keyUnwrapFailed) + } + } + + // MARK: - Rewrap: interop and round trip + + /// Interop links (c) and (b): `rewrap` opens a key access object written by + /// go, and `unwrap` opens what `rewrap` sealed. + func testRewrapOpensGoKAOAndUnwrapOpensResult() throws { + let fixture = try GoFixture.load() + let receiver = P256.KeyAgreement.PrivateKey() + let result = try TDFKAS.rewrap( + keyAccessObject: fixture.kao, + policyBase64: fixture.policyBase64, + kasPrivateKey: P256.KeyAgreement.PrivateKey(pemRepresentation: fixture.kasPrivateKeyPEM), + receiverPublicKey: receiver.publicKey, + ) + let share = try TDFKAS.unwrap( + wrappedKey: result.wrappedKey, + sessionPublicKey: result.sessionPublicKey, + receiverPrivateKey: receiver, + ) + XCTAssertEqual(Self.bytes(share), Data(base64Encoded: fixture.dekBase64)) + } + + func testWrapThenRewrapRoundTrip() throws { + let input = try Self.makeInput() + XCTAssertTrue(input.kao.ephemeralPublicKey?.hasPrefix("-----BEGIN PUBLIC KEY-----") ?? false) + let receiver = P256.KeyAgreement.PrivateKey() + let result = try TDFKAS.rewrap( + keyAccessObject: input.kao, + policyBase64: input.policyBase64, + kasPrivateKey: input.kasKey, + receiverPublicKey: receiver.publicKey, + ) + let share = try TDFKAS.unwrap( + wrappedKey: result.wrappedKey, + sessionPublicKey: result.sessionPublicKey, + receiverPrivateKey: receiver, + ) + XCTAssertEqual(Self.bytes(share), Self.bytes(input.share)) + } + + func testRewrapResultIsFresh() throws { + let input = try Self.makeInput() + let receiver = P256.KeyAgreement.PrivateKey().publicKey + let first = try input.rewrap(to: receiver) + let second = try input.rewrap(to: receiver) + XCTAssertNotEqual(first.sessionPublicKey.rawRepresentation, second.sessionPublicKey.rawRepresentation) + XCTAssertNotEqual(first.wrappedKey.prefix(12), second.wrappedKey.prefix(12)) + } + + // MARK: - Rewrap: policy binding + + func testTamperedPolicyIsRefused() throws { + let input = try Self.makeInput() + var characters = Array(input.policyBase64) + characters[10] = characters[10] == "A" ? "B" : "A" + assertRewrapFails(input, policyBase64: String(characters), .policyBindingRefused) + } + + func testDecodedPolicyJSONIsRefused() throws { + let input = try Self.makeInput() + assertRewrapFails(input, policyBase64: String(decoding: input.policyJSON, as: UTF8.self), .policyBindingRefused) + } + + func testTamperedBindingHashIsRefused() throws { + let input = try Self.makeInput() + var kao = input.kao + var characters = Array(kao.policyBinding.hash) + characters[5] = characters[5] == "A" ? "B" : "A" + kao.policyBinding.hash = String(characters) + assertRewrapFails(input, kao: kao, .policyBindingRefused) + } + + /// go's legacy `Base64(hex(HMAC))` form is a bug and is refused, even over + /// the correct HMAC. + func testLegacyHexBindingIsRefused() throws { + let input = try Self.makeInput() + let mac = HMAC.authenticationCode(for: Data(input.policyBase64.utf8), using: input.share) + let hex = Data(mac).map { String(format: "%02x", $0) }.joined() + var kao = input.kao + kao.policyBinding.hash = Data(hex.utf8).base64EncodedString() + assertRewrapFails(input, kao: kao, .policyBindingRefused) + } + + func testNonHS256AlgIsRefused() throws { + let input = try Self.makeInput() + var kao = input.kao + kao.policyBinding.alg = "GMAC" + assertRewrapFails(input, kao: kao, .policyBindingRefused) + } + + /// An empty `alg` means HS256 (OpenTDF spec PR #70), also on a key access + /// object built by hand rather than decoded. + func testEmptyAlgIsTreatedAsHS256() throws { + let input = try Self.makeInput() + var kao = input.kao + kao.policyBinding.alg = "" + XCTAssertNoThrow(try input.rewrap(kao: kao, to: P256.KeyAgreement.PrivateKey().publicKey)) + } + + /// Some writers emit `policyBinding` as a bare string; it decodes as HS256 + /// and verifies normally. + func testBareStringBindingVerifies() throws { + let input = try Self.makeInput() + var object = try XCTUnwrap( + JSONSerialization.jsonObject(with: JSONEncoder().encode(input.kao)) as? [String: Any], + ) + object["policyBinding"] = input.kao.policyBinding.hash + let kao = try JSONDecoder().decode( + TDFKeyAccessObject.self, + from: JSONSerialization.data(withJSONObject: object), + ) + XCTAssertNoThrow(try input.rewrap(kao: kao, to: P256.KeyAgreement.PrivateKey().publicKey)) + } + + // MARK: - Rewrap: wrapped key + + func testFlippedNonceByteIsRefused() throws { + let input = try Self.makeInput() + assertRewrapFails(input, kao: Self.flippingWrappedKeyByte(of: input.kao) { _ in 0 }, .keyUnwrapFailed) + } + + func testFlippedCiphertextByteIsRefused() throws { + let input = try Self.makeInput() + assertRewrapFails(input, kao: Self.flippingWrappedKeyByte(of: input.kao) { _ in 12 }, .keyUnwrapFailed) + } + + func testFlippedTagByteIsRefused() throws { + let input = try Self.makeInput() + assertRewrapFails(input, kao: Self.flippingWrappedKeyByte(of: input.kao) { $0 - 1 }, .keyUnwrapFailed) + } + + func testTruncatedWrappedKeyIsRefused() throws { + let input = try Self.makeInput() + let wrapped = try XCTUnwrap(Data(base64Encoded: input.kao.wrappedKey)) + for truncated in [wrapped.dropLast(), wrapped.prefix(20)] { + var kao = input.kao + kao.wrappedKey = Data(truncated).base64EncodedString() + assertRewrapFails(input, kao: kao, .keyUnwrapFailed) + } + } + + func testSixteenByteShareIsRefused() throws { + let input = try Self.makeInput(share: SymmetricKey(size: .bits128)) + assertRewrapFails(input, .keyUnwrapFailed) + } + + func testWrongKASPrivateKeyIsRefused() throws { + let input = try Self.makeInput() + assertRewrapFails(input, kasKey: P256.KeyAgreement.PrivateKey(), .keyUnwrapFailed) + } + + func testNonBase64WrappedKeyIsRefused() throws { + let input = try Self.makeInput() + var urlAlphabet = input.kao + urlAlphabet.wrappedKey = "-_" + input.kao.wrappedKey.dropFirst(2) + assertRewrapFails(input, kao: urlAlphabet, .invalidWrappedKeyEncoding) + var withNewline = input.kao + withNewline.wrappedKey.insert("\n", at: withNewline.wrappedKey.index(withNewline.wrappedKey.startIndex, offsetBy: 8)) + assertRewrapFails(input, kao: withNewline, .invalidWrappedKeyEncoding) + } + + // MARK: - Rewrap: key access object shape + + func testWrongKAOTypeIsRefused() throws { + let input = try Self.makeInput() + var kao = input.kao + kao.type = .wrapped + assertRewrapFails(input, kao: kao, .unsupportedKeyAccessType("wrapped")) + } + + func testMissingEphemeralKeyIsRefused() throws { + let input = try Self.makeInput() + var kao = input.kao + kao.ephemeralPublicKey = nil + assertRewrapFails(input, kao: kao, .missingEphemeralPublicKey) + } + + /// go's `omitempty` treats an empty string as absent; so does `rewrap`. + func testEmptyEphemeralKeyIsMissing() throws { + let input = try Self.makeInput() + for empty in ["", " \n"] { + var kao = input.kao + kao.ephemeralPublicKey = empty + assertRewrapFails(input, kao: kao, .missingEphemeralPublicKey) + } + } + + func testSEC1EphemeralKeyIsRefused() throws { + let input = try Self.makeInput() + var kao = input.kao + kao.ephemeralPublicKey = P256.KeyAgreement.PrivateKey().publicKey.compressedRepresentation.base64EncodedString() + assertRewrapFails(input, kao: kao, .ephemeralKeyNotPEM) + } + + /// The TDF-JSON container's EC scheme (compressed SEC1, empty salt) is not + /// the platform's `ec-wrapped` and is refused with a clear error. + func testTDFJSONContainerKAOIsRefused() throws { + let kasKey = P256.KeyAgreement.PrivateKey() + let result = try TDFJSONBuilder() + .kasURL(XCTUnwrap(URL(string: "https://kas.example.com"))) + .kasPublicKey(kasKey.publicKey.pemRepresentation) + .kasKid("e1") + .policy(TDFPolicy(json: Self.policyJSON())) + .encrypt(plaintext: Data("hello".utf8)) + let encryption = result.container.manifest.encryptionInformation + XCTAssertThrowsError(try TDFKAS.rewrap( + keyAccessObject: encryption.keyAccess[0], + policyBase64: encryption.policy, + kasPrivateKey: kasKey, + receiverPublicKey: P256.KeyAgreement.PrivateKey().publicKey, + )) { error in + XCTAssertEqual(error as? TDFKASError, .ephemeralKeyNotPEM) + } + } + + func testP384EphemeralKeyIsRefused() throws { + let input = try Self.makeInput() + var kao = input.kao + kao.ephemeralPublicKey = P384.KeyAgreement.PrivateKey().publicKey.pemRepresentation + assertRewrapFails(input, kao: kao, .invalidEphemeralPublicKey) + } + + func testRewrapAcceptsCRLFPEM() throws { + let fixture = try GoFixture.load() + let kasKey = try P256.KeyAgreement.PrivateKey(pemRepresentation: fixture.kasPrivateKeyPEM) + let pem = try XCTUnwrap(fixture.kao.ephemeralPublicKey) + XCTAssertTrue(pem.hasSuffix("\n"), "the go fixture's PEM ends with a newline") + for variant in [pem.replacingOccurrences(of: "\n", with: "\r\n"), String(pem.dropLast())] { + var kao = fixture.kao + kao.ephemeralPublicKey = variant + XCTAssertNoThrow(try TDFKAS.rewrap( + keyAccessObject: kao, + policyBase64: fixture.policyBase64, + kasPrivateKey: kasKey, + receiverPublicKey: P256.KeyAgreement.PrivateKey().publicKey, + )) + } + } + + /// go's `pem.Decode`, which the platform KAS uses, accepts any line length, + /// spaces and tabs inside the body, and text after the END line; so does + /// `rewrap`. + func testRewrapAcceptsPEMLayoutsGoAccepts() throws { + let fixture = try GoFixture.load() + let kasKey = try P256.KeyAgreement.PrivateKey(pemRepresentation: fixture.kasPrivateKeyPEM) + let der = try P256.KeyAgreement.PublicKey(pemRepresentation: XCTUnwrap(fixture.kao.ephemeralPublicKey)) + .derRepresentation + let body = der.base64EncodedString() + func pem(_ lines: [String], after: String = "") -> String { + (["-----BEGIN PUBLIC KEY-----"] + lines + ["-----END PUBLIC KEY-----"]).joined(separator: "\n") + "\n" + after + } + func chunks(_ width: Int) -> [String] { + stride(from: 0, to: body.count, by: width).map { start in + let from = body.index(body.startIndex, offsetBy: start) + return String(body[from ..< body.index(from, offsetBy: min(width, body.count - start))]) + } + } + let variants = [ + "one line": pem([body]), + "48 columns": pem(chunks(48)), + "76 columns": pem(chunks(76)), + "trailing spaces and a tab": pem(chunks(64).map { $0 + " \t " }), + "text after END": pem(chunks(64), after: "trailing text\n"), + ] + for (name, variant) in variants { + var kao = fixture.kao + kao.ephemeralPublicKey = variant + XCTAssertNoThrow(try TDFKAS.rewrap( + keyAccessObject: kao, + policyBase64: fixture.policyBase64, + kasPrivateKey: kasKey, + receiverPublicKey: P256.KeyAgreement.PrivateKey().publicKey, + ), name) + } + } + + /// The END marker overlapping the BEGIN marker's dashes must throw, not trap. + func testOverlappingPEMMarkersRefused() throws { + let input = try Self.makeInput() + for variant in ["-----BEGIN PUBLIC KEY-----END PUBLIC KEY-----", + "-----BEGIN PUBLIC KEY-----END PUBLIC KEY-----\n", + "-----BEGIN PUBLIC KEY-----"] + { + var kao = input.kao + kao.ephemeralPublicKey = variant + assertRewrapFails(input, kao: kao, .invalidEphemeralPublicKey) + } + } + + func testMalformedPEMBodyIsRefused() throws { + let input = try Self.makeInput() + for variant in [ + "-----BEGIN PUBLIC KEY-----\n!!!!\n-----END PUBLIC KEY-----\n", + "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE\n", + ] { + var kao = input.kao + kao.ephemeralPublicKey = variant + assertRewrapFails(input, kao: kao, .invalidEphemeralPublicKey) + } + } + + // MARK: - Helpers + + /// A key access object wrapped to a fresh KAS key with the library's EC wrap + /// for a KAS, plus everything needed to rewrap it. + struct Input { + let share: SymmetricKey + let kasKey: P256.KeyAgreement.PrivateKey + let policyJSON: Data + let policyBase64: String + let kao: TDFKeyAccessObject + + func rewrap( + kao: TDFKeyAccessObject? = nil, + to receiver: P256.KeyAgreement.PublicKey, + ) throws -> TDFKAS.RewrapResult { + try TDFKAS.rewrap( + keyAccessObject: kao ?? self.kao, + policyBase64: policyBase64, + kasPrivateKey: kasKey, + receiverPublicKey: receiver, + ) + } + } + + static func policyJSON() -> Data { + Data(#"{"uuid":"\#(UUID().uuidString)","body":{"dataAttributes":[],"dissem":["user@example.com"]}}"#.utf8) + } + + static func makeInput(share: SymmetricKey = SymmetricKey(size: .bits256)) throws -> Input { + let kasKey = P256.KeyAgreement.PrivateKey() + let policyJSON = policyJSON() + let wrapped = try TDFCrypto.wrapSymmetricKeyWithECForKAS( + publicKeyPEM: kasKey.publicKey.pemRepresentation, + symmetricKey: share, + ) + let kao = TDFKeyAccessObject( + type: .ecWrapped, + url: "https://kas.example.com", + protocolValue: .kas, + wrappedKey: wrapped.wrappedKey, + policyBinding: TDFCrypto.policyBinding(policy: policyJSON, symmetricKey: share), + kid: "e1", + schemaVersion: "1.0", + ephemeralPublicKey: wrapped.ephemeralPublicKeyPEM, + ) + return Input( + share: share, + kasKey: kasKey, + policyJSON: policyJSON, + policyBase64: policyJSON.base64EncodedString(), + kao: kao, + ) + } + + /// Returns `kao` with one byte of its decoded wrapped key flipped, at the + /// index `position` picks from the wrapped key's length. + static func flippingWrappedKeyByte( + of kao: TDFKeyAccessObject, + at position: (Int) -> Int, + ) -> TDFKeyAccessObject { + var wrapped = Data(base64Encoded: kao.wrappedKey)! + let index = position(wrapped.count) + wrapped[index] ^= 0x01 + var copy = kao + copy.wrappedKey = wrapped.base64EncodedString() + return copy + } + + func assertRewrapFails( + _ input: Input, + kao: TDFKeyAccessObject? = nil, + policyBase64: String? = nil, + kasKey: P256.KeyAgreement.PrivateKey? = nil, + _ expected: TDFKASError, + file: StaticString = #filePath, + line: UInt = #line, + ) { + XCTAssertThrowsError(try TDFKAS.rewrap( + keyAccessObject: kao ?? input.kao, + policyBase64: policyBase64 ?? input.policyBase64, + kasPrivateKey: kasKey ?? input.kasKey, + receiverPublicKey: P256.KeyAgreement.PrivateKey().publicKey, + ), file: file, line: line) { error in + XCTAssertEqual(error as? TDFKASError, expected, file: file, line: line) + } + } + + /// `SHA256("TDF")`, written out here rather than taken from the library. + static let tdfSalt = Data(SHA256.hash(data: Data("TDF".utf8))) + + static func bytes(_ key: SymmetricKey) -> Data { + key.withUnsafeBytes { Data($0) } + } + + /// Seals `plaintext` to `receiver` the way the platform KAS seals a rewrap + /// response: a fresh session key, ECDH, HKDF-SHA256 with the TDF salt, + /// AES-256-GCM, nonce ‖ ciphertext ‖ tag. + static func sealWithTDFSalt( + _ plaintext: Data, + to receiver: P256.KeyAgreement.PublicKey, + ) throws -> (Data, P256.KeyAgreement.PublicKey) { + let session = P256.KeyAgreement.PrivateKey() + let key = try session.sharedSecretFromKeyAgreement(with: receiver).hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: tdfSalt, + sharedInfo: Data(), + outputByteCount: 32, + ) + let sealed = try AES.GCM.seal(plaintext, using: key) + return try (XCTUnwrap(sealed.combined), session.publicKey) + } +} diff --git a/OpenTDFKitTests/TDFSegmentedPayloadTests.swift b/OpenTDFKitTests/TDFSegmentedPayloadTests.swift index c326d7f..9c47904 100644 --- a/OpenTDFKitTests/TDFSegmentedPayloadTests.swift +++ b/OpenTDFKitTests/TDFSegmentedPayloadTests.swift @@ -264,6 +264,11 @@ final class TDFSegmentedPayloadTests: XCTestCase { /// RSA-2048 SPKI public key PEM for tests that need a KAS wrapping key. static func makeRSAPublicKeyPEM() throws -> String { + try makeRSAKeyPair().publicKeyPEM + } + + /// An RSA-2048 key pair: the SPKI public key PEM and the private `SecKey`. + static func makeRSAKeyPair() throws -> (publicKeyPEM: String, privateKey: SecKey) { let attributes: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits as String: 2048, @@ -280,7 +285,7 @@ final class TDFSegmentedPayloadTests: XCTestCase { let bitString = derElement(tag: 0x03, content: Data([0x00]) + pkcs1) let spki = derElement(tag: 0x30, content: Data(algorithmIdentifier) + bitString) let base64 = spki.base64EncodedString(options: [.lineLength64Characters, .endLineWithLineFeed]) - return "-----BEGIN PUBLIC KEY-----\n\(base64)\n-----END PUBLIC KEY-----\n" + return ("-----BEGIN PUBLIC KEY-----\n\(base64)\n-----END PUBLIC KEY-----\n", privateKey) } private static func derElement(tag: UInt8, content: Data) -> Data { diff --git a/docs/superpowers/plans/2026-11-08-kas-side-ec-rewrap.md b/docs/superpowers/plans/2026-11-08-kas-side-ec-rewrap.md new file mode 100644 index 0000000..cfeed18 --- /dev/null +++ b/docs/superpowers/plans/2026-11-08-kas-side-ec-rewrap.md @@ -0,0 +1,409 @@ +# KAS-side TDF EC Rewrap Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** A pure Swift KAS-side rewrap and client unwrap for TDF `ec-wrapped` key access objects, and an +`ec-wrapped` path in the ZIP encryptor, byte-compatible with the go SDK and opentdf-platform KAS (issue #66). + +**Architecture:** A new `TDFKAS` namespace (`rewrap`, `unwrap`) with its own error type, built on CryptoKit and +the existing `KASRewrapClient.unwrapKey` / `standardTDFSessionSalt`. A new go-scheme EC wrap function in `TDFCrypto`, +selected by a new `TDFKasInfo.KeyType`, used by one KAO-building helper that all `TDFEncryptor` entry points share. +Interop is proven by a go program that generates a fixture (go → Swift, in CI) and verifies Swift output (Swift → go, +by hand before tagging). + +**Tech Stack:** Swift 6.2, CryptoKit, XCTest; Go with `github.com/opentdf/platform/lib/ocrypto` for the interop program. + +**Spec:** `docs/superpowers/specs/2026-11-08-kas-side-ec-rewrap-design.md` + +## Global Constraints + +- No new Swift package dependencies. CryptoKit for all new crypto. +- Salt for both the KAO wrap and the rewrap session: `KASRewrapClient.standardTDFSessionSalt` (`SHA256("TDF")`). HKDF + info empty, output 32 bytes. +- Wrapped key layout: nonce (12) ‖ ciphertext ‖ tag (16), base64 in the KAO, raw `Data` in `TDFKAS.RewrapResult`. +- KAO `ephemeralPublicKey`: PEM SubjectPublicKeyInfo on P-256. Always written as PEM; only PEM accepted. +- Policy binding: spec form only. `alg` must be `HS256`; `hash` must base64-decode to exactly the 32-byte + `HMAC-SHA256(share, Data(policyBase64.utf8))`, compared in constant time. The legacy `Base64(hex(HMAC))` form is refused. +- Key shares on this path are exactly 32 bytes. +- No error message contains key material, a key share or an HMAC. +- Existing RSA output and the TDF-JSON / TDF-CBOR EC scheme are unchanged. +- Run `swiftformat --swiftversion 6.2 .` before every commit. +- Work on branch `feat/66-kas-side-ec-rewrap`. Subagents never run `git checkout`, `git switch` or `git reset`; check + `git branch --show-current` after each commit. +- Commit messages end with: + ``` + Co-Authored-By: Claude Opus 5.5 + Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B + ``` +- Do not push, tag or publish a release. The owner gives that go-ahead separately. + +## Review Focus + +1. A KAO `ephemeralPublicKey` PEM with `\r\n` line endings or no trailing newline must parse (Task 2 test + `testRewrapAcceptsCRLFPEM`). +2. A `TDFKasInfo` whose `keyType` does not match its PEM (`.ecP256` with an RSA PEM, `.rsa` with an EC PEM) must throw, + not crash or write a broken KAO (Task 3 test `testKeyTypeAndPEMMismatchThrows`). +3. An empty-string `kid` is refused the same as nil (Task 3 test `testECKasWithoutKidIsRefused`). +4. A KAO decoded from JSON whose `policyBinding` is a bare string (decoded as `HS256`) verifies normally (Task 2 test + `testBareStringBindingVerifies`). +5. A `wrappedKey` that is not standard base64 (base64url alphabet, embedded newline) throws + `invalidWrappedKeyEncoding` (Task 2 test `testNonBase64WrappedKeyIsRefused`). + +--- + +### Task 1: Go fixture and `TDFKAS.unwrap` + +**Files:** +- Create: `scripts/interop/ec-wrapped/main.go`, `scripts/interop/ec-wrapped/go.mod`, `scripts/interop/ec-wrapped/go.sum`, + `scripts/interop/ec-wrapped/README.md` +- Create: `OpenTDFKit/TDF/TDFKAS.swift` +- Create: `OpenTDFKitTests/TDFKASGoFixture.swift`, `OpenTDFKitTests/TDFKASTests.swift` +- Modify: `OpenTDFKit/KASRewrapClient.swift` (`unwrapKey`, around line 1079) + +**Interfaces:** +- Produces: + - `public enum TDFKAS` with + `public static func unwrap(wrappedKey: Data, sessionPublicKey: P256.KeyAgreement.PublicKey, receiverPrivateKey: P256.KeyAgreement.PrivateKey) throws -> SymmetricKey` + - `public enum TDFKASError: Error, CustomStringConvertible, Equatable` with cases + `unsupportedKeyAccessType(String)`, `missingEphemeralPublicKey`, `ephemeralKeyNotPEM`, `invalidEphemeralPublicKey`, + `invalidWrappedKeyEncoding`, `keyUnwrapFailed`, `policyBindingRefused` + - `struct GoFixture: Decodable` (test target) with `kasPrivateKeyPEM`, `policyBase64`, `kao: TDFKeyAccessObject`, + `dekBase64`, `receiverPrivateKeyPEM`, `response: { wrappedKeyBase64, sessionPublicKeyPEM }`, and + `static func load() throws -> GoFixture` decoding `TDFKASGoFixture.json` + - Go program subcommand `generate` (prints that JSON to stdout) + +- [ ] **Step 1: Commit the approved spec and this plan** + +```bash +git add docs/superpowers/specs/2026-11-08-kas-side-ec-rewrap-design.md docs/superpowers/plans/2026-11-08-kas-side-ec-rewrap.md +git commit -m "docs: design and plan for KAS-side TDF EC rewrap (#66)" +``` + +- [ ] **Step 2: Write the go program's `generate` subcommand** + +`go.mod`: module `github.com/arkavo-org/OpenTDFKit/scripts/interop/ec-wrapped`, `require +github.com/opentdf/platform/lib/ocrypto v0.14.0`. `go mod tidy` writes `go.sum`. + +`generate` builds everything with `ocrypto`, mirroring the go reference exactly: +- KAS key: `NewECKeyPair(ECCModeSecp256r1)`; `kasPrivateKeyPEM` = `PrivateKeyInPemFormat()`. +- Random 32-byte DEK. Policy JSON `{"uuid":"","body":{"dataAttributes":[],"dissem":["interop@example.com"]}}`; + `policyBase64` = std base64 of it. +- KAO, as `sdk/tdf.go` `generateWrapKeyWithEC`: fresh ephemeral pair, `ComputeECDHKey(ephPrivPEM, kasPubPEM)`, + `CalculateHKDF(sha256("TDF"), ecdh)`, `NewAESGcm(key).Encrypt(dek)`; `wrappedKey` = std base64; + `ephemeralPublicKey` = ephemeral `PublicKeyInPemFormat()`. JSON keys: `type` `"ec-wrapped"`, `url` + `"https://kas.example.com"`, `protocol` `"kas"`, `wrappedKey`, `policyBinding` `{"alg":"HS256","hash": base64(raw + HMAC-SHA256(dek, []byte(policyBase64)))}` (spec form, not hex), `kid` `"e1"`, `schemaVersion` `"1.0"`, + `ephemeralPublicKey`. +- Response, as the platform's `rewrap.go`: fresh receiver pair; `FromPublicPEMWithSalt(receiverPubPEM, sha256("TDF"), + nil)`; `Encrypt(dek)` gives `wrappedKeyBase64`; the encryptor's `PublicKeyInPemFormat()` gives + `sessionPublicKeyPEM`. `receiverPrivateKeyPEM` = the receiver's private PEM. + +`README.md`: what the program is, `go run . generate > fixture.json`, and that the output goes into +`OpenTDFKitTests/TDFKASGoFixture.swift` verbatim. + +- [ ] **Step 3: Generate the fixture and embed it** + +Run: `cd scripts/interop/ec-wrapped && go run . generate` +Expected: one JSON object with every field above. Paste it into `OpenTDFKitTests/TDFKASGoFixture.swift` as +`enum TDFKASGoFixture { static let json = #""" … """# }`, with a comment naming the generator and the ocrypto +version. Add `GoFixture` and `load()` in the same file. + +- [ ] **Step 4: Write the failing tests** in `OpenTDFKitTests/TDFKASTests.swift` (`final class TDFKASTests: XCTestCase`) + +```swift +/// Interop link (a): unwrap uses the go session scheme. +func testUnwrapOpensGoSealedResponse() throws { + let f = try GoFixture.load() + let share = try TDFKAS.unwrap( + wrappedKey: Data(base64Encoded: f.response.wrappedKeyBase64)!, + sessionPublicKey: P256.KeyAgreement.PublicKey(pemRepresentation: f.response.sessionPublicKeyPEM), + receiverPrivateKey: P256.KeyAgreement.PrivateKey(pemRepresentation: f.receiverPrivateKeyPEM)) + XCTAssertEqual(share.withUnsafeBytes { Data($0) }, Data(base64Encoded: f.dekBase64)) +} + +func testUnwrapWithAnotherReceiverKeyFails() throws { + // same fixture, receiverPrivateKey: P256.KeyAgreement.PrivateKey() + // XCTAssertThrowsError → XCTAssertEqual($0 as? TDFKASError, .keyUnwrapFailed) +} + +func testUnwrapRefusesNon32ByteShare() throws { + // seal 16 random bytes to a fresh receiver with `standardTDFSessionSalt` (local helper, CryptoKit) + // → .keyUnwrapFailed +} +``` + +- [ ] **Step 5: Run to verify they fail** + +Run: `swift test --filter TDFKASTests` +Expected: compile failure, `cannot find 'TDFKAS' in scope`. + +- [ ] **Step 6: Implement** + +In `TDFKAS.swift`: the error enum (descriptions name the failure only; `ephemeralKeyNotPEM`'s says the key is +not PEM and that the TDF-JSON / TDF-CBOR EC scheme is not served here), and `unwrap`, which calls +`KASRewrapClient.unwrapKey(wrappedKey:sessionPublicKey: sessionPublicKey.compressedRepresentation, clientPrivateKey: +receiverPrivateKey.rawRepresentation, salt: KASRewrapClient.standardTDFSessionSalt)`, maps any thrown error to +`.keyUnwrapFailed`, and refuses a result that is not 32 bytes with `.keyUnwrapFailed`. Doc comments say "key share" +(the DEK for a single-split TDF). + +In `KASRewrapClient.unwrapKey`: make the opened `Data` a `var` and `defer { decryptedKey.secureZero() }` before +returning `SymmetricKey(data:)`, as `TDFCrypto.unwrapSymmetricKeyWithEC` already does. + +- [ ] **Step 7: Run to verify they pass, and nothing else broke** + +Run: `swift test --filter TDFKASTests && swift test --filter KASRewrap` +Expected: all pass. + +- [ ] **Step 8: Commit** + +```bash +swiftformat --swiftversion 6.2 . +git add scripts/interop/ec-wrapped OpenTDFKit/TDF/TDFKAS.swift OpenTDFKit/KASRewrapClient.swift OpenTDFKitTests/TDFKASGoFixture.swift OpenTDFKitTests/TDFKASTests.swift +git commit -m "feat(kas): TDF EC client unwrap and go interop fixture (#66)" +``` + +--- + +### Task 2: Go-scheme EC wrap and `TDFKAS.rewrap` + +**Files:** +- Modify: `OpenTDFKit/TDF/TDFCrypto.swift` (new function after the existing EC section) +- Modify: `OpenTDFKit/TDF/TDFKAS.swift` +- Test: `OpenTDFKitTests/TDFKASTests.swift` + +**Interfaces:** +- Consumes: Task 1's `TDFKAS`, `TDFKASError`, `GoFixture`. +- Produces: + - `public struct KASECWrappedKey: Sendable { public let wrappedKey: String; public let ephemeralPublicKeyPEM: String }` + - `TDFCrypto.wrapSymmetricKeyWithECForKAS(publicKeyPEM: String, symmetricKey: SymmetricKey) throws -> KASECWrappedKey` + - `TDFKAS.RewrapResult`, declared in an `extension TDFKAS` as `public struct RewrapResult: Sendable { public let wrappedKey: Data; public let sessionPublicKey: P256.KeyAgreement.PublicKey }` + - `TDFKAS.rewrap(keyAccessObject: TDFKeyAccessObject, policyBase64: String, kasPrivateKey: P256.KeyAgreement.PrivateKey, receiverPublicKey: P256.KeyAgreement.PublicKey) throws -> RewrapResult` + +- [ ] **Step 1: Write the failing tests** + +Test helper (in the test file): `makeKAO(share: SymmetricKey, kasPublicKey: P256.KeyAgreement.PublicKey, policyJSON: +Data) throws -> (TDFKeyAccessObject, policyBase64: String)` using `wrapSymmetricKeyWithECForKAS(publicKeyPEM: +kasPublicKey.pemRepresentation, …)` and `TDFCrypto.policyBinding(policy:symmetricKey:)`, `type: .ecWrapped`, `kid: "e1"`. + +```swift +/// Link (c): rewrap reads the go KAO scheme. Link (b): unwrap opens rewrap's output. +func testRewrapOpensGoKAOAndUnwrapOpensResult() throws { + let f = try GoFixture.load() + let receiver = P256.KeyAgreement.PrivateKey() + let r = try TDFKAS.rewrap(keyAccessObject: f.kao, policyBase64: f.policyBase64, + kasPrivateKey: .init(pemRepresentation: f.kasPrivateKeyPEM), receiverPublicKey: receiver.publicKey) + let share = try TDFKAS.unwrap(wrappedKey: r.wrappedKey, sessionPublicKey: r.sessionPublicKey, receiverPrivateKey: receiver) + XCTAssertEqual(share.withUnsafeBytes { Data($0) }, Data(base64Encoded: f.dekBase64)) +} + +func testWrapThenRewrapRoundTrip() // makeKAO → rewrap → unwrap == share; KAO ephemeralPublicKey hasPrefix "-----BEGIN PUBLIC KEY-----" +func testRewrapResultIsFresh() // two rewraps of one input: sessionPublicKey.rawRepresentation differ, wrappedKey.prefix(12) differ + +// Each of these: XCTAssertThrowsError → XCTAssertEqual($0 as? TDFKASError, .policyBindingRefused) +func testTamperedPolicyIsRefused() // one base64 character of policyBase64 changed +func testDecodedPolicyJSONIsRefused() // policyBase64: String(decoding: policyJSON, as: UTF8.self) +func testTamperedBindingHashIsRefused() // one character of policyBinding.hash changed +func testLegacyHexBindingIsRefused() // hash = base64(hex string of the correct HMAC) +func testNonHS256AlgIsRefused() // policyBinding.alg = "GMAC" +func testBareStringBindingVerifies() // KAO JSON re-encoded with "policyBinding": "", decoded, rewrap succeeds + +// Each of these: .keyUnwrapFailed +func testFlippedNonceByteIsRefused() // byte 0 of the decoded wrappedKey +func testFlippedCiphertextByteIsRefused() // byte 12 +func testFlippedTagByteIsRefused() // last byte +func testTruncatedWrappedKeyIsRefused() // drop the last byte; also a 20-byte prefix +func testSixteenByteShareIsRefused() // makeKAO with SymmetricKey(size: .bits128) +func testWrongKASPrivateKeyIsRefused() + +func testNonBase64WrappedKeyIsRefused() // base64url alphabet ("-", "_") and an embedded "\n" → .invalidWrappedKeyEncoding +func testWrongKAOTypeIsRefused() // type .wrapped → .unsupportedKeyAccessType("wrapped") +func testMissingEphemeralKeyIsRefused() // nil → .missingEphemeralPublicKey +func testSEC1EphemeralKeyIsRefused() // base64 compressed SEC1 → .ephemeralKeyNotPEM +func testTDFJSONContainerKAOIsRefused() // TDFJSONBuilder().kasURL(…).kasPublicKey(kasPub.pemRepresentation).policy(…).encrypt → keyAccess[0] → .ephemeralKeyNotPEM +func testP384EphemeralKeyIsRefused() // P384.KeyAgreement.PrivateKey().publicKey.pemRepresentation → .invalidEphemeralPublicKey +func testRewrapAcceptsCRLFPEM() // ephemeralPublicKey with "\n" → "\r\n", and with the trailing newline removed: both succeed +``` + +- [ ] **Step 2: Run to verify they fail** + +Run: `swift test --filter TDFKASTests` +Expected: compile failure, `type 'TDFKAS' has no member 'rewrap'`. + +- [ ] **Step 3: Implement `wrapSymmetricKeyWithECForKAS`** + +Load the KAS key with `P256.KeyAgreement.PublicKey(pemRepresentation:)`, fresh ephemeral key, ECDH, HKDF (`standardTDFSessionSalt`, +empty info, 32), `AES.GCM.seal` with a random nonce, `combined` base64. `ephemeralPublicKeyPEM` = +`ephemeral.publicKey.pemRepresentation`. Errors from loading surface as `TDFCryptoError`. Doc comment: the go SDK / +platform `ec-wrapped` scheme, distinct from `wrapSymmetricKeyWithEC`. + +- [ ] **Step 4: Implement `rewrap`** + +Steps exactly as the spec's §1 list: +1. `type == .ecWrapped` else `.unsupportedKeyAccessType(type.rawValue)`; `ephemeralPublicKey` non-nil else + `.missingEphemeralPublicKey`. +2. If the trimmed string does not start with `-----BEGIN PUBLIC KEY-----`, `.ephemeralKeyNotPEM`. Normalize `\r\n` to + `\n`, then `P256.KeyAgreement.PublicKey(pemRepresentation:)`; failure → `.invalidEphemeralPublicKey`. +3. `Data(base64Encoded: wrappedKey)` (no options) else `.invalidWrappedKeyEncoding`. Fewer than 29 bytes, + `SealedBox(combined:)` or `open` failure, or a result that is not 32 bytes → `.keyUnwrapFailed`. +4. `var share` with `defer { share.secureZero() }` immediately after it is opened. +5. Binding: `alg == "HS256"`, `Data(base64Encoded: hash)` exactly 32 bytes, `HMAC.isValidAuthenticationCode(_: + authenticating: Data(policyBase64.utf8), using: SymmetricKey(data: share))`. Any failure → `.policyBindingRefused`. +6. Fresh `P256.KeyAgreement.PrivateKey()`, ECDH with `receiverPublicKey`, same HKDF, `AES.GCM.seal(share, …)`, return + `combined` and the session public key. + +`rewrap`'s doc comment carries the spec's two security notes ("does not prove who made the KAO"; "do not forward which +step failed") and the `policyBase64` encoding rule. + +- [ ] **Step 5: Run to verify they pass** + +Run: `swift test --filter TDFKASTests` +Expected: all pass. + +- [ ] **Step 6: Commit** + +```bash +swiftformat --swiftversion 6.2 . +git add OpenTDFKit/TDF/TDFCrypto.swift OpenTDFKit/TDF/TDFKAS.swift OpenTDFKitTests/TDFKASTests.swift +git commit -m "feat(kas): KAS-side TDF ec-wrapped rewrap (#66)" +``` + +--- + +### Task 3: `ec-wrapped` KAOs from `TDFEncryptor` + +**Files:** +- Modify: `OpenTDFKit/TDF/TDFProcessor.swift` (`TDFKasInfo` lines 4-16; wrap sites in `encryptFile` ~117, + `encryptFileMultiSegment` ~229, `makeResult` ~413; new `TDFEncryptError` beside `TDFDecryptError` ~740) +- Modify: `OpenTDFKit/TDF/TDFCrypto.swift` (doc comments of `wrapSymmetricKeyWithEC`, `unwrapSymmetricKeyWithEC`, + `ECWrappedKeyResult`) +- Test: `OpenTDFKitTests/TDFKASEncryptorTests.swift` + +**Interfaces:** +- Consumes: Task 2's `wrapSymmetricKeyWithECForKAS`, `TDFKAS.rewrap`, `TDFKAS.unwrap`. +- Produces: + - `TDFKasInfo.KeyType: Sendable, Equatable { case rsa, ecP256 }`; `public let keyType: KeyType`; + `init(url:publicKeyPEM:kid:schemaVersion:keyType: KeyType = .rsa)` + - `public enum TDFEncryptError: Error, CustomStringConvertible, Equatable { case ecKasRequiresKeyID, ecKasRequiresAES256 }` + +- [ ] **Step 1: Write the failing tests** (`final class TDFKASEncryptorTests: XCTestCase`) + +Helper: `makeECKas(kid: String? = "e1") -> (TDFKasInfo, P256.KeyAgreement.PrivateKey)` with `keyType: .ecP256` and +`publicKeyPEM: kasKey.publicKey.pemRepresentation`. `openThroughKAS(_ result: TDFEncryptionResult, kasKey:) throws -> +Data` does `rewrap(keyAccessObject: keyAccess[0], policyBase64: encryptionInformation.policy, …)` → `unwrap` → +`TDFDecryptor().decrypt(container:symmetricKey:)`. + +```swift +/// Link (d): the encryptor writes the go KAO scheme. This proves PEM output only while +/// rewrap accepts PEM alone; keep that comment if rewrap's parsing ever changes. +func testEncryptPlaintextWritesECWrappedKAO() // encrypt(plaintext:configuration:): keyAccess.count == 1, type == .ecWrapped, + // kid == "e1", ephemeralPublicKey hasPrefix "-----BEGIN PUBLIC KEY-----", + // openThroughKAS == plaintext +func testEncryptSegmentedWritesECWrappedKAO() // encrypt(plaintext:configuration:segmentSize: 1024) on 5_000 bytes +func testEncryptFileWritesECWrappedKAO() // encryptFile to a temp dir, TDFLoader().load, open +func testEncryptFileMultiSegmentWritesECWrappedKAO() // segmentSizes [1024, 1024, 2952] +func testECKasWithoutKidIsRefused() // kid nil and kid "" → TDFEncryptError.ecKasRequiresKeyID, no output file written +func testECKasWithAES128IsRefused() // keySize .bits128 → .ecKasRequiresAES256 +func testKeyTypeAndPEMMismatchThrows() // .ecP256 + RSA PEM, .rsa + EC PEM: both throw (any error) +func testRSAKasOutputIsUnchanged() // default keyType: type .wrapped, ephemeralPublicKey nil, schemaVersion "1.0", + // binding verifies, TDFCrypto.unwrapSymmetricKeyWithRSA gives result.symmetricKey +``` + +Use `generateTestRSAKeyPair()` (already used by `TDFTests`) for RSA PEMs. + +- [ ] **Step 2: Run to verify they fail** + +Run: `swift test --filter TDFKASEncryptorTests` +Expected: compile failure, `extra argument 'keyType' in call`. + +- [ ] **Step 3: Implement** + +- `TDFKasInfo.KeyType` and `keyType` as above. +- `TDFEncryptError` with descriptions. +- A private `TDFEncryptor` helper `func validate(_ configuration: TDFEncryptionConfiguration) throws`, called first in + `encryptFile`, `encryptFileMultiSegment`, `encrypt(plaintext:configuration:)` and + `encrypt(plaintext:configuration:segmentSize:)`: for `.ecP256`, a nil or empty `kid` throws `.ecKasRequiresKeyID` + and `keySize != .bits256` throws `.ecKasRequiresAES256`. +- A private helper `func makeKeyAccessObject(kas: TDFKasInfo, symmetricKey: SymmetricKey, policyBinding: + TDFPolicyBinding) throws -> TDFKeyAccessObject` replacing the three inline RSA wrap + `TDFKeyAccessObject(…)` blocks: + `.rsa` builds today's object unchanged; `.ecP256` uses `wrapSymmetricKeyWithECForKAS` and sets `type: + .ecWrapped`, `ephemeralPublicKey: wrapped.ephemeralPublicKeyPEM`, the same `url`, `kid`, `schemaVersion ?? "1.0"`. +- Doc comments: `wrapSymmetricKeyWithEC` / `unwrapSymmetricKeyWithEC` are the TDF-JSON / TDF-CBOR draft scheme (empty + salt, compressed SEC1 ephemeral key), not the platform's `ec-wrapped`; point to `wrapSymmetricKeyWithECForKAS`. + `ECWrappedKeyResult.ephemeralPublicKey` is base64 compressed SEC1, not PEM. + +- [ ] **Step 4: Run to verify they pass, plus the existing TDF suites** + +Run: `swift test --filter TDFKAS && swift test --filter TDF` +Expected: all pass. + +- [ ] **Step 5: Commit** + +```bash +swiftformat --swiftversion 6.2 . +git add OpenTDFKit/TDF/TDFProcessor.swift OpenTDFKit/TDF/TDFCrypto.swift OpenTDFKitTests/TDFKASEncryptorTests.swift +git commit -m "feat(tdf): ec-wrapped key access objects from TDFEncryptor (#66)" +``` + +--- + +### Task 4: Swift → go verification, docs + +**Files:** +- Modify: `scripts/interop/ec-wrapped/main.go`, `scripts/interop/ec-wrapped/README.md` +- Modify: `OpenTDFKitTests/TDFKASEncryptorTests.swift` +- Modify: `CLAUDE.md`, `MIGRATION_GUIDE.md`, `README.md` (if it lists TDF APIs) + +**Interfaces:** +- Consumes: Tasks 1-3. +- Produces: go subcommand `verify `; env var `OPENTDFKIT_INTEROP_OUT`. + +- [ ] **Step 1: Write the fixture-writing test** + +`testWriteSwiftFixtureForGo`: `XCTSkip` unless `OPENTDFKIT_INTEROP_OUT` is set. Otherwise: a fresh KAS key, a policy, +`TDFEncryptor().encrypt(plaintext:configuration:)` with `.ecP256`, a fresh receiver key, `TDFKAS.rewrap` of the +written KAO; write JSON in Task 1's fixture shape (`kasPrivateKeyPEM`, `policyBase64`, `kao` as the manifest encodes +it, `dekBase64` = `result.symmetricKey`, `receiverPrivateKeyPEM`, `response` with `sessionPublicKey.pemRepresentation`) +to that path. + +- [ ] **Step 2: Write the go `verify` subcommand** + +Reads the file and fails loudly at the first mismatch: +- Open the KAO the way the platform does: `pem.Decode` the `ephemeralPublicKey` (fail if nil), `x509.ParsePKIXPublicKey`, + `*ecdsa.PublicKey`, `CompressedECPublicKey(ECCModeSecp256r1, …)`, then `NewSaltedECDecryptor(ECPrivateKeyFromPem(kas), + sha256("TDF"), nil).DecryptWithEphemeralKey(wrapped, compressed)`; must equal the DEK. +- Binding: base64-decode `hash` to 32 bytes, `hmac.Equal` with HMAC-SHA256(dek, []byte(policyBase64)); `alg` is `HS256`. +- Open the response the way the go SDK client does: `ComputeECDHKey(receiverPrivPEM, sessionPubPEM)`, + `CalculateHKDF(sha256("TDF"), …)`, `NewAESGcm(…).Decrypt(wrapped)`; must equal the DEK. +- Print `OK` and exit 0. + +- [ ] **Step 3: Run the check** + +```bash +OPENTDFKIT_INTEROP_OUT="$PWD/swift-interop.json" swift test --filter TDFKASEncryptorTests/testWriteSwiftFixtureForGo +(cd scripts/interop/ec-wrapped && go run . verify "$OLDPWD/swift-interop.json") +rm swift-interop.json +``` +Expected: the test passes (not skipped), then `OK`. Paste the output into the task report; it goes in the PR +description. A failure here blocks the release. + +- [ ] **Step 4: Docs** + +- `CLAUDE.md` Project Structure: a **TDFKAS** entry (pure KAS-side `ec-wrapped` rewrap and client unwrap, the + salt, PEM-only, spec-form binding only, 32-byte shares, and the two security notes in one line each), and under + **TDFProcessor** the `TDFKasInfo.keyType` (`.rsa` default, `.ecP256` needs a `kid` and AES-256). +- `MIGRATION_GUIDE.md`: a `v5.2.0` section, additive: the new types and functions, `TDFKasInfo.keyType`, the + `KASRewrapClient.unwrapKey` wipe, and that `wrapSymmetricKeyWithEC` is the TDF-JSON/CBOR scheme. +- `README.md`: only if it already documents TDF encryption APIs; one short `ec-wrapped` example. + +- [ ] **Step 5: Full suite** + +Run: `swift build && swift test` +Expected: all pass except tests that already need a live platform and skip without one. + +- [ ] **Step 6: Commit** + +```bash +swiftformat --swiftversion 6.2 . +git add scripts/interop/ec-wrapped OpenTDFKitTests/TDFKASEncryptorTests.swift CLAUDE.md MIGRATION_GUIDE.md README.md +git commit -m "test(interop): verify Swift ec-wrapped output with go; docs for 5.2.0 (#66)" +``` diff --git a/docs/superpowers/plans/2026-11-09-owner-kas-rewrap.md b/docs/superpowers/plans/2026-11-09-owner-kas-rewrap.md new file mode 100644 index 0000000..4df4698 --- /dev/null +++ b/docs/superpowers/plans/2026-11-09-owner-kas-rewrap.md @@ -0,0 +1,365 @@ +# Owner KAS Rewrap Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Items 2–8 of the revised #66: the owner's phone can verify a Rewrap and build its response, and +`KASRewrapClient` can call a KAS that answers later (202 polling, caller `exp`, extension member, full results), with +path-aware key access object matching. + +**Architecture:** +- The phone half is pure `TDFKAS` functions: shared digests, request verification and a response builder. +- The client half is new `KASRewrapClient` methods (`prepareRewrap`, `submitRewrap`, `pollRewrap`, `rewrap`) that + leave the existing methods unchanged. +- Path-aware matching changes `matchesKasURL`, and with it every client path. +- An end-to-end test runs the real client against a fake transport that plays relay and phone with the `TDFKAS` + functions. + +**Tech Stack:** Swift 6.2, CryptoKit, XCTest. + +**Spec:** `docs/superpowers/specs/2026-11-09-owner-kas-rewrap-design.md` (extends +`docs/superpowers/specs/2026-11-08-kas-side-ec-rewrap-design.md`). + +## Global Constraints + +- No new package dependencies. The existing `KASRewrapClient`, `rewrapTDF`, `rewrapAndUnwrapTDF`, + `rewrapAndUnwrapTDFShares` and bulk API keep their behavior, except for matching (Task 2). +- `requestTokenDigest` = SHA-256 of the compact JWT's UTF-8 bytes. The phone and the client both call + `TDFKAS.requestTokenDigest`. +- `keyAccessObjectDigest`: + - SHA-256 over the tag `OpenTDFKit/kao-digest/v1`; + - then, in order, `type`, `url`, `protocol`, `wrappedKey`, `policyBinding.alg` (empty → `HS256`), + `policyBinding.hash`, `kid`, `sid`, `encryptedMetadata`, `ephemeralPublicKey`; + - each field is a presence byte (0/1), then, if present, a 4-byte big-endian length and its UTF-8 bytes; + - `schemaVersion` is excluded. +- `publicKeyFingerprint` = SHA-256 of `x963Representation` (65 bytes). +- Phone limits: + - bodies at most 65,536 bytes; + - only JWT `alg` `ES256`, with a raw 64-byte signature over `header.payload` as received; + - `exp` is returned, not enforced. +- Standard `requestBody` member names: `clientPublicKey`, `requests`, `keyAccess`, `policy`, `algorithm`, + `schemaVersion`. +- `Retry-After`: delta-seconds only, default 2 s, clamped to 1–60 s, never past the deadline. +- `Location`: resolved against the Rewrap URL, and must keep its scheme, host and effective port. +- Poll statuses: `202` repeats; `200` is answered; `410` is expired; `404` at or after the handle's `expiresAt` is + expired; a `404` before it throws `.httpError(404, …)`. +- Matching: case-insensitive scheme and host, the effective port, and the normalized path (trailing `/` trimmed, `/kas` + ≡ empty, case-sensitive). +- No error description contains key material, a share, an HMAC or a token. +- Run `swiftformat --swiftversion 6.2 .` before every commit. +- Work on branch `feat/66-kas-side-ec-rewrap`. Never `git checkout`, `switch` or `reset`; check + `git branch --show-current` after each commit. +- Commit messages end with: + ``` + Co-Authored-By: Claude Opus 5.5 + Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B + ``` +- Push only to update PR #68. No tag or release. + +## Review Focus + +1. A `requestBody` whose extension holds non-ASCII text or escaped `/` must come back from `verifyRewrapRequest` as + JSON equal to what was sent (Task 3: `testExtensionRoundTripsUnicodeAndSlashes`). +2. A `Retry-After` of `0`, a negative value or a huge value is clamped, and never sleeps past the deadline (Task 6: + `testRetryAfterIsClamped`). +3. A `Location` that is absolute but on the same origin is followed; protocol-relative (`//evil.example/x`) and other + origins are refused (Task 6: `testLocationOriginRules`). +4. A 200 answer with `sessionPublicKey` absent and only fail results (a pure DENY) parses without throwing (Task 6: + `testDenyOnlyAnswerParses`). +5. A KAO URL with a different-case path (`/OWNER-KAS/…`) does not match; a different-case host does (Task 2: + `testPathIsCaseSensitiveHostIsNot`). + +--- + +### Task 1: Shared digests + +**Files:** +- Create: `OpenTDFKit/TDF/TDFKASDigests.swift` +- Test: `OpenTDFKitTests/TDFKASDigestTests.swift` + +**Interfaces:** +- Produces: `TDFKAS.requestTokenDigest(_ token: String) -> Data`, + `TDFKAS.keyAccessObjectDigest(_ kao: TDFKeyAccessObject) -> Data`, + `TDFKAS.publicKeyFingerprint(_ key: P256.KeyAgreement.PublicKey) -> Data` + +- [ ] **Step 1: Commit the approved spec and this plan.** + `git add docs/superpowers/specs/2026-11-08-kas-side-ec-rewrap-design.md docs/superpowers/specs/2026-11-09-owner-kas-rewrap-design.md docs/superpowers/plans/2026-11-09-owner-kas-rewrap.md`. + Commit as `docs: design and plan for owner-KAS rewrap (#66)`. + +- [ ] **Step 2: Write the failing tests** (`final class TDFKASDigestTests: XCTestCase`) + +```swift +func testRequestTokenDigestIsSHA256OfTokenBytes() // == Data(SHA256.hash(data: Data("a.b.c".utf8))) +func testKAODigestKnownVector() // a fixed KAO (all fields set) → hex string written into the test from a + // hand-assembled byte buffer built in the test, independently of the implementation +func testKAODigestIgnoresSchemaVersion() // schemaVersion "1.0" vs nil → equal +func testKAODigestEmptyAlgIsHS256() // alg "" vs "HS256" → equal +func testKAODigestChangesWithEachIncludedField() // mutate each of the 10 fields in turn → all digests distinct +func testKAODigestAbsentVersusEmptyDiffer() // kid nil vs kid "" → different +func testKAODigestSameForManifestAndForwardedKAO() // KAO from TDFEncryptor (.ecP256); round-trip it through the client's + // request encoding (JSONEncoder of the request entry), decode → equal digest +func testFingerprintIndependentOfPEMLayout() // key from PEM (LF), PEM (CRLF), x963 bytes → equal; == SHA256(x963) +``` + +- [ ] **Step 3: Run:** `swift test --filter TDFKASDigestTests`. Expected: compile failure, `has no member 'requestTokenDigest'`. + +- [ ] **Step 4: Implement** the three functions in `TDFKASDigests.swift` as `extension TDFKAS`. The algorithm is fixed + by the Global Constraints. + +- [ ] **Step 5: Run:** `swift test --filter TDFKASDigestTests`. Expected: PASS. + +- [ ] **Step 6: Commit** `feat(kas): shared request, KAO and key digests (#66)`. + +--- + +### Task 2: Path-aware key access object matching + +**Files:** +- Modify: `OpenTDFKit/KASRewrapClient.swift` (`matchesKasURL`, ~line 1042) +- Test: `OpenTDFKitTests/KASRewrapMatchingTests.swift` + +**Interfaces:** +- Produces: the behavior of `keyAccessObjects(in:)`. Nothing new is public. + +- [ ] **Step 1: Write the failing tests.** Clients come from `forKasConnect(uri)`. The manifest holds KAOs at the + table's URLs, with `h = platform.arkavo.net` and `R = 01HZXK3Q8R4M5N6P7Q8R9S0T1V`. + +```swift +func testPlatformClientSelectsPlatformKAOsOnly() // uri https://h → selects https://h/kas and https://h, not the owner KAO +func testKasPathClientSelectsPlatformKAOsOnly() // uri https://h/kas → same +func testOwnerClientSelectsOwnKAOOnly() // uri https://h/owner-kas/v1/routes/R → only that KAO +func testTrailingSlashesIgnored() // KAO https://h/kas/ and https://h/owner-kas/v1/routes/R/ match their clients +func testPathIsCaseSensitiveHostIsNot() // https://H/kas matches the platform client; https://h/OWNER-KAS/v1/routes/R doesn't match the owner client +func testOtherPrefixDoesNotMatchPathlessClient() // https://h/api/kas does not match uri https://h (the spec's stated cost) +``` + +- [ ] **Step 2: Run:** `swift test --filter KASRewrapMatchingTests`. Expected: the owner-KAO and prefix tests FAIL, + because today's matching is host-only. + +- [ ] **Step 3: Implement.** In `matchesKasURL`, after the scheme, host and port checks, compare `normalizedPath(_:)` + of both URLs: trim trailing `/`, then map `/kas` to `""`. + +- [ ] **Step 4: Run:** `swift test --filter "KASRewrapMatchingTests|KASRewrap|KASBulkRewrap"`. Expected: PASS, and + the existing matching tests stay green. + +- [ ] **Step 5: Commit** `fix(kas): match key access objects by path too (#66)`. + +--- + +### Task 3: Verify a received Rewrap (phone) + +**Files:** +- Create: `OpenTDFKit/TDF/TDFKASRequest.swift` +- Modify: `OpenTDFKit/TDF/TDFKAS.swift` (new `TDFKASError` cases) +- Modify: `OpenTDFKit/KASRewrapClient.swift` (internal `Data.init?(base64URLEncoded:)` beside `base64URLEncodedString`) +- Test: `OpenTDFKitTests/TDFKASRequestTests.swift` + +**Interfaces:** +- Consumes: `TDFKAS.requestTokenDigest` (Task 1). +- Produces: + - `TDFKAS.verifyRewrapRequest(body: Data, signingPublicKey: P256.Signing.PublicKey) throws -> TDFKAS.RewrapRequest`. + - `TDFKAS.RewrapRequest`, with the fields from the spec: `requestToken`, `requestTokenDigest`, `issuedAt`, + `expiresAt`, `clientPublicKey`, `policies`, `extensions`. + - `TDFKAS.RewrapRequest.Policy` holds `policyId`, `policyBase64` and `keyAccessObjects: [KeyAccessEntry]`, where + `KeyAccessEntry` is a struct `{ id: String; keyAccessObject: TDFKeyAccessObject }` (a struct rather than a tuple, + so it is `Sendable`). + - New `TDFKASError` cases: `requestTooLarge`, `malformedRewrapRequest(String)` (the string names the field, never its + value), `unsupportedRequestAlgorithm(String)`, `requestSignatureInvalid`. + +- [ ] **Step 1: Write the failing tests.** A test helper `signedRequest(requestBody: [String: Any], key:, header: + ["alg": "ES256"], exp:, iat:) -> Data` builds `{"signed_request_token": JWT}` independently of the library. It uses + JSONSerialization, base64url and `key.signature(for:).rawRepresentation`. + +```swift +func testValidRequestVerifies() // fields equal what was sent: exp, iat, digest == requestTokenDigest(token), + // clientPublicKey, policyId, policyBase64, KAO id and decoded KAO, extensions["arkavo"] +func testExtensionRoundTripsUnicodeAndSlashes() // extension {"v":1,"note":"é/ü"} → JSONSerialization of extensions["arkavo"] equals the input object +func testOtherSigningKeyRefused() // .requestSignatureInvalid +func testPayloadChangedAfterSigningRefused() // swap the payload segment for a re-encoded one with exp+1 → .requestSignatureInvalid +func testSignatureChangedRefused() // flip one signature byte → .requestSignatureInvalid +func testAlgNoneAndHS256Refused() // → .unsupportedRequestAlgorithm("none") / ("HS256") +func testOversizedBodyRefused() // 65,537 bytes → .requestTooLarge +func testMalformedShapesRefused() // non-PEM clientPublicKey; requests []; policy.body not base64; + // KAO missing wrappedKey; no signed_request_token → .malformedRewrapRequest(_) +func testExpiredTokenStillParses() // exp = now - 3600 → verifies, expiresAt returned +func testStandardMembersAreNotExtensions() // requestBody with algorithm and keyAccess → extensions is empty for them +``` + +- [ ] **Step 2: Run:** `swift test --filter TDFKASRequestTests`. Expected: compile failure, `has no member 'verifyRewrapRequest'`. + +- [ ] **Step 3: Implement** in the spec's check order (§2, checks 1–7). The claims' `requestBody` is a JSON string. + Parse it with `JSONSerialization` to collect the extensions as raw member JSON, and decode the standard parts with + `JSONDecoder` into private Codable types. Re-encode each extension with + `JSONSerialization.data(withJSONObject:options: [.fragmentsAllowed])`. + +- [ ] **Step 4: Run:** `swift test --filter TDFKASRequestTests`. Expected: PASS. + +- [ ] **Step 5: Commit** `feat(kas): verify a received Rewrap on the owner KAS (#66)`. + +--- + +### Task 4: Build a Rewrap response (phone) + +**Files:** +- Create: `OpenTDFKit/TDF/TDFKASResponse.swift` +- Test: `OpenTDFKitTests/TDFKASResponseTests.swift` + +**Interfaces:** +- Produces: + - `TDFKAS.rewrapResponseBody(sessionPublicKey: P256.KeyAgreement.PublicKey?, responses: [TDFKAS.PolicyResponse]) throws -> Data`. + - `TDFKAS.PolicyResponse(policyId: String, results: [TDFKAS.KeyAccessResult])`. + - `TDFKAS.KeyAccessResult(keyAccessObjectId: String, status: TDFKAS.ResultStatus, kasWrappedKey: Data?, error: String?, metadata: [String: KASRewrapClient.RewrapMetadataValue])`. + - `TDFKAS.ResultStatus { case permit, fail }`. + - A new `TDFKASError` case, `invalidResult(String)`. + + The spec calls the result type `Result`. It is named `KeyAccessResult` here, so it doesn't shadow `Swift.Result`. + +- [ ] **Step 1: Write the failing tests.** + +```swift +func testPermitAndFailShape() // JSONSerialization of the output: sessionPublicKey is PEM; status "permit"/"fail"; + // kasWrappedKey std base64; fail result has no kasWrappedKey key; error present only when set +func testMetadataAllValueTypes() // string, number, bool, array, object, null → decoded back equal (via JSONDecoder of RewrapMetadataValue) +func testDenyWithoutSessionKey() // sessionPublicKey nil → member absent +func testInvalidCombinationsRefused() // permit without key; fail with key → .invalidResult(_) +``` + +- [ ] **Step 2: Run:** `swift test --filter TDFKASResponseTests`. Expected: compile failure. +- [ ] **Step 3: Implement.** Use private `Encodable` structs and `JSONEncoder` with `.sortedKeys`, and omit nil fields. +- [ ] **Step 4: Run:** `swift test --filter TDFKASResponseTests`. Expected: PASS. +- [ ] **Step 5: Commit** `feat(kas): build a Rewrap response on the owner KAS (#66)`. + +--- + +### Task 5: `prepareRewrap` (client) + +**Files:** +- Create: `OpenTDFKit/KASRewrapPending.swift` +- Modify: `OpenTDFKit/KASRewrapClient.swift`: + - `createSignedJWT` gains an `expiresAt: Date` parameter. The default call sites pass `now + 60`. + - `StandardUnsignedRewrapRequest` encoding is reused. + - New `KASRewrapError` cases `invalidRewrapOptions(String)`, `pendingWithoutLocation` and `unsafeLocation(String)`, + with descriptions. +- Test: `OpenTDFKitTests/KASRewrapPendingTests.swift` + +**Interfaces:** +- Consumes: `TDFKAS.requestTokenDigest` (Task 1) and `TDFKAS.verifyRewrapRequest` (Task 3, in the tests). +- Produces: + - `KASRewrapClient.RewrapOptions(expiresAt: Date? = nil, requestBodyExtension: RequestBodyExtension? = nil)`. + - `KASRewrapClient.RequestBodyExtension(name: String, json: Data)`. + - `KASRewrapClient.PreparedRewrap { body: Data; requestToken: String; requestTokenDigest: Data; expiresAt: Date; keyAccessObjects: [TDFKeyAccessObject] }`. + The last field is internal: the KAOs sent, in `kao-` order, for Task 6's `sid`. + - `func prepareRewrap(manifest: TDFManifest, clientPrivateKey: P256.KeyAgreement.PrivateKey, options: RewrapOptions = .init()) throws -> PreparedRewrap`. + +- [ ] **Step 1: Write the failing tests.** The client is built with a fixed `signingKey`. Verification uses + `TDFKAS.verifyRewrapRequest` with `signingKey.publicKey`. + +```swift +func testPreparedRequestVerifiesOnThePhone() // verifies; requestTokenDigest equal on both sides; expiresAt equal (to the second) +func testPolicyForwardedVerbatim() // phone policyBase64 == manifest.encryptionInformation.policy +func testSignedWithInitSigningKeyNotClientKey() // verify with clientPrivateKey's signing form → .requestSignatureInvalid +func testDefaultExpIsSixtySeconds() // expiresAt - issuedAt == 60 +func testCallerExp() // expiresAt = now + 900 → token exp equals it +func testPastExpRefused() // → KASRewrapError.invalidRewrapOptions +func testExtensionCoveredBySignature() // phone extensions["arkavo"] == the input JSON (object equality) +func testExtensionNameCollisionRefused() // each standard name → .invalidRewrapOptions +func testExtensionMustBeJSON() // json "not json" → .invalidRewrapOptions +func testOnlyThisKASKAOsSent() // a manifest with a platform KAO and an owner KAO; the owner client sends one KAO +``` + +- [ ] **Step 2: Run:** `swift test --filter KASRewrapPendingTests`. Expected: compile failure. +- [ ] **Step 3: Implement.** Encode the request as today, then add the extension with `JSONSerialization` and + re-serialize. Sign with `self.signingKey` and `expiresAt`. Compute the digest with `TDFKAS.requestTokenDigest`. +- [ ] **Step 4: Run:** `swift test --filter "KASRewrapPendingTests|KASRewrap"`. Expected: PASS, and the existing + rewrap tests stay green. +- [ ] **Step 5: Commit** `feat(kas): prepare a signed Rewrap with caller exp and extension (#66)`. + +--- + +### Task 6: `submitRewrap`, `pollRewrap`, `rewrap` (client) + +**Files:** +- Modify: `OpenTDFKit/KASRewrapPending.swift` +- Modify: `OpenTDFKit/KASRewrapClient.swift`. It gains internal stored `sleeper: @Sendable (TimeInterval) async throws + -> Void` (default `Task.sleep`) and `now: @Sendable () -> Date` (default `Date.init`), set through an internal + initializer that the public initializers call. +- Test: `OpenTDFKitTests/KASRewrapPendingTests.swift` + +**Interfaces:** +- Consumes: Task 5's `PreparedRewrap`, and `TDFKAS.unwrap`. +- Produces: the spec's `PendingRewrap`, `RewrapSubmission`, `RewrapPollOutcome`, `RewrapAnswer` (with its + `Result` → named `RewrapAnswer.KeyAccessResult`), `RewrapAnswer.share(for:clientPrivateKey:) throws -> TDFKeyShare` + and `RewrapOutcome`, plus: + - `func submitRewrap(_ prepared: PreparedRewrap) async throws -> RewrapSubmission` + - `func pollRewrap(_ pending: PendingRewrap, until deadline: Date) async throws -> RewrapPollOutcome` + - `func rewrap(manifest:clientPrivateKey:options:deadline:) async throws -> RewrapOutcome` + +- [ ] **Step 1: Write the failing tests.** They use an actor `ScriptedTransport: KASRewrapTransport`, which replays + `(status, headers, body)` in order and records each request's method, URL, headers and body. They also use a + recording sleeper and a controllable clock. + +```swift +func testImmediate200IsAnswered() // .answered; results keep fail entries; no throw on a deny +func testDenyOnlyAnswerParses() // 200 with only fail results and no sessionPublicKey → .answered, sessionPublicKey nil +func testPendingThenAnswered() // POST 202 (Location /owner-kas/v1/requests/abc, Retry-After 3), GET 202 (Retry-After 5), GET 200 + // → sleeps [3, 5]; GETs to https://h/owner-kas/v1/requests/abc carry the same bearer and no body +func testGoneIsExpired() // GET 410 → .expired +func test404AfterExpIsExpired() // clock past expiresAt → .expired +func test404BeforeExpThrows() // → KASRewrapError.httpError(404, _) +func testDeadlineReachedReturnsHandleAndResumes() // deadline before the next wait ends → .deadlineReached(pending); pollRewrap(pending) again → .answered +func testRetryAfterIsClamped() // "0" → 1; "-5" → default 2; "999" → 60; HTTP-date → 2; missing → 2; never past the deadline +func testLocationOriginRules() // relative ok; absolute same origin ok; https://evil.example/x, //evil.example/x, + // http://h/x, https://h:8443/x → .unsafeLocation, with no request sent to them +func testPendingWithoutLocationThrows() // → .pendingWithoutLocation +func testResubmitSendsIdenticalBytes() // submitRewrap(prepared) twice → both recorded bodies equal +func testRewrapUnwrapsPermittedShares() // permit with a key sealed by TDFKAS.rewrap → shares contain the DEK with the KAO's sid +func testAnswerShareRefusesFailResult() // share(for: failResult) throws +``` + +- [ ] **Step 2: Run:** `swift test --filter KASRewrapPendingTests`. Expected: compile failure. +- [ ] **Step 3: Implement** as in the spec's `submitRewrap` and `pollRewrap` lists. Parse a 200 with the existing + `RewrapResponse` decoder and map it to `RewrapAnswer`; `sid` comes from `prepared.keyAccessObjects[i]` for id + `kao-`. `PendingRewrap` carries the internal `keyAccessObjects` too, for `sid` after a resume. +- [ ] **Step 4: Run:** `swift test --filter KASRewrapPendingTests`. Expected: PASS. +- [ ] **Step 5: Commit** `feat(kas): poll a KAS that answers later; return full Rewrap results (#66)`. + +--- + +### Task 7: End to end, docs, PR + +**Files:** +- Test: `OpenTDFKitTests/OwnerKASEndToEndTests.swift` +- Modify: `CLAUDE.md`, `MIGRATION_GUIDE.md` + +**Interfaces:** +- Consumes: everything above. + +- [ ] **Step 1: Write the end-to-end tests.** An actor `FakeOwnerKAS: KASRewrapTransport` plays the relay: + - On the POST it returns 202 + `Location`. + - On the first GET it returns 202. + - On the second GET it plays the phone: `verifyRewrapRequest(body, cnf key)`, then checks + `keyAccessObjectDigest(kao) == the digest recorded at encrypt time`, then `TDFKAS.rewrap`, then + `rewrapResponseBody`, with `metadata["arkavo.decision"] = .string("…")`. + +```swift +func testOwnerAllowEndToEnd() // TDFEncryptor(.ecP256, url https://h/owner-kas/v1/routes/R) → client.rewrap → share == DEK, + // payload decrypts, metadata["arkavo.decision"] intact, digests equal on both sides +func testOwnerDenyEndToEnd() // phone answers fail "ACCESS_DENIED" with metadata → .answered with one fail result, no shares, no throw +``` + +- [ ] **Step 2: Run:** `swift test --filter OwnerKASEndToEndTests`. Expected: PASS. Everything they use exists, so + a failure is a bug in Tasks 1–6. + +- [ ] **Step 3: Docs.** + - `CLAUDE.md`: + - in the TDFKAS entry, add the phone functions and the digests; + - in the KASRewrapClient entry, add prepare/submit/poll/rewrap, path-aware matching and the 404 rule. + - `MIGRATION_GUIDE.md` v5.2.0: + - the new API; + - path-aware matching and its one cost (a KAS mounted under another prefix needs that prefix in its `uri`); + - the new `KASRewrapError` cases for exhaustive switches. + +- [ ] **Step 4: Full suite:** `swift build && swift test`, then `cd scripts/interop/ec-wrapped && go test ./...`. + Expected: all pass, with the same skipped count as before (15). + +- [ ] **Step 5: Commit** `test(kas): owner-KAS end to end; docs (#66)`, push, then retitle PR #68 and update its + description for the revised #66. diff --git a/docs/superpowers/specs/2026-11-08-kas-side-ec-rewrap-design.md b/docs/superpowers/specs/2026-11-08-kas-side-ec-rewrap-design.md new file mode 100644 index 0000000..4a003b2 --- /dev/null +++ b/docs/superpowers/specs/2026-11-08-kas-side-ec-rewrap-design.md @@ -0,0 +1,257 @@ +# KAS-side TDF EC rewrap and an exposed client unwrap + +Date: 2026-11-08 +Status: Design, builder-checked, reviewed (advisor, Codex), pending approval +Issue: [#66](https://github.com/arkavo-org/OpenTDFKit/issues/66). Prerequisite for #67. +Consumer: arkavo-ios on-device KAS (arkavo-ios#77; its design §4.6 and ADR-0073, pinned at +`39da0a52b1191b4515eeeec2438ebb78b0ccd4fb`). + +## Why + +arkavo-ios wants an iPhone to act as a KAS for files its owner encrypts. The phone holds an EC P-256 KAS private key +and answers rewrap requests itself, relayed through a server that never sees key material. The phone needs the KAS half +of the TDF `ec-wrapped` rewrap in Swift. The receiving phone needs the client half for a response that did not +arrive over HTTP. The files are ordinary TDFs (ZIP) and must stay openable by other OpenTDF tools that know +the KAS (ADR-0073), so everything here must be byte-compatible with the go SDK and the opentdf-platform KAS. + +Today OpenTDFKit has the KAS side only for NanoTDF (`KASService`), the ZIP encryptor wraps only with RSA, and the client +EC session unwrap exists (`KASRewrapClient.unwrapKey`) but defaults to the NanoTDF salt. + +## Goals + +1. **KAS-side rewrap.** A public, pure function (no network, no storage, no globals) that takes the KAS P-256 private + key as a value, an `ec-wrapped` key access object (KAO) and the manifest's policy string. It unwraps the DEK, verifies + the policy binding, and seals the DEK to a receiver's P-256 public key. It returns `(wrappedKey, sessionPublicKey)`. +2. **Client unwrap, exposed.** *(Superseded 2026-11-08 by the revised #66: the receiver now calls the owner KAS over HTTP with `KASRewrapClient`; see `2026-11-09-owner-kas-rewrap-design.md`. `TDFKAS.unwrap` stays, for use after the receiver verifies the owner's decision.)* A public, pure function that takes `(wrappedKey, sessionPublicKey, receiverPrivateKey)` + and returns the DEK, with the TDF salt fixed so a caller cannot pick the NanoTDF one by accident. +3. **Encrypt with an `ec-wrapped` KAO.** The ZIP encryptor (`TDFEncryptor`) can wrap to a caller-supplied P-256 KAS + public key, with a caller-supplied KAO URL, `kid` and policy, in the go SDK's format. +4. **Proof of interop** with go, not only a Swift round trip (see Tests). +5. **A tagged release**, 5.2.0. Tagging and publishing wait for the owner's go-ahead. + +## Non-goals + +- Multiple KAOs, split or any-of plans (#67). +- Attribute or entitlement evaluation. The caller (the app) decides whether to release; this API only does the + cryptography of a release it has already decided on. +- Matching the KAO's `url` or `kid` against the KAS. The caller does that; it knows its route and key ID. +- Changing the TDF-JSON or TDF-CBOR containers or their EC scheme. +- An offline "open my own file with the KAS private key" decrypt path in `TDFDecryptor`. +- P-384 and P-521 for this path. +- go's legacy hex binding form, in either direction. It is a bug (the owner's decision, 2026-11-08). OpenTDFKit + neither writes nor accepts it, so older KASs without #4081 cannot rewrap OpenTDFKit's files, and this KAS-side rewrap + refuses a TDF whose binding a go SDK wrote in hex. +- A manifest field for arkavo-ios's `arkavo.owner-image/1` profile marker. The OpenTDF spec has no such field and the + KAS never reads one. A caller can carry it in the policy JSON today (the binding makes it tamper-evident). If + arkavo-ios settles on a manifest assertion instead, that is a follow-up release. + +## Anti-goals + +It fails even if it works if: +- an `ec-wrapped` KAO written here cannot be rewrapped by an opentdf-platform KAS with EC enabled and the spec-form + binding fix (#4081, `ca178b05`), or one written by the go SDK cannot be rewrapped here; +- a tampered policy produces any wrapped key; +- the existing TDF-JSON / TDF-CBOR EC files stop opening; +- an existing RSA caller of `TDFKasInfo` or `TDFEncryptor` has to change code or gets different output. + +## Reference facts (verified against the local opentdf-platform checkout, `02813896`) + +Two different EC schemes exist, and they must not be mixed: + +| | TDF `ec-wrapped` (go SDK / platform) | TDF-JSON / TDF-CBOR drafts (OpenTDFKit today) | +| --- | --- | --- | +| Writer | `sdk/tdf.go` `generateWrapKeyWithEC` | `TDFCrypto.wrapSymmetricKeyWithEC` | +| HKDF salt | `SHA256("TDF")` (`tdfSalt()`) | empty | +| HKDF info / length | empty / 32 bytes | empty / 32 bytes | +| `ephemeralPublicKey` | PEM (SubjectPublicKeyInfo) | base64 compressed SEC1 | +| `wrappedKey` | base64(nonce 12 ‖ ciphertext ‖ tag 16) | same | + +- The platform KAS (`service/kas/access/rewrap.go`, `case "ec-wrapped"`) PEM-decodes `ephemeralPublicKey` and refuses + anything else ("invalid ephemeral public key PEM"). It unwraps with `NewSaltedECDecryptor(sk, TDFSalt(), nil)` + (`service/internal/security/standard_crypto.go`). +- Policy binding (`rewrap.go`, `dek.VerifyBinding`): `HMAC-SHA256(DEK, policyBody)` where `policyBody` is the + manifest's `encryptionInformation.policy` string as sent (the base64 text, as bytes). The KAO's `policyBinding.hash` + is base64 of either the raw 32-byte HMAC (spec form; what OpenTDFKit writes) or the hex string of it (go's legacy + form). **At `02813896` the KAS verifies only the legacy hex form**: it decodes the spec form into a 33-byte buffer + and the length-sensitive compare fails. The fix is opentdf/platform#4081 (`ca178b05`, "accept spec-compliant policy + bindings"), which OpenTDFKit's `xtest.yml` already pins. OpenTDFKit's RSA path already writes the spec form and + already depends on that fix (`TDFCrypto.policyBinding`'s doc comment); the EC path follows the same rule. +- The platform's `ec-wrapped` case passes the KAO's `kid` straight to the key lookup, with no legacy-key fallback (the + `wrapped` case has one). An `ec-wrapped` KAO without a `kid` cannot be rewrapped by a platform KAS. +- Rewrap response sealing (`rewrap.go` → `ocrypto.FromPublicPEMWithSalt(clientPublicKey, TDFSalt(), nil)`, + `ECEncryptor.Encrypt`): a fresh ephemeral P-256 session key, ECDH with the client key, HKDF-SHA-256 with + `SHA256("TDF")`, empty info, 32 bytes, AES-256-GCM with a random 12-byte nonce, output nonce ‖ ciphertext ‖ tag. The + session public key is returned as PEM. `KASRewrapClient` already unwraps exactly this from a live platform, with + `KASRewrapClient.standardTDFSessionSalt`. + +The KAO wrap salt and the session salt are the same value, `SHA256("TDF")`. + +## Design + +### 1. KAS-side rewrap (new file, e.g. `OpenTDFKit/TDF/TDFKAS.swift`) + +```swift +public enum TDFKAS { + /// KAS side: unwrap the key share from an `ec-wrapped` KAO, verify the policy binding, seal the share to the + /// receiver. See "What a successful rewrap proves" before relying on it. + public static func rewrap( + keyAccessObject: TDFKeyAccessObject, + policyBase64: String, // manifest encryptionInformation.policy, unchanged + kasPrivateKey: P256.KeyAgreement.PrivateKey, + receiverPublicKey: P256.KeyAgreement.PublicKey, + ) throws -> TDFKAS.RewrapResult + + /// Client side: open a rewrapped key share that did not come from an HTTP rewrap. + public static func unwrap( + wrappedKey: Data, + sessionPublicKey: P256.KeyAgreement.PublicKey, + receiverPrivateKey: P256.KeyAgreement.PrivateKey, + ) throws -> SymmetricKey +} + +extension TDFKAS { + public struct RewrapResult: Sendable { + public let wrappedKey: Data // nonce ‖ ciphertext ‖ tag + public let sessionPublicKey: P256.KeyAgreement.PublicKey + } +} +``` + +**Key share, not DEK.** What a KAO wraps is its split's key share. For a TDF with one split (every KAO in #66) the +share is the DEK. With several splits (#67) the shares are XORed (`TDFDecryptor.combineKeyShares`). The doc comments +say "key share" so #67 needs no signature change. + +**`policyBase64`.** The HMAC is over the base64 text of the policy exactly as it appears in the manifest, not the +decoded JSON. The parameter name and doc comment say so; arkavo-ios's §4.4 "policy: bytes as in the TDF" must carry +that same base64 text. + +`rewrap` steps, in order: +1. Refuse a KAO whose `type` is not `.ecWrapped`, or that has no `ephemeralPublicKey`. +2. Parse `ephemeralPublicKey` as a PEM P-256 public key, as the platform KAS does. Anything else is refused with its own + error, whose message says the key is not PEM and that the TDF-JSON / TDF-CBOR EC scheme (compressed SEC1, empty + salt) is not served by this function. A PEM key not on P-256 is refused. +3. ECDH(KAS private key, ephemeral key) → HKDF-SHA-256(salt `SHA256("TDF")`, info empty, 32) → AES-GCM open of the + base64-decoded `wrappedKey` (nonce 12 ‖ ciphertext ‖ tag 16). Any failure is one "key unwrap failed" error: it does + not say which step failed. The opened share must be exactly 32 bytes, or it is the same error. +4. From the moment the share is opened, a `defer` zeroes its bytes, so every later exit (a binding failure, a sealing + failure, success) wipes it. Best effort, as `TDFCrypto` already does with `secureZero`. +5. Verify the binding over `Data(policyBase64.utf8)` with the share, in the spec form only: `policyBinding.alg` must be + `HS256` (empty already decodes as `HS256`), and `policyBinding.hash` must base64-decode to exactly 32 bytes equal to + the HMAC, compared in constant time. Any other `alg`, go's legacy `Base64(hex(HMAC))` form, and any mismatch are + refused as one binding error. Nothing is sealed. +6. Generate a fresh P-256 session key and a fresh random nonce, ECDH with the receiver key, the same HKDF, AES-256-GCM + seal. Return. + +"A tampered policy fails before any rewrap" means step 5 runs before step 6. The share has to be opened first because +the binding is keyed by it. + +`unwrap` delegates to `KASRewrapClient.unwrapKey` with `standardTDFSessionSalt`, so the HTTP and non-HTTP paths share +one implementation. It requires a 32-byte result. `KASRewrapClient.unwrapKey` currently leaves its decrypted `Data` +unwiped; it gets the same `defer` wipe, which also covers the HTTP path. + +Errors: a new `TDFKASError` (`CustomStringConvertible`) with cases for an unsupported KAO type, a missing or +non-PEM ephemeral key, an invalid wrapped-key encoding, key unwrap failed, and binding refused. No message contains key +material, the share or the HMAC. + +### What a successful rewrap proves (security notes; also in `rewrap`'s doc comment) + +- **It does not prove who made the KAO.** Anyone holding the KAS *public* key (it is published in arkavo-ios's route + record, §4.3) can wrap a key of their choosing to it and compute a valid binding over a policy of their choosing. + `rewrap` will accept that. A passing binding proves only that the policy belongs to this KAO. The caller must match + the KAO and policy against its own records (arkavo-ios records policy and KAO digests at protect time) before calling + `rewrap`. +- **Do not forward which step failed.** The distinct errors (key unwrap failed versus binding refused) tell the caller + whether a submitted ciphertext authenticated under the KAS key. That is for the caller's own audit. A response to a + requester should collapse every `rewrap` failure into one code, as the platform's "bad request" does. (arkavo-ios's + §4.5 lists a `BINDING_MISMATCH` deny code; its builder should map both failures to it.) + +### 2. Encrypt with an `ec-wrapped` KAO + +- `TDFKasInfo` gains a key type: `public enum KeyType: Sendable { case rsa, ecP256 }`, stored as `keyType`, with an + `init` parameter defaulting to `.rsa` so every existing caller compiles and behaves the same. #67 reuses this type + for each recipient in a plan, so keep it a plain enum on `TDFKasInfo`. +- A new go-compatible wrap function in `TDFCrypto`, named so it cannot be confused with the JSON/CBOR one, e.g. + `wrapSymmetricKeyWithECForKAS(publicKeyPEM:symmetricKey:) -> (wrappedKey: String, ephemeralPublicKeyPEM: String)`. + It mirrors `generateWrapKeyWithEC`: a fresh P-256 key, PEM ephemeral key, salt `SHA256("TDF")`. +- `TDFEncryptor` wraps in three places today (`encryptFile`, `encryptFileMultiSegment`, `encrypt(plaintext:…)`). Fold + them into one helper that builds the KAO from `TDFKasInfo`: `.rsa` writes today's `wrapped` KAO byte for byte; + `.ecP256` writes `type: "ec-wrapped"`, the PEM `ephemeralPublicKey`, the same `url`, `kid`, `schemaVersion` and policy + binding (spec form) as the RSA path. +- An `.ecP256` `TDFKasInfo` is refused before encryption when its `kid` is nil or empty (no platform KAS can rewrap + that KAO: verified, neither platform key index falls back for an empty `kid`), or when the configuration's key size + is `.bits128` (the go SDK only reconstructs a 32-byte payload key, and `rewrap` only accepts 32-byte shares). +- Document the existing `wrapSymmetricKeyWithEC` / `unwrapSymmetricKeyWithEC` as the TDF-JSON / TDF-CBOR draft scheme, + not the platform's `ec-wrapped`, and fix `ECWrappedKeyResult`'s doc comment (it says PEM; the value is compressed SEC1). + +### 3. Tests + +**The interop chain.** A Swift round trip alone would pass with the wrong salt. These four links together prove the +Swift code speaks the go scheme in both directions: +- (a) `unwrap` opens a rewrap response sealed by go → `unwrap` uses the go session scheme. +- (b) `unwrap` opens `rewrap`'s output → `rewrap` seals with that same scheme. +- (c) `rewrap` opens a KAO written by go → `rewrap` reads the go KAO scheme. +- (d) `rewrap` opens a KAO written by the Swift encryptor → the encryptor writes the go KAO scheme. + +The chain closes only because `rewrap` accepts PEM ephemeral keys alone. If that is ever loosened, (d) stops proving +that the encryptor writes PEM. That dependency is stated in a comment on the (d) test. + +The chain proves the cryptography, not serialization details that only go's parsers check (PEM framing, JSON field +spelling). So the go program also checks the reverse direction: it opens a KAO and a rewrap response written by Swift +(a fixture the Swift tests can write out on request) with go's `ocrypto` and the platform's PEM parsing. This runs by +hand, not in CI, and **must pass before the release is tagged**; the result goes in the PR description. + +Swift (`swift test`, run in CI): +- Round trip: `TDFEncryptor` with an `.ecP256` KAS → `rewrap` → `unwrap` gives the DEK, and the payload decrypts with + it. Covered for all three encryptor entry points (`encryptFile`, `encryptFileMultiSegment`, `encrypt(plaintext:…)`). +- Go fixture: links (a) and (c), above. A committed fixture produced by go, embedded in the test file. It holds a KAS + P-256 private key, a policy string, an `ec-wrapped` KAO written the way `generateWrapKeyWithEC` writes it (with a + spec-form binding computed by the generator, not go's hex form), the expected DEK, and a rewrap response sealed the + way the platform seals it (`FromPublicPEMWithSalt(…, TDFSalt(), nil)`) to a fixed receiver key. +- Another receiver private key fails to unwrap. +- Tampering, each refused with nothing sealed: one changed character in the policy base64; the decoded policy JSON + passed instead of the base64 text; a changed `policyBinding.hash`; the legacy hex binding of the correct HMAC; an + `alg` other than `HS256`. +- Wrapped-key mutation, each refused: a flipped byte in the nonce, in the ciphertext and in the tag; the wrapped key + truncated; a KAO wrapping a 16-byte key. +- Two `rewrap` calls on the same input give different session public keys and different nonces. +- A non-`ec-wrapped` KAO, a missing ephemeral key, a base64 SEC1 (non-PEM) ephemeral key, a KAO written by the + TDF-JSON container, a P-384 ephemeral key and a wrong KAS private key each throw. +- An `.ecP256` `TDFKasInfo` without a `kid`, or with `.bits128`, is refused. +- An `.rsa` `TDFKasInfo` produces the same KAO fields as before this change. + +Go program: under `scripts/interop/ec-wrapped/`, using the published `github.com/opentdf/platform/lib/ocrypto` module (a +pinned version in its `go.mod`). `generate` mirrors `generateWrapKeyWithEC` and the platform's response sealing and +prints the fixture; `verify` opens Swift output as above. Run by hand, not in CI. + +## Left to the builder + +- Exact type and function names, and file placement, provided the TDF EC functions are clearly distinct from + the JSON/CBOR ones. +- How the Swift tests write out the fixture for the go `verify` step (for example, behind an environment variable). +- An optional manual check against a live opentdf-platform KAS with `ec_tdf_enabled` and #4081 (`ca178b05` or later, + not the local checkout at `02813896`, which rejects spec-form bindings and would make a correct KAO look broken), + using `KASRewrapClient` on a TDF written by the new encryptor path. +- README / CLAUDE.md updates for the new API. + +## The owner's decisions + +- "Standard TDF" just means TDF. New types, functions and files say TDF (`TDFKAS`, not `StandardTDFKAS`). The existing + public `KASRewrapClient.standardTDFSessionSalt` keeps its name, since renaming it would break callers. + +- The policy binding is the spec form only, written and verified. go's legacy hex form is a bug and is refused + (2026-11-08). + +## Calls made in this document (open to correction) + +- Accept only a PEM ephemeral key in the KAO, as the platform does (changed from "PEM or SEC1" in chat: the only SEC1 + `ec-wrapped` writer is OpenTDFKit's own TDF-JSON/CBOR path, which uses a different salt, so accepting SEC1 would only + turn a clear refusal into an opaque unwrap failure). +- Require a `kid` for an `.ecP256` KAS when encrypting. +- Key shares are exactly 32 bytes on this path (changed from "any length"): `rewrap` and `unwrap` refuse anything else, + and the encryptor refuses `.ecP256` with `.bits128`. The go KAS accepts 16, 24 or 32, but the go SDK reader only + builds a 32-byte key, so an AES-128 file would not open in other OpenTDF tools. +- Refuse any `policyBinding.alg` other than `HS256`. +- `rewrap` does not check the KAO's `url` or `kid`; the caller does. +- KAO unwrap and binding verification stay internal; only `rewrap` and `unwrap` are public. +- The Swift→go check is required before tagging but runs by hand, not in CI. +- Version 5.2.0, additive. diff --git a/docs/superpowers/specs/2026-11-09-owner-kas-rewrap-design.md b/docs/superpowers/specs/2026-11-09-owner-kas-rewrap-design.md new file mode 100644 index 0000000..8080c6e --- /dev/null +++ b/docs/superpowers/specs/2026-11-09-owner-kas-rewrap-design.md @@ -0,0 +1,371 @@ +# Owner KAS: Rewrap on the phone, and a client for a KAS that answers later + +Date: 2026-11-09 +Status: Design, builder-checked, pending approval +Issue: [#66](https://github.com/arkavo-org/OpenTDFKit/issues/66), as revised on 2026-11-08 (items 2–8). +Extends: `2026-11-08-kas-side-ec-rewrap-design.md` (items 1 and 9, in PR #68). Same PR. +Consumer contract: arkavo-ios `docs/superpowers/specs/2026-11-08-owner-kas-design.md` §4.1–§4.6, at `3fea003` +(which adds the relay's wire details as arkavo-rs built them; the issue links `7d11e02`). + +## Why + +The owner decided that "OpenTDFKit can hit either KAS (platform KAS or owner KAS)". The owner's iPhone is a KAS. +Its URL is `https://platform.arkavo.net/owner-kas/v1/routes/`, where a relay (arkavo-rs) holds requests +until the phone answers. A receiver calls that URL with `KASRewrapClient`, exactly as it calls the platform KAS. Two +things differ: +- **The answer can take up to 15 minutes.** The relay answers the Rewrap POST with `202`, a relative `Location` and + `Retry-After`. Polls of `Location` get `202` while pending, `200` with the Rewrap response body once answered, and + `410` after the deadline. +- **The phone is the KAS.** It verifies the signed request and builds the Rewrap response itself. + +The previous design's "exposed non-HTTP unwrap" goal is superseded. `TDFKAS.unwrap` stays: the receiver calls it +after verifying the owner's signed decision. + +## Goals + +KAS side (the owner's phone; pure, keys as values, no network or storage): +1. **Done in PR #68:** `TDFKAS.rewrap`, the `ec-wrapped` rewrap to the request's `clientPublicKey`. +2. **Parse and verify a received Rewrap.** Verify the ES256 signed request token under a given P-256 key. Return its + `exp`, the request-token digest, `clientPublicKey`, the policies with their key access objects, and any extension + members. +3. **Build a Rewrap response body**, with caller `metadata`, for ALLOW and DENY alike. + +Client side (`KASRewrapClient`, the receiver): +4. **Pending answers:** follow `202` + `Location`, honoring `Retry-After`, until `200`, `410` or the caller's + deadline. Expired (`410`) is reported distinctly from a denial and from the caller's deadline. +5. **Request-token lifetime:** the caller sets the signed request token's `exp`. +6. **Path-aware matching:** a client selects only key access objects whose URL is its KAS, path included. +7. **One extension member** in `requestBody`, covered by the request signature. +8. **Return what the KAS sent:** each result's status, `error`, `metadata` and `kasWrappedKey`, the + `sessionPublicKey` and the request-token digest, with the unwrapped share for each permitted result. A denial is a + result, not a thrown error, so the app can verify the owner's signed DENY. + +## Non-goals + +- The relay, the owner-KAS token (CWT) and the owner's signed decision record. Those belong to arkavo-rs, authnz-rs + and arkavo-ios. OpenTDFKit carries `metadata` opaquely. +- Bulk rewrap (`rewrapAndUnwrapTDFs`) through an owner KAS, and multiple key access objects across KASs (#67). +- The go SDK's legacy single-KAO request shape (top-level `keyAccess`, `policy`, `algorithm`) on the phone side. The + only client of an owner KAS is OpenTDFKit, which sends `requests`. +- DPoP. +- Changing the existing `rewrapTDF`, `rewrapAndUnwrapTDF`, `rewrapAndUnwrapTDFShares` or the bulk API, apart from + path-aware matching, which applies to all of them. + +## Anti-goals + +It fails even if it works if: +- the bearer token is ever sent to an origin other than the configured KAS's (a hostile `Location`); +- a 202, an expiry or the caller's deadline is ever reported as the owner's denial; +- the digest the client reports differs from the digest the phone computes for the same request, because the owner's + decision record binds to it; +- an existing platform-KAS caller stops matching its key access objects, except in the one case listed under + "Calls made". + +## Reference facts + +- The relay (arkavo-ios design §4.2) does the following: + - It accepts `POST /kas.AccessService/Rewrap` (Connect JSON, at most 64 KiB) and answers + `202 { request_id, status: "pending", deadline }`, with `Location: /owner-kas/v1/requests/{request_id}` (a path) + and `Retry-After`. + - It answers `GET Location` (same bearer) with `202` + `Retry-After` while pending, `200` + the stored Rewrap + response body once answered, and `410 { status: "expired" }` after the deadline. A poll after the request is + deleted (the deadline plus 10 minutes) gets `404`, which the receiver treats as expired. A poll with any other + token also gets `404`, so a request's existence isn't revealed. + - It checks the signed request token's ES256 signature under the bearer's `cnf` key, and that its `exp` is no later + than the token's. + - Sending the same body again returns the same `request_id`. +- The platform KAS verifies the signed request token only under a DPoP key (`requireVerification := dpopJWK != nil`, + `service/kas/access/rewrap.go` at `ca178b05`). Without DPoP it does not care which key signed. +- `OpenTDFConfiguration.forKasConnect(base)` sets `kas.uri = base` and the Rewrap URL to + `base/kas.AccessService/Rewrap`. `validateKasURL` checks only scheme, host and IP, so a base with a path is fine. +- Platform discovery reports `kas.uri: "https://platform.arkavo.net"`, with no path (`KASDiscoveryTests.swift:27`). + Key access objects usually carry `…/kas`. +- `KASRewrapClient` already takes a `signingKey` at init. Today only the NanoTDF path uses it; `rewrapTDF` signs with + the client's ECDH key (`KASRewrapClient.swift:587`). The JWT `exp` is fixed at `iat + 60` (line 1244). +- CryptoKit's ECDSA signatures are randomized, so re-signing the same claims never reproduces the same bytes. + +## Design + +### Request-token digest (shared) + +`TDFKAS.requestTokenDigest(_ token: String) -> Data` is SHA-256 of the compact JWT string's UTF-8 bytes (the +`signed_request_token` value, not the HTTP body). It is arkavo-ios's `request_digest`. The phone side and the client +side both call this one function. + +### Key access object digest and key fingerprint (shared) + +The owner's phone must check that a forwarded key access object is the one in the file. The client re-encodes it when +it sends it: it drops `schemaVersion`, and its key order is not the manifest's. So no digest of JSON bytes taken at +protect time can equal one taken at service time. OpenTDFKit therefore defines the digests (the owner's decision, +2026-11-09), and arkavo-ios calls the same functions at protect time and at service time: + +- `TDFKAS.keyAccessObjectDigest(_ kao: TDFKeyAccessObject) -> Data` is SHA-256 over: + - the domain tag `OpenTDFKit/kao-digest/v1`; + - then, in this fixed order, each of `type` (raw value), `url`, `protocol`, `wrappedKey`, `policyBinding.alg` + (empty means `HS256`), `policyBinding.hash`, `kid`, `sid`, `encryptedMetadata` and `ephemeralPublicKey`. + + Each field is written as one presence byte (`0` absent, `1` present), then, if present, a 4-byte big-endian length + and its UTF-8 bytes. `schemaVersion` is left out. Every field the client forwards is in it, so the digest of the + manifest's object equals the digest of the forwarded one. +- `TDFKAS.publicKeyFingerprint(_ key: P256.KeyAgreement.PublicKey) -> Data` is SHA-256 of the 65-byte uncompressed + SEC1 point (`04 ‖ X ‖ Y`, CryptoKit's `x963Representation`). It is for arkavo-ios's `response_key_fp` (of + `clientPublicKey`) and `session_key_fp` (of `sessionPublicKey`). It doesn't depend on how the PEM was written. + +### 2. Verify a received Rewrap (phone) + +```swift +extension TDFKAS { + public static func verifyRewrapRequest( + body: Data, // the HTTP body: {"signed_request_token": ""} + signingPublicKey: P256.Signing.PublicKey, // the bearer token's cnf key + ) throws -> RewrapRequest + + public struct RewrapRequest: Sendable { + public let requestToken: String + public let requestTokenDigest: Data + public let issuedAt: Date? + public let expiresAt: Date + public let clientPublicKey: P256.KeyAgreement.PublicKey + public let policies: [Policy] + public let extensions: [String: Data] // top-level requestBody members, raw JSON, by name + + public struct Policy: Sendable { + public let policyId: String + public let policyBase64: String // the policy body, as sent; what rewrap's binding needs + public let keyAccessObjects: [(id: String, keyAccessObject: TDFKeyAccessObject)] + } + } +} +``` + +**Checks, in order** (each failure throws a `TDFKASError` naming the check, never the content): +1. The body is at most 64 KiB. +2. It is a JSON object with a string `signed_request_token`. +3. The token has three base64url parts. The header is a JSON object with `alg == "ES256"`; anything else, including + `none`, is refused. +4. The signature is 64 raw bytes (r ‖ s) and verifies under `signingPublicKey` over `header.payload`, exactly as + received. +5. The claims hold `requestBody` (a string), a numeric `exp` and an optional numeric `iat`. +6. `requestBody` parses as a JSON object with a PEM P-256 `clientPublicKey` and a non-empty `requests` array. Each + entry has `policy.id`, a `policy.body` that decodes as base64, and a non-empty `keyAccessObjects` array of + `{keyAccessObjectId, keyAccessObject}`. Each `keyAccessObject` decodes as `TDFKeyAccessObject`. +7. `extensions` holds every top-level member other than `clientPublicKey`, `requests`, `keyAccess`, `policy`, + `algorithm` and `schemaVersion`, as that member's JSON bytes. + +`exp` is **returned, not enforced**. The phone must be able to parse an expired request so it can send a signed DENY +`REQUEST_EXPIRED`. It applies its own clock and skew. + +### 3. Build a Rewrap response (phone) + +```swift +extension TDFKAS { + public static func rewrapResponseBody( + sessionPublicKey: P256.KeyAgreement.PublicKey?, // nil when nothing was permitted + responses: [PolicyResponse], + ) throws -> Data + + public struct PolicyResponse: Sendable { public let policyId: String; public let results: [Result] } + public struct Result: Sendable { + public let keyAccessObjectId: String + public let status: Status // .permit | .fail + public let kasWrappedKey: Data? // required for .permit, absent for .fail + public let error: String? + public let metadata: [String: KASRewrapClient.RewrapMetadataValue] + } +} +``` + +The output is `{"sessionPublicKey": , "responses": [{"policyId", "results": [{"keyAccessObjectId", "status", +"kasWrappedKey", "error", "metadata"}]}]}`: `status` is `permit` or `fail`, `kasWrappedKey` is standard base64, and +absent fields are omitted. A `.permit` without a key, or a `.fail` with one, throws. `metadata` uses the client's +existing public value type, so what the phone writes round-trips through what the client parses. + +### 4, 5, 7, 8. Client: prepare, submit, poll + +The new API leaves the existing methods unchanged. It signs with the client's `signingKey`, the one given at init, +which for an owner KAS is the bearer token's `cnf` key, not the client's ECDH key. + +```swift +extension KASRewrapClient { + public struct RewrapOptions: Sendable { + public var expiresAt: Date? // the token's exp; default now + 60 s + public var requestBodyExtension: RequestBodyExtension? + } + public struct RequestBodyExtension: Sendable { public let name: String; public let json: Data } + + /// The signed request, as bytes. Submitting the same value again sends identical bytes. + public struct PreparedRewrap: Sendable { + public let body: Data + public let requestToken: String + public let requestTokenDigest: Data + public let expiresAt: Date + } + + public func prepareRewrap(manifest: TDFManifest, clientPrivateKey: P256.KeyAgreement.PrivateKey, + options: RewrapOptions = .init()) throws -> PreparedRewrap + public func submitRewrap(_ prepared: PreparedRewrap) async throws -> RewrapSubmission // .answered | .pending + public func pollRewrap(_ pending: PendingRewrap, until deadline: Date) async throws -> RewrapPollOutcome + public func rewrap(manifest: TDFManifest, clientPrivateKey: P256.KeyAgreement.PrivateKey, + options: RewrapOptions = .init(), deadline: Date? = nil) async throws -> RewrapOutcome + + public struct PendingRewrap: Sendable { public let location: URL; public let retryAfter: TimeInterval; + public let requestTokenDigest: Data; public let expiresAt: Date } + public enum RewrapSubmission: Sendable { case answered(RewrapAnswer), pending(PendingRewrap) } + public enum RewrapPollOutcome: Sendable { case answered(RewrapAnswer), expired, deadlineReached(PendingRewrap) } + + public struct RewrapAnswer: Sendable { + public let requestTokenDigest: Data + public let sessionPublicKey: P256.KeyAgreement.PublicKey? + public let results: [Result] + public struct Result: Sendable { + public let keyAccessObjectId: String + public let sid: String? // from this client's key access object kao- + public let status: String // "permit", "fail", or whatever the KAS sent + public let kasWrappedKey: Data? + public let error: String? + public let metadata: [String: RewrapMetadataValue] + } + /// Unwraps one permitted result with TDFKAS.unwrap (TDF session salt). + public func share(for result: Result, clientPrivateKey: P256.KeyAgreement.PrivateKey) throws -> TDFKeyShare + } + /// `rewrap`'s outcome: answered carries the shares of every permitted result, already unwrapped. + public enum RewrapOutcome: Sendable { + case answered(RewrapAnswer, shares: [TDFKeyShare]), expired, deadlineReached(PendingRewrap) + } +} +``` + +**`prepareRewrap`** +- Builds today's `requestBody` (`clientPublicKey`, one `requests` entry with the manifest's policy and this KAS's key + access objects, ids `kao-`). `policy.body` is the manifest's `encryptionInformation.policy` string, unchanged, as + `standardPolicyRequest` already sends it. arkavo-ios digests the decoded policy, and the binding is over that string. +- Adds the extension as one top-level member. Its name may not be one of the standard names listed under check 7. + Its JSON must parse. It is covered by the signature, because it is inside `requestBody`. +- Signs the claims `{requestBody, iat: now, exp}`. `exp` must be in the future, otherwise it throws. +- Computes the digest with `TDFKAS.requestTokenDigest`. + +**`submitRewrap`** +- POSTs `prepared.body`, as today's Rewrap does: bearer, Connect headers, 30 s timeout, through the + `KASRewrapTransport`. +- `200` gives `.answered`. Every result is kept. A denial is a result, not a throw. +- `202` gives `.pending`: + - `Location` is required and is resolved against the Rewrap URL. + - The resolved URL must have the Rewrap URL's scheme, host and effective port, otherwise it throws: the bearer + goes there. + - `Retry-After` is parsed as delta-seconds. Anything else, including an HTTP-date, gives the default of 2 s. It is + clamped to 1–60 s. +- Other statuses throw as today. +- It never retries on its own. Resending the same `PreparedRewrap` after a network failure is safe: the relay + returns the same `request_id`. + +**`pollRewrap`** +- Waits `retryAfter`, then GETs `location` with the same bearer, no body, a 30 s timeout and the same transport. +- `202` repeats, with the new `Retry-After`. `200` gives `.answered`. `410` gives `.expired`. +- `404` at or after the handle's `expiresAt` (the token's `exp`, which is the relay's deadline) gives `.expired`: the + relay deletes a request after its deadline. A `404` before then throws `.httpError(404)`, because it means the + request is unknown to the relay (a wrong token, or lost state), which the app shows as unavailable, never as a + denial. +- Other statuses throw. +- It never sleeps past `deadline`. If the next wait would end after it, it sleeps only until `deadline`, polls once + more, and returns `.deadlineReached(pending)` with the current handle if that poll is still pending. If the app + wakes after `deadline` (suspended mid-wait), it returns at once without polling. Each poll's timeout is clamped to + the time left (1–30 s). *(Revised after the final review, 2026-11-09.)* +- It first checks that the handle's `location` is on this client's KAS origin. A handle from another client throws + `.unsafeLocation`, and nothing is sent. +- A `403` on submit or poll is `.httpError(403, …)`, never `.accessDenied`: on this path a denial is always a + result. +- The sleep goes through an internal, injectable sleeper, so tests run instantly. + +**`rewrap`** runs prepare, submit and poll, with `deadline` defaulting to `expiresAt`, and unwraps the permitted +shares. Reaching that default deadline is `.expired`, because the KAS's own deadline has passed. +- On task cancellation it throws, and the pending handle is lost. A receiver that must survive backgrounding calls the + three steps itself and keeps the `PendingRewrap`. + +**New `KASRewrapError` cases:** `pendingWithoutLocation`, `unsafeLocation(String)`, `invalidRewrapOptions(String)`. +They are listed in the migration guide, because an exhaustive `switch` over `KASRewrapError` needs them. + +### 6. Path-aware matching + +`matchesKasURL` (used by `keyAccessObjects(in:)` and therefore every rewrap path) compares: +- scheme and host, case-insensitive; +- the effective port; +- the **normalized path**, case-sensitive. Normalizing trims trailing `/`, and `/kas` counts as empty, because a + platform KAS lives at `/kas` for REST and at the root for Connect, and discovery reports it without a path. + +Outcomes: + +| Configured KAS (`kas.uri`) | KAO `https://h/kas` | KAO `https://h` | KAO `https://h/owner-kas/v1/routes/R` | +| --- | --- | --- | --- | +| `https://h` (platform, from discovery) | match | match | no | +| `https://h/kas` | match | match | no | +| `https://h/owner-kas/v1/routes/R` | no | no | match | + +## Tests + +- **Verify (phone):** + - A request from `prepareRewrap` verifies, and its fields equal what was sent, including the extension, byte for + byte. + - Each of these is refused: another signing key; a changed payload after signing; a changed signature; `alg` `none` + or `HS256`; a body over 64 KiB; a non-PEM `clientPublicKey`; an empty `requests`; an invalid KAO. + - An expired token still parses and returns its `exp`. +- **Digests:** + - The client's `PreparedRewrap.requestTokenDigest` equals the phone's `RewrapRequest.requestTokenDigest` for the same + request. + - `keyAccessObjectDigest` of the manifest's key access object equals that of the object the phone parses from the + request. That holds for one written by `TDFEncryptor`, with `schemaVersion`, and for one with `sid` and + `encryptedMetadata`. Changing any one included field changes the digest; changing `schemaVersion` does not. + - `publicKeyFingerprint` is the same for a key parsed from PEM with LF or CRLF line endings, and from its SEC1 bytes. + - The phone's `policyBase64` is the manifest's `encryptionInformation.policy` string, byte for byte. +- **Response:** `rewrapResponseBody` output parsed by the client gives the same results. That covers a permit with + metadata of every value type, and a fail with an error code and metadata but no key. An invalid + permit/fail-and-key combination is refused. +- **Polling:** each through a scripted fake transport and a recording sleeper. + - 202 → 202 → 200 honors each `Retry-After`. + - The deadline returns `.deadlineReached` with a handle, and polling resumes from that handle. + - 410 gives `.expired`. A 404 after `expiresAt` gives `.expired`; a 404 before it throws. + - A `Location` on another host, port or scheme is refused before any request is sent to it. + - A 202 with no `Location` is refused. + - An HTTP-date or a missing `Retry-After` uses the default, and values are clamped. + - Submitting the same `PreparedRewrap` twice sends identical bytes. +- **Options:** the token's `exp` equals `expiresAt`; a past `expiresAt` is refused; an extension named `requests` + (or any other standard name) is refused; the request is signed with the init `signingKey`, verified with its + public key. +- **Matching:** the table above. A platform client and an owner client on one host each select only their own KAO. + Existing matching tests stay green. +- **End to end:** the real client against a fake transport that plays relay and phone in-process. The phone side runs + `verifyRewrapRequest`, then `TDFKAS.rewrap`, then `rewrapResponseBody`. + - An ALLOW gives a share equal to the DEK, with the metadata intact. + - A DENY gives a fail result with its metadata and nothing thrown. + +## Left to the builder + +- File layout. A new `OpenTDFKit/KASRewrapPending.swift` for the client half, and the phone half in `TDFKAS.swift` + or a sibling file, is the suggestion. +- Error-case names beyond those listed. +- README / CLAUDE.md / migration-guide wording. + +## The owner's decisions + +- OpenTDFKit defines the key access object digest and the public-key fingerprint, and arkavo-ios uses them, rather + than comparing JSON bytes (2026-11-09). + +## Calls made in this document (open to correction) + +1. **Path-aware matching is stricter than the issue's wording.** The issue says to match on path "when the configured + KAS URL has a path". Discovery gives the platform client a path-less `uri`, so under that rule a platform client + would also claim owner KAOs, which fails the issue's own "each client selects only its own KAO" test. The rule here + always compares the normalized path, with `/kas` the same as no path. + **Cost:** a KAS mounted at another prefix (for example `https://h/api/kas`) no longer matches a path-less client. + The configured `uri` must then carry that prefix. +2. **Resending is safe by keeping the signed bytes, not by re-signing.** CryptoKit's randomized ECDSA can't reproduce + a body, so `prepareRewrap` returns the bytes. `submitRewrap` never retries on its own; the app resends the same + `PreparedRewrap`. +3. **New methods, old ones unchanged.** The new client path signs with the init `signingKey`. The existing + `rewrapTDF` keeps signing with the client key and keeps throwing on a denial, so no current caller changes + behavior. +4. **`exp` is returned, not enforced, on the phone,** so an expired request can still get a signed `REQUEST_EXPIRED`. +5. **`Retry-After`:** delta-seconds only, default 2 s, clamped to 1–60 s, and never past the deadline. +8. **A poll `404` is expired only at or after the token's `exp`.** Before then the client can't tell a deleted + request from a wrong token, so it throws and the app shows the owner as unavailable. +6. **Only a same-origin `Location` is followed.** +7. **Bodies over 64 KiB are refused** on the phone side, the relay's own limit. diff --git a/scripts/interop/ec-wrapped/README.md b/scripts/interop/ec-wrapped/README.md new file mode 100644 index 0000000..2652fe5 --- /dev/null +++ b/scripts/interop/ec-wrapped/README.md @@ -0,0 +1,42 @@ +# ec-wrapped interop check + +Checks OpenTDFKit's TDF `ec-wrapped` key access objects and `TDFKAS` rewrap +responses against the go reference implementation, using the same +`github.com/opentdf/platform/lib/ocrypto` calls as the go SDK and the platform +KAS. + +## Regenerate the go fixture (go → Swift) + +```bash +cd scripts/interop/ec-wrapped +go run . generate > fixture.json +``` + +Paste `fixture.json` verbatim into `OpenTDFKitTests/TDFKASGoFixture.swift` +(between the `#"""` delimiters), then delete `fixture.json`. The key access +object mirrors the go SDK's `generateWrapKeyWithEC`; the response mirrors the +platform KAS's rewrap sealing. The policy binding is the spec form (Base64 of +the raw HMAC), not go's legacy hex form, which OpenTDFKit refuses. + +## Verify Swift output with go (Swift → go) + +Required before tagging a release that touches the EC path. + +```bash +OPENTDFKIT_INTEROP_OUT="$PWD/swift-interop.json" \ + swift test --filter TDFKASEncryptorTests/testWriteSwiftFixtureForGo +(cd scripts/interop/ec-wrapped && go run . verify "$OLDPWD/swift-interop.json") +rm swift-interop.json +``` + +The test encrypts a file with `TDFEncryptor.encryptFile`, copies the key access +object and policy byte for byte from the archive's `manifest.json`, and adds a +`TDFKAS.rewrap` response. `verify` checks the key access object's fields +(`type`, `url`, `protocol`, `kid`, `schemaVersion`), opens it the way the +platform KAS does, checks the spec-form policy binding, opens the response the +way the go SDK client does, and prints `OK`. + +`go test ./...` in this directory checks that `verify` accepts what `generate` +writes and refuses each kind of tampering. + +The keys in the fixture are generated for the test and protect nothing. diff --git a/scripts/interop/ec-wrapped/go.mod b/scripts/interop/ec-wrapped/go.mod new file mode 100644 index 0000000..39e37e6 --- /dev/null +++ b/scripts/interop/ec-wrapped/go.mod @@ -0,0 +1,11 @@ +module github.com/arkavo-org/OpenTDFKit/scripts/interop/ec-wrapped + +go 1.25.0 + +require github.com/opentdf/platform/lib/ocrypto v0.14.0 + +require ( + github.com/cloudflare/circl v1.6.3 // indirect + golang.org/x/crypto v0.52.0 // indirect + golang.org/x/sys v0.45.0 // indirect +) diff --git a/scripts/interop/ec-wrapped/go.sum b/scripts/interop/ec-wrapped/go.sum new file mode 100644 index 0000000..a5a8129 --- /dev/null +++ b/scripts/interop/ec-wrapped/go.sum @@ -0,0 +1,16 @@ +github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8= +github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/opentdf/platform/lib/ocrypto v0.14.0 h1:qAIOFpz72/QDhYC0oLRXgA5uEnyv1xqkc7kvWQSRFcY= +github.com/opentdf/platform/lib/ocrypto v0.14.0/go.mod h1:TLaMvVE1aTqrgW8AZz0ZuxX/ZpI7l5IQOHyX99fdKl0= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= +golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= +golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= +golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/scripts/interop/ec-wrapped/main.go b/scripts/interop/ec-wrapped/main.go new file mode 100644 index 0000000..94cd75b --- /dev/null +++ b/scripts/interop/ec-wrapped/main.go @@ -0,0 +1,272 @@ +// Command ec-wrapped checks OpenTDFKit's TDF `ec-wrapped` key access objects +// against the go reference implementation (github.com/opentdf/platform). +// +// go run . generate print a fixture produced the way go writes it +// go run . verify open a fixture written by OpenTDFKit the way go does +// +// generate mirrors sdk/tdf.go generateWrapKeyWithEC for the key access object +// and service/kas/access/rewrap.go for the rewrap response, using the same +// lib/ocrypto calls. The policy binding is the spec form, Base64 of the raw +// HMAC-SHA256, not go's legacy hex form, which OpenTDFKit refuses. +// +// verify reads the same JSON shape, written by OpenTDFKit's +// TDFKASEncryptorTests.testWriteSwiftFixtureForGo. It opens the key access +// object the way the platform KAS does (PEM-decode the ephemeral key, PKIX +// parse, compress, NewSaltedECDecryptor with the TDF salt), checks the +// spec-form policy binding, and opens the rewrap response the way the go SDK +// client does (ComputeECDHKey, CalculateHKDF with the TDF salt, AES-GCM). +package main + +import ( + "bytes" + "crypto/ecdsa" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "os" + + "github.com/opentdf/platform/lib/ocrypto" +) + +// tdfSalt is the go SDK's tdfSalt(): SHA256("TDF"). +func tdfSalt() []byte { + digest := sha256.Sum256([]byte("TDF")) + return digest[:] +} + +type policyBinding struct { + Alg string `json:"alg"` + Hash string `json:"hash"` +} + +type keyAccess struct { + Type string `json:"type"` + URL string `json:"url"` + Protocol string `json:"protocol"` + WrappedKey string `json:"wrappedKey"` + PolicyBinding policyBinding `json:"policyBinding"` + Kid string `json:"kid"` + SchemaVersion string `json:"schemaVersion"` + EphemeralPublicKey string `json:"ephemeralPublicKey"` +} + +type response struct { + WrappedKeyBase64 string `json:"wrappedKeyBase64"` + SessionPublicKeyPEM string `json:"sessionPublicKeyPEM"` +} + +type fixture struct { + KASPrivateKeyPEM string `json:"kasPrivateKeyPEM"` + PolicyBase64 string `json:"policyBase64"` + KAO keyAccess `json:"kao"` + DEKBase64 string `json:"dekBase64"` + ReceiverPrivateKeyPEM string `json:"receiverPrivateKeyPEM"` + Response response `json:"response"` +} + +func must[T any](v T, err error) T { + if err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } + return v +} + +func randomBytes(n int) []byte { + b := make([]byte, n) + must(rand.Read(b)) + return b +} + +func generate() fixture { + kas := must(ocrypto.NewECKeyPair(ocrypto.ECCModeSecp256r1)) + kasPublicPEM := must(kas.PublicKeyInPemFormat()) + dek := randomBytes(32) + + policyJSON := fmt.Sprintf(`{"uuid":"%s","body":{"dataAttributes":[],"dissem":["interop@example.com"]}}`, + hex.EncodeToString(randomBytes(16))) + policyBase64 := base64.StdEncoding.EncodeToString([]byte(policyJSON)) + + // Key access object: sdk/tdf.go generateWrapKeyWithEC. + ephemeral := must(ocrypto.NewECKeyPair(ocrypto.ECCModeSecp256r1)) + ephemeralPublicPEM := must(ephemeral.PublicKeyInPemFormat()) + ephemeralPrivatePEM := must(ephemeral.PrivateKeyInPemFormat()) + ecdhKey := must(ocrypto.ComputeECDHKey([]byte(ephemeralPrivatePEM), []byte(kasPublicPEM))) + sessionKey := must(ocrypto.CalculateHKDF(tdfSalt(), ecdhKey)) + gcm := must(ocrypto.NewAESGcm(sessionKey)) + wrapped := must(gcm.Encrypt(dek)) + + mac := hmac.New(sha256.New, dek) + mac.Write([]byte(policyBase64)) + + // Rewrap response: service/kas/access/rewrap.go. + receiver := must(ocrypto.NewECKeyPair(ocrypto.ECCModeSecp256r1)) + receiverPublicPEM := must(receiver.PublicKeyInPemFormat()) + encryptor := must(ocrypto.FromPublicPEMWithSalt(receiverPublicPEM, tdfSalt(), nil)) + sessionPublicPEM := must(encryptor.PublicKeyInPemFormat()) + rewrapped := must(encryptor.Encrypt(dek)) + + return fixture{ + KASPrivateKeyPEM: must(kas.PrivateKeyInPemFormat()), + PolicyBase64: policyBase64, + KAO: keyAccess{ + Type: "ec-wrapped", + URL: "https://kas.example.com", + Protocol: "kas", + WrappedKey: base64.StdEncoding.EncodeToString(wrapped), + PolicyBinding: policyBinding{Alg: "HS256", Hash: base64.StdEncoding.EncodeToString(mac.Sum(nil))}, + Kid: "e1", + SchemaVersion: "1.0", + EphemeralPublicKey: ephemeralPublicPEM, + }, + DEKBase64: base64.StdEncoding.EncodeToString(dek), + ReceiverPrivateKeyPEM: must(receiver.PrivateKeyInPemFormat()), + Response: response{ + WrappedKeyBase64: base64.StdEncoding.EncodeToString(rewrapped), + SessionPublicKeyPEM: sessionPublicPEM, + }, + } +} + +func verify(path string) error { + var f fixture + if err := json.Unmarshal(must(os.ReadFile(path)), &f); err != nil { + return fmt.Errorf("reading %s: %w", path, err) + } + return verifyFixture(f) +} + +func verifyFixture(f fixture) error { + dek, err := base64.StdEncoding.DecodeString(f.DEKBase64) + if err != nil { + return fmt.Errorf("dekBase64: %w", err) + } + if f.KAO.Type != "ec-wrapped" { + return fmt.Errorf("kao type is %q, want ec-wrapped", f.KAO.Type) + } + if f.KAO.Kid == "" { + return errors.New("kao has no kid; a platform KAS finds EC keys by kid") + } + // Field spellings: a writer whose JSON keys differ from go's tags leaves these empty. + if f.KAO.URL == "" { + return errors.New("kao has no url") + } + if f.KAO.Protocol != "kas" { + return fmt.Errorf("kao protocol is %q, want kas", f.KAO.Protocol) + } + if f.KAO.SchemaVersion == "" { + return errors.New("kao has no schemaVersion") + } + + // Key access object, as service/kas/access/rewrap.go case "ec-wrapped". + if _, err := ocrypto.GetECKeySize([]byte(f.KAO.EphemeralPublicKey)); err != nil { + return fmt.Errorf("ephemeral key size: %w", err) + } + block, _ := pem.Decode([]byte(f.KAO.EphemeralPublicKey)) + if block == nil { + return errors.New("ephemeral public key is not PEM") + } + pub, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return fmt.Errorf("ephemeral public key: %w", err) + } + ecPub, ok := pub.(*ecdsa.PublicKey) + if !ok { + return errors.New("ephemeral key is not EC") + } + compressed, err := ocrypto.CompressedECPublicKey(ocrypto.ECCModeSecp256r1, *ecPub) + if err != nil { + return fmt.Errorf("compress ephemeral key: %w", err) + } + kasKey, err := ocrypto.ECPrivateKeyFromPem([]byte(f.KASPrivateKeyPEM)) + if err != nil { + return fmt.Errorf("kas private key: %w", err) + } + decryptor, err := ocrypto.NewSaltedECDecryptor(kasKey, tdfSalt(), nil) + if err != nil { + return err + } + wrapped, err := base64.StdEncoding.DecodeString(f.KAO.WrappedKey) + if err != nil { + return fmt.Errorf("kao wrappedKey: %w", err) + } + share, err := decryptor.DecryptWithEphemeralKey(wrapped, compressed) + if err != nil { + return fmt.Errorf("kao unwrap: %w", err) + } + if !bytes.Equal(share, dek) { + return errors.New("kao unwrapped to a different key") + } + + // Policy binding, spec form. + if f.KAO.PolicyBinding.Alg != "HS256" { + return fmt.Errorf("binding alg is %q, want HS256", f.KAO.PolicyBinding.Alg) + } + expected, err := base64.StdEncoding.DecodeString(f.KAO.PolicyBinding.Hash) + if err != nil || len(expected) != sha256.Size { + return errors.New("binding hash is not base64 of a 32-byte HMAC") + } + mac := hmac.New(sha256.New, dek) + mac.Write([]byte(f.PolicyBase64)) + if !hmac.Equal(mac.Sum(nil), expected) { + return errors.New("policy binding does not verify") + } + + // Rewrap response, as sdk/kas_client.go opens an EC session response. + ecdhKey, err := ocrypto.ComputeECDHKey([]byte(f.ReceiverPrivateKeyPEM), []byte(f.Response.SessionPublicKeyPEM)) + if err != nil { + return fmt.Errorf("response ECDH: %w", err) + } + sessionKey, err := ocrypto.CalculateHKDF(tdfSalt(), ecdhKey) + if err != nil { + return err + } + gcm, err := ocrypto.NewAESGcm(sessionKey) + if err != nil { + return err + } + rewrapped, err := base64.StdEncoding.DecodeString(f.Response.WrappedKeyBase64) + if err != nil { + return fmt.Errorf("response wrappedKeyBase64: %w", err) + } + opened, err := gcm.Decrypt(rewrapped) + if err != nil { + return fmt.Errorf("response unwrap: %w", err) + } + if !bytes.Equal(opened, dek) { + return errors.New("response unwrapped to a different key") + } + return nil +} + +func main() { + if len(os.Args) < 2 { + fmt.Fprintln(os.Stderr, "usage: ec-wrapped generate | verify ") + os.Exit(2) + } + switch os.Args[1] { + case "generate": + out := must(json.MarshalIndent(generate(), "", " ")) + fmt.Println(string(out)) + case "verify": + if len(os.Args) != 3 { + fmt.Fprintln(os.Stderr, "usage: ec-wrapped verify ") + os.Exit(2) + } + if err := verify(os.Args[2]); err != nil { + fmt.Fprintln(os.Stderr, "FAIL:", err) + os.Exit(1) + } + fmt.Println("OK") + default: + fmt.Fprintln(os.Stderr, "unknown command:", os.Args[1]) + os.Exit(2) + } +} diff --git a/scripts/interop/ec-wrapped/main_test.go b/scripts/interop/ec-wrapped/main_test.go new file mode 100644 index 0000000..5cb6de3 --- /dev/null +++ b/scripts/interop/ec-wrapped/main_test.go @@ -0,0 +1,44 @@ +package main + +import "testing" + +// A fixture generate() writes the way go does must verify. +func TestVerifyAcceptsGeneratedFixture(t *testing.T) { + if err := verifyFixture(generate()); err != nil { + t.Fatalf("verify(generate()) = %v", err) + } +} + +// Each mutation must make verify fail. The field checks catch a writer that +// spells a key access object field differently from go's JSON tags. +func TestVerifyRejectsBadFixtures(t *testing.T) { + tamper := func(s string) string { + b := []byte(s) + if b[10] == 'A' { + b[10] = 'B' + } else { + b[10] = 'A' + } + return string(b) + } + cases := map[string]func(*fixture){ + "empty url": func(f *fixture) { f.KAO.URL = "" }, + "wrong protocol": func(f *fixture) { f.KAO.Protocol = "" }, + "empty schemaVersion": func(f *fixture) { f.KAO.SchemaVersion = "" }, + "empty kid": func(f *fixture) { f.KAO.Kid = "" }, + "wrong type": func(f *fixture) { f.KAO.Type = "wrapped" }, + "tampered policy": func(f *fixture) { f.PolicyBase64 = tamper(f.PolicyBase64) }, + "tampered binding": func(f *fixture) { f.KAO.PolicyBinding.Hash = tamper(f.KAO.PolicyBinding.Hash) }, + "tampered wrapped key": func(f *fixture) { f.KAO.WrappedKey = tamper(f.KAO.WrappedKey) }, + "tampered response": func(f *fixture) { f.Response.WrappedKeyBase64 = tamper(f.Response.WrappedKeyBase64) }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + f := generate() + mutate(&f) + if err := verifyFixture(f); err == nil { + t.Fatal("verify accepted a bad fixture") + } + }) + } +}