Skip to content

feat(kas): owner KAS — KAS-side TDF EC rewrap and a Rewrap client for a KAS that answers later (#66) - #68

Merged
arkavo-com merged 19 commits into
mainfrom
feat/66-kas-side-ec-rewrap
Nov 9, 2026
Merged

arkavo-com merged 19 commits into
mainfrom
feat/66-kas-side-ec-rewrap

Conversation

@arkavo-com

@arkavo-com arkavo-com commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Implements the revised #66, items 1–9, for an owner KAS: an owner's iPhone that acts as a KAS behind a relay at https://platform.arkavo.net/owner-kas/v1/routes/<route_id>. The receiver calls it with KASRewrapClient, as it calls a platform KAS. Item 10, the 5.2.0 tag, follows after merge.

Designs:

  • docs/superpowers/specs/2026-11-08-kas-side-ec-rewrap-design.md (items 1 and 9)
  • docs/superpowers/specs/2026-11-09-owner-kas-rewrap-design.md (items 2–8)

The consumer contract is arkavo-ios's owner-KAS design §4.1–§4.6. arkavo-ios has adopted this PR's digest functions.

KAS side, used on the owner's phone (pure: no network, no storage, keys as values)

  • Item 1: TDFKAS.rewrap(keyAccessObject:policyBase64:kasPrivateKey:receiverPublicKey:).

    • Opens the key share in an ec-wrapped key access object, verifies the spec-form policy binding, and seals the share to the receiver under a fresh session key.
    • The binding is HS256 with the raw HMAC; go's legacy hex form is refused.
    • The share is wiped on every exit.
  • Item 2: TDFKAS.verifyRewrapRequest(body:signingPublicKey:) verifies a received Rewrap:

    • at most 64 KiB, ES256 only, no crit header;
    • canonical base64url, and no duplicate JSON members anywhere;
    • returns exp without enforcing it, so the phone can still sign a REQUEST_EXPIRED denial.

    It returns clientPublicKey, the policies with their key access objects, and the extension members.

  • Item 3: TDFKAS.rewrapResponseBody(sessionPublicKey:responses:) builds the response, with caller metadata.

  • Shared digests: both sides call these functions; none of them hashes JSON bytes.

    • TDFKAS.requestTokenDigest is SHA-256 of the JWT string.
    • TDFKAS.keyAccessObjectDigest uses a fixed field encoding without schemaVersion, so the manifest's object and the one the client forwards digest the same.
    • TDFKAS.publicKeyFingerprint is SHA-256 of the uncompressed SEC1 point.

Client side (KASRewrapClient, the receiver)

  • Items 4, 5, 7 and 8: prepareRewrap, then submitRewrap, then pollRewrap; or rewrap, which runs all three. Existing methods are unchanged.

    • The request is signed with the init signingKey, which is the owner-KAS token's cnf key.
    • The caller sets the token's exp and can add one requestBody extension member.
    • Resending the same PreparedRewrap sends identical bytes.
    • A 202 is polled at a same-origin Location only; the origin is checked on submit and again on every poll.
    • Retry-After is clamped to 1–60 s. Polling never happens after the deadline, the last wait ends at the deadline with one final poll, and each poll's timeout is clamped to the time left.
    • 410, or a 404 at or after the token's exp, is .expired. A 403 on this path is an HTTP error, never accessDenied.
    • Every result is returned with its status, error, metadata and kasWrappedKey, together with the session key and the request-token digest. A denial is a result, not a thrown error.
  • Item 6: path-aware matching. A key access object matches by scheme, host, port and normalized path:

    • percent-encoded unreserved characters are decoded;
    • a trailing / is trimmed;
    • /kas is treated the same as no path.

    A platform client and an owner client on platform.arkavo.net each select only their own object. The cost: a KAS mounted under another prefix, for example /api/kas, needs that prefix in its configured URL.

Encrypt (item 9)

TDFKasInfo.keyType: .ecP256 writes a go-compatible ec-wrapped key access object, with a kid and AES-256 required. OpenTDFKitCLI supports ecwrap.

Evidence

  • swift test: 448 tests, 0 failures, 15 skipped. The skipped tests need a live platform, plus the opt-in fixture writer.
  • End to end: the real client against a fake relay and phone that uses verifyRewrapRequest, a key access object digest check, TDFKAS.rewrap and rewrapResponseBody.
    • Allow: decrypts the payload, with one request-token digest on both sides and the decision metadata intact.
    • Deny: comes back as a fail result, not an error.
  • go interop:
    • The CI job interop-ec-wrapped runs go test on the go verifier, and go opens a Swift-written key access object and rewrap response.
    • A committed go fixture is opened in Swift.
  • xtest (live platform ca178b05, EC enabled): swift→go, go→swift and swift→swift all pass for both tdf and tdf-ecwrap, in both go legs.

Review

The design went through a builder check, Codex and an advisor. The code had a fresh whole-branch review and a Codex review, and every finding was fixed in this PR:

  • strict JWS/JSON checks (ce9a8d3);
  • pending-client and matching hardening (a8c7e8d);
  • the earlier EC rewrap fixes (2111335, 53fb664).

🤖 Generated with Claude Code

https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B

arkavo-com and others added 6 commits November 8, 2026 17:55
TDFKAS.unwrap opens a rewrapped key share with the TDF session salt for
responses that did not come over HTTP. A go program generates a fixture
the way the go SDK and platform KAS write it; the Swift test opens it.
KASRewrapClient.unwrapKey now wipes the opened key bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
TDFKAS.rewrap opens the key share in an ec-wrapped key access object
with the KAS private key, verifies the spec-form policy binding (HS256,
raw HMAC; the legacy hex form is refused), and seals the share to the
receiver under a fresh session key. The share is wiped on every exit.
TDFCrypto.wrapSymmetricKeyWithECForKAS writes the go SDK's ec-wrapped
scheme (SHA256("TDF") salt, PEM ephemeral key).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
TDFKasInfo gains keyType (.rsa by default, .ecP256). Every encrypt
entry point builds its key access object through one helper: .rsa
writes today's wrapped object, .ecP256 writes an ec-wrapped object in
the go SDK scheme. An .ecP256 KAS without a kid, or with AES-128, is
refused before anything is encrypted. The TDF-JSON/CBOR EC functions
are documented as their own scheme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
…#66)

testWriteSwiftFixtureForGo (opt-in via OPENTDFKIT_INTEROP_OUT) writes a
key access object from TDFEncryptor and a TDFKAS.rewrap response; the
go program's verify subcommand opens them the way the platform KAS and
go SDK client do. Run before tagging. CLAUDE.md and the migration guide
describe the new API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
…66)

