Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
b6ed4f3
docs: design and plan for KAS-side TDF EC rewrap (#66)
arkavo-com Nov 8, 2026
46fba4e
feat(kas): TDF EC client unwrap and go interop fixture (#66)
arkavo-com Nov 8, 2026
7c4f7db
feat(kas): KAS-side TDF ec-wrapped rewrap (#66)
arkavo-com Nov 8, 2026
69cdd60
feat(tdf): ec-wrapped key access objects from TDFEncryptor (#66)
arkavo-com Nov 8, 2026
77a2696
test(interop): verify Swift ec-wrapped output with go; docs for 5.2.0…
arkavo-com Nov 8, 2026
2111335
fix(kas): parse ec-wrapped PEM like the platform; empty alg is HS256 …
arkavo-com Nov 8, 2026
53fb664
fix(kas): close review minors on the ec-wrapped path (#66)
arkavo-com Nov 8, 2026
c267fdc
ci: ec-wrapped interop job and xtest tdf-ecwrap (#66)
arkavo-com Nov 9, 2026
d0c7332
docs: design and plan for owner-KAS rewrap (#66)
arkavo-com Nov 9, 2026
cd9c754
feat(kas): shared request, KAO and key digests (#66)
arkavo-com Nov 9, 2026
0ff40c2
fix(kas): match key access objects by path too (#66)
arkavo-com Nov 9, 2026
3a6a9bc
feat(kas): verify a received Rewrap on the owner KAS (#66)
arkavo-com Nov 9, 2026
78358e7
feat(kas): build a Rewrap response on the owner KAS (#66)
arkavo-com Nov 9, 2026
b78cda1
feat(kas): prepare a signed Rewrap with caller exp and extension (#66)
arkavo-com Nov 9, 2026
f00dd47
feat(kas): poll a KAS that answers later; return full Rewrap results …
arkavo-com Nov 9, 2026
5fb1342
test(kas): owner-KAS end to end; docs (#66)
arkavo-com Nov 9, 2026
ce9a8d3
fix(kas): strict JWS and JSON checks on the owner KAS (#66)
arkavo-com Nov 9, 2026
a8c7e8d
fix(kas): harden the pending Rewrap client and matching (#66)
arkavo-com Nov 9, 2026
40b98f1
fix(kas): close Gitar findings on the owner-KAS path (#66)
arkavo-com Nov 9, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 57 additions & 1 deletion .github/workflows/swift.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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()
Expand Down
9 changes: 5 additions & 4 deletions .github/workflows/xtest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 }}
Expand All @@ -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 }}"
Expand Down Expand Up @@ -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 \
Expand Down
10 changes: 7 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
Expand Down Expand Up @@ -211,17 +213,19 @@ 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-<i>`) 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-<i>`) 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`.

### TDF (Archive Envelope) Components

- **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.

Expand Down
18 changes: 18 additions & 0 deletions MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)`.
Expand Down
Loading
Loading