oficina / home Public

handoff: native nonce derivation, Verify and Reserve for NativeExchange

Human

Prompt

Implement the consumer (connect) half of slice A of the approved Oficina ID native spec, and wire it into Docs. Coordinate only through the spec's wire formats.

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

Adds the one derivation both Home's assert and an instance's NativeExchange use (verifier -> challenge -> nonce, with a fixed test vector), a Verify that consumes nothing, and a Reserve that burns (iss,jti) in its own committed transaction (spec 2026-11-14 §7 step 5).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c43a9100faf05a126948b54b6d574540268a56ea parent 979dac4
2 files changed, +213 −0
  • handoff/native.go +113 −0
  • handoff/native_test.go +100 −0

CI cancelled — superseded by a newer push — run details

diff --git a/handoff/native.go b/handoff/native.go
new file mode 100644
index 0000000..3b7f26d
--- /dev/null
+++ b/handoff/native.go
@@ -0,0 +1,113 @@
+package handoff
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/assertion"
+)
+
+// The native slice (Home spec 2026-11-14-oficina-id-native.md §7) has no
+// browser and so no pending row: a native client proves it requested an
+// assertion by holding the verifier behind the challenge it gave Home, and
+// Home, not the client, sets the nonce from that challenge. These two
+// functions are the whole derivation. Home's assert and every instance's
+// NativeExchange use them, so the two sides cannot drift apart.
+//
+// On the wire every value is unpadded base64url:
+//
+// verifier = 32 random bytes (43 characters)
+// challenge = SHA-256(verifier bytes) (43 characters)
+// nonce = SHA-256("oficina-id/native/v1" || 0x00 || challenge bytes)[:16]
+// (22 characters)
+//
+// The nonce is cut to 16 bytes because an assertion nonce is exactly that
+// (rastrillo assertion: 22 characters of 16 bytes).
+const nativeNonceContext = "oficina-id/native/v1\x00"
+
+// NativeChallenge is the challenge for a native verifier, or false unless
+// the verifier is the canonical encoding of exactly 32 bytes.
+func NativeChallenge(verifier string) (string, bool) {
+ raw, ok := decode32(verifier)
+ if !ok {
+ return "", false
+ }
+ sum := sha256.Sum256(raw)
+ return base64.RawURLEncoding.EncodeToString(sum[:]), true
+}
+
+// NativeNonce is the nonce Home sets on a native assertion for challenge,
+// or false unless the challenge is the canonical encoding of 32 bytes.
+// Nothing else may produce a native nonce: a caller-chosen nonce is a
+// browser's (/authorize), and NativeExchange accepts only this one.
+func NativeNonce(challenge string) (string, bool) {
+ raw, ok := decode32(challenge)
+ if !ok {
+ return "", false
+ }
+ sum := sha256.Sum256(append([]byte(nativeNonceContext), raw...))
+ return base64.RawURLEncoding.EncodeToString(sum[:16]), true
+}
+
+func decode32(s string) ([]byte, bool) {
+ if len(s) != 43 {
+ return nil, false
+ }
+ raw, err := base64.RawURLEncoding.Strict().DecodeString(s)
+ return raw, err == nil && len(raw) == 32 && base64.RawURLEncoding.EncodeToString(raw) == s
+}
+
+// Verify checks an assertion against this store's pinned keys, issuer and
+// audience at now. It consumes and writes nothing: a native exchange
+// verifies first and reserves the jti only once it has decided to mint.
+func (s *Store) Verify(token string, now time.Time) (assertion.Claims, error) {
+ claims, err := s.verifier.Verify(token, now)
+ if err != nil {
+ return assertion.Claims{}, ErrRefused
+ }
+ return claims, nil
+}
+
+// Reserve burns an assertion's (iss, jti) in its own short transaction and
+// commits before returning, so no caller can hold the writer across it.
+// It re-verifies the token, and refuses one whose jti is already reserved
+// or is waiting in a browser's inbox. A reserved jti that then produces no
+// session costs only a fresh assertion; a jti is never reserved twice, so
+// replay stays impossible (the native slice's accepted non-atomicity).
+func (s *Store) Reserve(ctx context.Context, token string, now time.Time) (assertion.Claims, error) {
+ zero := assertion.Claims{}
+ claims, err := s.Verify(token, now)
+ if err != nil {
+ return zero, err
+ }
+ tx, _, _, err := s.begin(ctx, now)
+ if err != nil {
+ return zero, err
+ }
+ defer tx.Rollback()
+ jti := jtiHash(claims)
+ var waiting int
+ if err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM oficina_handoff_inbox WHERE jti_hash=?`, jti).Scan(&waiting); err != nil {
+ return zero, ErrStorage
+ }
+ if waiting != 0 {
+ return zero, ErrRefused
+ }
+ result, err := tx.ExecContext(ctx, `INSERT INTO oficina_handoff_replay(jti_hash,expires_at) VALUES(?,?) ON CONFLICT DO NOTHING`, jti, claims.ExpiresAt)
+ if err != nil {
+ return zero, ErrStorage
+ }
+ rows, err := result.RowsAffected()
+ if err != nil {
+ return zero, ErrStorage
+ }
+ if rows != 1 {
+ return zero, ErrRefused
+ }
+ if tx.Commit() != nil {
+ return zero, ErrStorage
+ }
+ return claims, nil
+}
diff --git a/handoff/native_test.go b/handoff/native_test.go
new file mode 100644
index 0000000..1ca2513
--- /dev/null
+++ b/handoff/native_test.go
@@ -0,0 +1,100 @@
+package handoff
+
+import (
+ "context"
+ "testing"
+)
+
+// A fixed vector, so Home's assert, every instance and the Swift client can
+// each check their derivation against the same bytes (verifier = 0x00..0x1f).
+func TestNativeNonceVector(t *testing.T) {
+ const verifier = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"
+ challenge, ok := NativeChallenge(verifier)
+ if !ok || challenge != "Yw3NKWbEM2aRElRIu7JbT_QSpJxzLbLIq8G4WBvXEN0" {
+ t.Fatalf("challenge %q %v", challenge, ok)
+ }
+ nonce, ok := NativeNonce(challenge)
+ if !ok || nonce != "cU9jQRCTNby9G46AOrt78A" || !ValidNonce(nonce) {
+ t.Fatalf("nonce %q %v", nonce, ok)
+ }
+}
+
+func TestNativeDerivationRefusesNonCanonicalInput(t *testing.T) {
+ for _, bad := range []string{
+ "",
+ "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", // padded
+ "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh", // 31 bytes
+ "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh9", // non-canonical last character
+ "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh+", // standard alphabet
+ "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8\n", // trailing newline
+ } {
+ if _, ok := NativeChallenge(bad); ok {
+ t.Errorf("NativeChallenge accepted %q", bad)
+ }
+ if _, ok := NativeNonce(bad); ok {
+ t.Errorf("NativeNonce accepted %q", bad)
+ }
+ }
+}
+
+func TestVerifyConsumesNothing(t *testing.T) {
+ f := fresh(t)
+ token := f.token(t, "cU9jQRCTNby9G46AOrt78A")
+ for range 2 {
+ if c, err := f.s.Verify(token, f.now); err != nil || c.Nonce != "cU9jQRCTNby9G46AOrt78A" {
+ t.Fatal(c, err)
+ }
+ }
+ if count(t, f.db, "oficina_handoff_replay") != 0 {
+ t.Fatal("Verify wrote a replay row")
+ }
+ if _, err := f.s.Verify(token, f.now.Add(10*60e9)); err != ErrRefused {
+ t.Fatal("expired assertion verified", err)
+ }
+}
+
+func TestReserveOnceAcrossRestart(t *testing.T) {
+ f := fresh(t)
+ ctx := context.Background()
+ token := f.token(t, "cU9jQRCTNby9G46AOrt78A")
+ if c, err := f.s.Reserve(ctx, token, f.now); err != nil || c.Subject != "person_123" {
+ t.Fatal(c, err)
+ }
+ if _, err := f.s.Reserve(ctx, token, f.now); err != ErrRefused {
+ t.Fatal("reserved twice", err)
+ }
+ // A new Store over the same database is a restarted process.
+ again, err := NewStore(f.db, f.s.sealer, f.s.issuer, f.s.audience, map[string][]byte{"k1": f.k.SignPub()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := again.Reserve(ctx, token, f.now); err != ErrRefused {
+ t.Fatal("reserved again after a restart", err)
+ }
+ // And the browser path refuses what the native path reserved.
+ if _, err := f.s.Receive(ctx, token, f.now); err != ErrRefused {
+ t.Fatal("browser received a reserved assertion", err)
+ }
+}
+
+func TestReserveRefusesAWaitingBrowserReceipt(t *testing.T) {
+ f := fresh(t)
+ _, nonce := f.pending(t)
+ token := f.token(t, nonce)
+ if _, err := f.s.Receive(context.Background(), token, f.now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.s.Reserve(context.Background(), token, f.now); err != ErrRefused {
+ t.Fatal("reserved an assertion waiting in a browser inbox", err)
+ }
+}
+
+func TestReserveRefusesAnInvalidToken(t *testing.T) {
+ f := fresh(t)
+ if _, err := f.s.Reserve(context.Background(), "not-a-token", f.now); err != ErrRefused {
+ t.Fatal(err)
+ }
+ if count(t, f.db, "oficina_handoff_replay") != 0 {
+ t.Fatal("an invalid token wrote a replay row")
+ }
+}