TDFKAS.rewrap parsed the ephemeral key with CryptoKit's PEM reader,
which only accepts 64-column lines; the platform KAS (go pem.Decode)
accepts any line length, spaces and tabs in the body, and text after
the END line. Decode the body and parse the DER instead. An empty
policyBinding alg now means HS256 on a hand-built key access object,
as the decoder and the OpenTDF spec already have it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
Comment thread OpenTDFKit/TDF/TDFKAS.swift Resolved
- TDFEncryptor loads the KAS public key as its declared type before
  reading the input, so a key-type/PEM mismatch fails fast; a blank kid
  is refused like a missing one.
- TDFKAS.unwrap passes CryptoKit keys through a typed unwrapKey, so no
  raw copy of the receiver private key is made; the EC wrap seals from
  the key's own storage instead of copying the share.
- Key derivation moves into TDFCrypto (TDFKAS calls down, not up).
- An empty ephemeralPublicKey is reported as missing, as go omitempty.
- Refusal tests cover all four encrypt entry points and assert nothing
  is written. The Swift-to-go fixture is copied from a real archive's
  manifest.json; go verify checks url, protocol and schemaVersion, with
  go tests for verify itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gitar has auto-approved this PR (configure)

- OpenTDFKitCLI supports ecwrap: with XT_WITH_ECWRAP=true, tdf encrypt
  fetches the KAS EC P-256 key and kid and writes an ec-wrapped key
  access object. Decrypt already rewraps with an EC session key.
- xtest runs the tdf-ecwrap container as well as tdf, so a platform KAS
  (ca178b05, ec-tdf-enabled) rewraps OpenTDFKit's ec-wrapped objects and
  go and Swift decrypt each other's; the probe now expects ecwrap.
- swift.yaml gains interop-ec-wrapped: go tests its verifier, then opens
  a key access object and rewrap response Swift wrote from a real
  encryptFile archive. The manual pre-tag step becomes a PR check.
- benchmark job: quote the *.log glob (actionlint SC2035).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gitar has auto-approved this PR (configure)

arkavo-com and others added 8 commits November 8, 2026 20:58
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
TDFKAS.requestTokenDigest, keyAccessObjectDigest (a fixed field
encoding, so the manifest's object and the one a client forwards digest
the same) and publicKeyFingerprint (SHA-256 of the uncompressed SEC1
point), for the owner KAS's decision record and the receiver.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
A platform KAS and owner KASs share platform.arkavo.net, so a client
now also compares the normalized path: trailing slashes trimmed, /kas
the same as no path (discovery reports the platform KAS without one).
A KAS mounted under another prefix needs that prefix in its uri.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
TDFKAS.verifyRewrapRequest checks a Rewrap body (64 KiB at most), the
signed request token (ES256 only, raw signature over header.payload as
received) under a given key, and parses requestBody: clientPublicKey,
policies with their key access objects, and extension members as raw
JSON. exp is returned, not enforced, so an expired request can still
get a signed denial.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
TDFKAS.rewrapResponseBody writes the standard Rewrap response for permit
and fail results, with caller metadata in the client's own value type so
it round-trips, and refuses a permit without a key or a fail with one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
KASRewrapClient.prepareRewrap builds and signs a Rewrap for this KAS's
key access objects without sending it: signed with the init signingKey
(an owner KAS's cnf key), the token's exp set by the caller (default 60
s), one extension member inside requestBody, the policy forwarded
verbatim, and the request-token digest. Resending the same value sends
identical bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
…66)

submitRewrap sends a prepared Rewrap once: 200 is answered, 202 is
pending with a same-origin Location (anything else is refused, since the
bearer goes there) and Retry-After (delta-seconds, 1-60 s, default 2).
pollRewrap polls with the same bearer until 200, 410 or a 404 after the
token's exp (expired), or returns the handle when the caller's deadline
comes first. Every result is returned with its status, error, metadata
and kasWrappedKey, the session key and the request-token digest; a
denial is a result, not an error. rewrap runs all three and unwraps the
permitted shares. The sleeper and clock are injectable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
The receiver's client against a fake relay that queues the Rewrap and,
on a later poll, lets the phone answer with verifyRewrapRequest, a KAO
digest check, TDFKAS.rewrap and rewrapResponseBody. ALLOW yields the DEK
and decrypts the payload with the decision metadata intact and one
request-token digest on both sides; DENY is a fail result, not an error.
CLAUDE.md and the migration guide describe the owner-KAS API and
path-aware matching.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
Comment thread OpenTDFKit/KASRewrapPending.swift Resolved

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gitar has auto-approved this PR (configure)

arkavo-com and others added 2 commits November 8, 2026 21:24
From review (Codex, final reviewer):
- refuse duplicate member names in the body, header, claims and
  requestBody (RFC 7515 10.12, RFC 7519 4), compared after unescaping;
- refuse a crit header (RFC 7515 4.1.11): no extensions are supported;
- require canonical unpadded base64url for every JWS part, so a token
  has one spelling and one request-token digest;
- refuse iat: null;
- extensions are re-serialized with sorted keys and unescaped slashes,
  and a failure throws instead of dropping the member;
- rewrapResponseBody refuses a permit without a session key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
From review (Codex, final reviewer):
- pollRewrap rechecks that a handle is on this client's KAS origin, so
  one client's handle never carries another client's bearer elsewhere;
- a Location with user info is refused;
- the deadline is checked after waking too (a suspended app never polls
  late), the last wait ends at the deadline with one more poll, and each
  poll's timeout ends at the deadline; rewrap's default deadline (the
  token's exp) is reported as expired;
- a 403 on this path is httpError, never accessDenied;
- an answer that answers no sent key access object throws emptyResponse,
  and a result with an undecodable key is kept without it;
- an out-of-range expiresAt throws instead of trapping;
- matching decodes percent-encoded unreserved path characters;
- tests: cross-client handle, hostile Location on a poll, oversleep,
  timeouts, userinfo, the KAO digest with sid and encryptedMetadata
  through the client's encoding; docs and spec updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
@arkavo-com arkavo-com changed the title feat(kas): KAS-side TDF ec-wrapped rewrap and client unwrap (#66) feat(kas): owner KAS — KAS-side TDF EC rewrap and a Rewrap client for a KAS that answers later (#66) Nov 9, 2026
Comment thread OpenTDFKit/KASRewrapPending.swift Resolved

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gitar has auto-approved this PR (configure)

- A PEM whose END marker overlaps the BEGIN marker's dashes
  ("-----BEGIN PUBLIC KEY-----END PUBLIC KEY-----") built an invalid
  range and trapped: any requester could crash the owner's KAS through
  TDFKAS.rewrap or verifyRewrapRequest's clientPublicKey. END is now
  searched for only after BEGIN.
- A negative expiresAt beyond Int's range trapped in Int(_:); the guard
  now has a lower bound.
- Retry-After too large for Int fell back to 2 s instead of the 60 s
  cap, and "+5" was read as 5 s; delta-seconds is now ASCII digits
  only, and overflow clamps to 60.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XAvDR2wxp8A5rjt3P3FB1B
@gitar-bot

gitar-bot Bot commented Nov 9, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 3 closed / 3 findings

🔴 High risk · Adding owner-KAS EC key rewrapping and signed Rewrap handling could expose protected key shares if verification or access decisions fail.

Adds an owner-KAS path with KAS-side EC rewrap, a verifier for received Rewrap requests, and a pending-aware KASRewrapClient with path-aware key access object matching. Resolved this session: an oversized Retry-After now falls back to 2 s instead of the 60 s cap, and a huge negative expiresAt no longer traps in Int(_:). No open issues found.

✅ 3 closed
✅ Edge Case: Retry-After too large for Int falls back to 2 s, not the 60 s cap

📄 OpenTDFKit/KASRewrapPending.swift:295-300
retryAfterSeconds parses with Int(...). A delta-seconds value that doesn't fit in an Int (e.g. "99999999999999999999") makes that parse return nil, so the function returns the 2 s default instead of the 60 s cap. A relay that asks for a long back-off then gets polled every 2 s. The plan's Review Focus says huge values are clamped, but the test only checks "999". Fix: treat any all-digit string as delta-seconds and clamp it on overflow.

✅ Edge Case: Huge negative expiresAt still traps in Int(_:) despite the new guard

📄 OpenTDFKit/KASRewrapPending.swift:90-95 📄 OpenTDFKitTests/KASRewrapPendingTests.swift:360-366
The new guard checks only isFinite and the upper bound (<= 253_402_300_799). A finite value below Int.min, such as Date(timeIntervalSince1970: -1e300), gets through, and Int(requested) then crashes the process before the expiresAt > issuedAt check can throw .invalidRewrapOptions. The comment says this guard keeps Int(_:) from trapping, but it only covers the positive side, and testOutOfRangeExpiresAtRefused never tries a negative value. Fix: add a lower bound to the guard (any past time is rejected later anyway), e.g. requested >= 0, and add -1e300 to the test.

Closed: Bug: Crafted ephemeral PEM crashes TDFKAS.rewrap with an invalid Range

📄 OpenTDFKit/TDF/TDFKAS.swift:155-159
parseEphemeralPublicKey looks for the END marker anywhere in trimmed, starting from the beginning of the string. The BEGIN marker ends in ----- and the END marker starts with -----, so the two can overlap. For an input like "-----BEGIN PUBLIC KEY-----END PUBLIC KEY-----", range(of: end) finds the END marker at offset 21, before the body start at offset 26. Building start ..< endRange.lowerBound with lowerBound greater than upperBound is a runtime trap in Swift.

ephemeralPublicKey comes straight from a requester-supplied key access object, so anyone who can send a rewrap request can crash the on-device KAS process. The function is supposed to throw TDFKASError instead. The fix is to search for the END marker only after the BEGIN marker, which gives an empty body and an .invalidEphemeralPublicKey throw instead of a crash.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Approved

For more verification details, comment gitar display:verbose.

Options

Auto-apply is off → Gitar will not commit updates to this branch.
Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Auto-apply Compact
gitar auto-apply:on         
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

@arkavo-com
arkavo-com deleted the feat/66-kas-side-ec-rewrap branch November 9, 2026 02:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant