Skip to content

Feat/lei verification - #42

Merged
jhateley-godaddy merged 23 commits into
mainfrom
feat/lei-verification
Jul 15, 2026
Merged

jhateley-godaddy merged 23 commits into
mainfrom
feat/lei-verification

Conversation

@jhateley-godaddy

@jhateley-godaddy jhateley-godaddy commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Add lei (vLEI) identifier kind

Lets agents prove control via a vLEI credential chain. The noop default keeps the quickstart zero-infra; production swaps in the real vlei-verifier at the port boundary.

Enables the lei (vLEI / GLEIF ACDC) identifier kind as a fully-registered control verifier alongside did:web and did:key. Previously lei was recognized lexically but rejected with IDENTIFIER_KIND_UNSUPPORTED; it now registers and runs end-to-end.

Port & adapters

  • New outbound port port.LEIControlVerifier (Present / Authorization / VerifySignature) — lei is not a DID method, so it gets its own port rather than riding port.DIDResolver, following the DNS/DID precedent.
  • Two adapters: noop (quickstart — structural qb64 checks only, waives GLEIF authorization, AID↔LEI binding, and signature verification) and verifier (hardened HTTP client for an internal vlei-verifier service). Selected by vlei.type: noop | verifier.

Domain

  • VerifiedIdentity gains SubjectAID + PendingSubjectAID: the holder AID is derived from the presentation by the verifier and pinned on the aggregate — never caller-asserted (§3.6 pinning rule). Staging/promotion mirrors PendingValue, so an abandoned rotation never overwrites the proven signer.

Service

  • Register/Rotate take an additive RegisterOptions carrying the full-chain CESR presentation. A presentationRegistrar capability (discovered by type-assertion) runs inside the shared challenge path: submits the CESR, pins the derived subject AID, reconciles the credential LEI against the requested value, and returns an advisory presentation status (AUTHORIZED | PENDING). The race invariant is preserved — RegisterPresentation must not touch the conditional-persist guard columns (Status, Challenge.Nonce).
  • VerifyControl accepts a single cesrSignature proof (not a JWS array); the live Authorization re-check is the authoritative gate at verify time.

Storage

  • Migration 008_identity_subject_aid.sql adds subject_aid / pending_subject_aid. Store read/write paths updated; conditional-persist staging stays race-safe.

Config / wiring

  • New VLEI config block (type, base-url, present-timeout) with validation; noop logs a not-for-production warning.

HTTP / spec

  • vleiPresentation.cesr on register/rotate, presentationStatus on the 202, cesrSignature on verify-control, 1 MiB body cap. spec/api-spec-v2.yaml, spec/api-spec-tl-v2.yaml, and the docsui OpenAPI mirrors updated.

Demo

  • scripts/demo/vlei/ — end-to-end harness: KERIA + witness docker-compose, signify-ts build-chain/sign scripts, and a verify-control demo.

Also

  • Tidied stale comments referencing lei as "postponed".

@jhateley-godaddy
jhateley-godaddy force-pushed the feat/lei-verification branch 4 times, most recently from d3f3b21 to 20d1efd Compare June 17, 2026 04:34
@jhateley-godaddy
jhateley-godaddy marked this pull request as ready for review June 17, 2026 04:38
Copilot AI review requested due to automatic review settings June 17, 2026 04:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds end-to-end support for the lei (vLEI) identifier kind in the RA identity lifecycle, including register-time credential presentation, subject-AID pinning, and a CESR-signature verify-control proof backed by either a noop adapter or a real vlei-verifier service.

Changes:

  • Implement lei control verification (presentation + live authorization + CESR signature verification) with persistent subject AID pinning and updated sealing semantics.
  • Add configurable vLEI verifier selection (vlei.type: noop|verifier) plus a hardened HTTP adapter and extensive tests.
  • Update OpenAPI specs and add a self-contained local vLEI demo stack (docker-compose + scripts) to exercise the real verifier flow.

Reviewed changes

Copilot reviewed 43 out of 44 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
spec/api-spec-v2.yaml Updates RA v2 API spec for LEI presentation + CESR signature proof and new error codes.
spec/api-spec-tl-v2.yaml Updates TL spec to document LEI seal exception (AID + thumbprint).
scripts/demo/vlei/witness-config/main/wyz.json Adds witness demo config for wyz.
scripts/demo/vlei/witness-config/main/wub.json Adds witness demo config for wub.
scripts/demo/vlei/witness-config/main/wit.json Adds witness demo config for wit.
scripts/demo/vlei/witness-config/main/wil.json Adds witness demo config for wil.
scripts/demo/vlei/witness-config/main/wes.json Adds witness demo config for wes.
scripts/demo/vlei/witness-config/main/wan.json Adds witness demo config for wan.
scripts/demo/vlei/verify-control-demo.sh New end-to-end demo driving register-with-presentation + verify-control + link.
scripts/demo/vlei/up.sh Brings up the local vLEI ecosystem and waits for readiness.
scripts/demo/vlei/signify/scripts_ts/utils.ts SignifyTS helper utilities used by the demo chain-builder/signer.
scripts/demo/vlei/signify/scripts_ts/sign-proof.ts Standalone proof signer for LEI verify-control signingInput.
scripts/demo/vlei/signify/scripts_ts/build-chain.ts Headless synthetic vLEI trust-chain builder + root-of-trust registration/export.
scripts/demo/vlei/run-vlei.sh One-command orchestration of RA verifier mode + vLEI stack + full flow.
scripts/demo/vlei/README.md Documentation for the vLEI ecosystem and demo flow.
scripts/demo/vlei/keria-docker.json KERIA container config for demo witness bootstrapping.
scripts/demo/vlei/down.sh Teardown script for the vLEI demo stack.
scripts/demo/vlei/docker-compose.yml Compose stack (witnesses, schema server, KERIA, vlei-verifier, Deno runner).
scripts/demo/vlei/build-chain.sh Runs build-chain.ts inside the signify container and asserts outputs.
scripts/demo/start.sh Adds vlei: config wiring for the demo RA startup flow.
internal/ra/service/leiverifier.go Implements LEI verifier (presentation + live auth + signature verify + seal shape).
internal/ra/service/identitykinds.go Adds LEI proof submission fields, register options, and verifier registry wiring.
internal/ra/service/identity.go Threads register options through challenge flow and returns presentationStatus.
internal/ra/service/identity_test.go Updates fixtures and rejection tests for LEI now being enabled.
internal/ra/service/identity_lei_test.go Adds dedicated LEI lane tests (presentation pinning, failures, rotation, sealing).
internal/ra/handler/identity.go Extends request/response DTOs for vleiPresentation + cesrSignature + presentationStatus.
internal/ra/handler/identity_handler_test.go Adds body cap test and LEI HTTP round-trip test.
internal/port/leiverifier.go Introduces LEIControlVerifier port and related result/status types.
internal/domain/identity.go Adds subject AID fields + staging/promotion logic for LEI pinning.
internal/domain/identity_test.go Tests StageSubjectAID staging + promotion behavior.
internal/config/defaults.go Sets default vlei.type to noop.
internal/config/config.go Adds vlei config block + validation.
internal/config/config_test.go Adds config validation tests for vLEI verifier selection and URL rules.
internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql Adds subject_aid + pending_subject_aid columns.
internal/adapter/store/sqlite/identity.go Persists/loads subject AID fields and stages pending subject AID during challenge.
internal/adapter/store/sqlite/identity_test.go Adds store round-trip test for subject AID + pending staging behavior.
internal/adapter/leiverifier/verifier.go Adds hardened HTTP client for vlei-verifier (present/auth/verify) + CESR scanning helpers.
internal/adapter/leiverifier/noop.go Adds noop LEI verifier adapter that pins AID from CESR and waives external checks.
internal/adapter/leiverifier/leiverifier_test.go Unit tests for noop and HTTP verifier behavior (including path injection guards).
internal/adapter/docsui/openapi/tl.yaml Mirrors TL spec updates in docs UI bundle.
internal/adapter/docsui/openapi/ra.yaml Mirrors RA spec updates in docs UI bundle.
config/ra-local.yaml Adds local config knobs for vLEI verifier selection.
cmd/ans-ra/main.go Wires vLEI verifier selection into RA startup and logs mode.
.gitignore Ignores demo output directory for vLEI demo artifacts.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 43 out of 44 changed files in this pull request and generated 4 comments.

Comment thread internal/ra/handler/identity.go Resolved
Comment thread config/ra-local.yaml Resolved
Comment thread scripts/demo/vlei/README.md Resolved
Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
Replace the literal {"v":"ACDC marker in presentedCredentialSAID with a
regexp tolerating insignificant JSON whitespace around the brace, key,
and colon, so a pretty-printing serializer does not cause the leaf-SAID
scan to miss credential frames. Anchored on the version member being
first, which the KERI/ACDC serialization rules guarantee.

Trim the vlei demo README to remove three-way repetition while keeping
every script-verified fact, and tidy the demo scripts, docker-compose,
and start.sh vlei config comment. Ignore scripts/demo/vlei/signify/out/.

Signed-off-by: James Hateley <jhateley@godaddy.com>
The noop LEIControlVerifier required a bespoke base64url-JSON payload
({publicKey, lei}) while the real verifier consumes a full-chain
KERI/CESR export. Presenting the demo's real CESR to a noop-mode RA
therefore failed base64url decoding and returned 422
LEI_PRESENTATION_INVALID — diverging from the DNS and did:web noops,
which accept the same client payload as their real counterparts and
waive only the external-world binding.

The noop now consumes the same cesr/cesrSignature the verifier does: it
pins the real subject AID read from the presented leaf credential (a.i),
echoes the credential's LEI (a.LEI), and structurally accepts a
well-formed qb64 signature — waiving the GLEIF authorization, the live
AID↔LEI binding, and the cryptographic signature check (no KEL key-state
oracle in the quickstart), mirroring the noop DNS verifier.

The ACDC frame scan in verifier.go is refactored into a shared
scanACDCChain/leafFrame so the noop reads the leaf's a.i/a.LEI;
presentedCredentialSAID is preserved as a thin wrapper. No wire-contract
change — the OpenAPI cesr field already specifies the full-chain export.
Stale "runs real Ed25519 crypto"/"base64url JSON" docs updated.

Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
VerifyControlRequest declares a oneOf between signedProofs and
cesrSignature (spec/api-spec-v2.yaml): exactly one proof family per
request. The per-kind controlVerifiers each validate only their own
member, so a body carrying BOTH families slipped through silently —
the dispatched verifier read its member and ignored the other,
diverging from the spec and weakening client-side validation.

Add ProofSubmission.validateExactlyOneFamily(), called in
VerifyControl before kind dispatch, failing closed with
IDENTIFIER_PROOF_INVALID when both (or neither) family is set. The
gate is kind-independent, hence above the per-kind verifiers, which
keep their own empty-member checks as defensive backstops.

Also correct the lei noop-adapter docs/config: it performs structural
qb64 checks only and waives both the GLEIF authorization binding and
the cryptographic signature check (it does not run real Ed25519
crypto), and drop a stray debug log from the signify demo helper.

Signed-off-by: James Hateley <jhateley@godaddy.com>
The production vLEI verifier (internal/adapter/leiverifier) made three
outbound HTTP calls to the GLEIF vlei-verifier with zero observability:
every transport error, 5xx, oversized body, fail-closed decode, and
empty-subject-AID contract violation collapsed into one opaque
LEI_VERIFIER_UNAVAILABLE wire error, leaving an on-call engineer no way
to tell an internal outage from a 5xx from a malformed response.

Add a WithLogger option + logFailure helper mirroring the did:web
resolver's coarse-wire / detailed-log split: the wire error stays
deliberately coarse and never names the configured host (no
internal-topology leak), while the diagnosable category (op, reason,
status, underlying error) goes only to the server-side log at WARN.
Wire it through selectLEIVerifier in cmd/ans-ra, matching
selectDIDResolver.

The noop adapter (dev-only, never dials) and the service layer
(verification outcomes already surface as RFC 7807 to the caller) are
intentionally left uninstrumented, consistent with the rest of the
identity lane.

Signed-off-by: James Hateley <jhateley@godaddy.com>

@csnitker-godaddy csnitker-godaddy left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Two things to look at, both inline:

  1. Verifier.Authorization's 200 branch trusts the bare status — a contentless / lei-less success satisfies the verify-control gate and waives the AID↔LEI binding.
  2. register/rotate emit a 503 and several lei 422 codes their OpenAPI operations don't declare.

The security-critical paths (verify-time authz gate, subject-AID pinning, qb64 path guard, CESR parsing, the RegisterPresentation race invariant, the lei seal shape) look correct, and build/tests pass locally.

Non-blocking: the exactly-one-proof-family check uses value-emptiness vs the spec oneOf's key-presence (degenerate bodies only); and a few stale "postponed"/"will seal" lei comments remain (domain/identity.go, tl/event/identity/event.go, service/leiverifier.go:64).

return port.AuthorizationResult{}, err
}
switch status {
case http.StatusOK:

@csnitker-godaddy csnitker-godaddy Jun 22, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Authorization's 200 branch returns Authorized: true from the status code alone, and do's strict decode only runs when len(body) > 0 (line 311). So a 200 with an empty body or {} yields {Authorized: true, LEI: ""} — which passes the verify-control gate and skips the AID↔LEI reconcile (empty LEI reads as the noop waiver). That's the degradation lines 304–309 say to fail closed on, but the guard only catches malformed JSON. Present already guards its empty-AID case (line 175); this branch doesn't.

case http.StatusOK:
    if auth.LEI == "" {
        v.logFailure("authorize", "verifier 200 carried no LEI (failing closed)", status, nil)
        return port.AuthorizationResult{}, v.unavailable("authorize")
    }
    return port.AuthorizationResult{Authorized: true, LEI: auth.LEI}, nil

@jhateley-godaddy jhateley-godaddy Jun 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

good catch, updated

Comment thread spec/api-spec-v2.yaml
their verifiers ship) returns 422
`IDENTIFIER_KIND_UNSUPPORTED`. The `lei` kind additionally
requires a `vleiPresentation` at register time; omitting it
returns 422 `IDENTIFIER_PRESENTATION_REQUIRED`.

@csnitker-godaddy csnitker-godaddy Jun 22, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

register and rotate run the verifier synchronously (service/leiverifier.go:50), so both can return 503 LEI_VERIFIER_UNAVAILABLE and the 422 codes LEI_PRESENTATION_INVALID, LEI_MISMATCH, LEI_SUBJECT_AID_INVALID — none of which are declared on these operations (the 503 is new; did:web only ever 422'd). IDENTIFIER_PRESENTATION_REQUIRED is documented here on register but not on the rotate PUT, which also returns it.

Add a 503 to both operations, list the three LEI_* 422 codes, and add IDENTIFIER_PRESENTATION_REQUIRED to rotate. Mirror into ra.yaml.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

updated

The Authorization 200 branch returned {Authorized: true, LEI: auth.LEI}
from the status code alone, and do's strict decode only ran for a
non-empty body. A 200 with an empty body or {} therefore yielded
{Authorized: true, LEI: ""}, which passes the verify-control gate and
skips the AID->LEI reconcile because an empty LEI reads downstream as
the noop waiver of the binding -- silently degrading the production
verifier to noop semantics. The decode guard only caught malformed JSON.

Add a symmetric empty-LEI guard in the 200 branch, mirroring Present's
empty-AID guard: log server-side and return the coarse unavailable
error. Cover it with 200-without-LEI cases (empty body, {}, {"lei":""}).

Signed-off-by: James Hateley <jhateley@godaddy.com>
register and rotate run the kind's verifier synchronously inside the
shared challenge path, so both surface verifier failures the spec did
not declare:

- did:web Challenges resolves the DID at register/rotate and propagates
  DID_RESOLUTION_FAILED / DID_DOCUMENT_ID_MISMATCH as 422.
- lei RegisterPresentation runs the vlei-verifier, returning the 422
  codes IDENTIFIER_PRESENTATION_REQUIRED, LEI_PRESENTATION_INVALID,
  LEI_MISMATCH, LEI_SUBJECT_AID_INVALID and a new 503
  LEI_VERIFIER_UNAVAILABLE.

Enumerate all of these on both operations (matching the verify-control
style), add the 503, and add IDENTIFIER_PRESENTATION_REQUIRED to rotate.
Mirrored into the docsui ra.yaml copy.

Signed-off-by: James Hateley <jhateley@godaddy.com>
…check

lei now ships behind the LEIControlVerifier port, so the 'postponed'/
'will seal' wording in domain/identity.go and tl/event/identity/event.go
is stale; reword to describe the live behavior.

Also document that validateExactlyOneFamily intentionally tests value-
presence rather than the spec oneOf's literal key-presence: the plain
[]string/string DTO and submission types collapse absent, null, and
empty to the same zero value, and value-presence is the stricter guard.

Signed-off-by: James Hateley <jhateley@godaddy.com>
@jhateley-godaddy

Copy link
Copy Markdown
Contributor Author
Non-blocking: the exactly-one-proof-family check uses value-emptiness vs the spec oneOf's key-presence (degenerate bodies only); and a few stale "postponed"/"will seal" lei comments remain (domain/identity.go, tl/event/identity/event.go, service/leiverifier.go:64).

Fixed the remaining stale comments and updated the comments around exactly-one-proof-family check.

@kperry-godaddy kperry-godaddy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ran a multi-perspective review pass (security / architecture / Go / systems / skeptic) against b4a59a9.

Credit first, because it's earned: the three headline claims in the description all check out in code. The §3.6 pinning rule holds (the subject AID is never caller-asserted anywhere), the live Authorization re-check really is the authoritative gate at verify time, and the RegisterPresentation race invariant is honored by the current implementation — I traced the register/rotate/verify/revoke interleavings and the conditional persist brackets them correctly. The adapter hardening (fail-closed 2xx decode, qb64 path guards, response-size caps, wire/log split) is genuinely well built, and go build / tests / golangci-lint are all clean at head.

Five items rose to must-fix in my pass — each inline comment below carries the evidence and a concrete fix. The common thread: the code is careful, but a few things around it (the default trust posture, a comment-enforced invariant, migration numbering, and the outbound wire contract) need the same rigor before this takes real traffic. None require architectural rework; two are minutes of work, and one (#3) is only fixable before merge.

Comment thread internal/config/defaults.go Outdated
LinkRateLimit: 60,
SealTimeout: 5 * time.Second,
},
VLEI: VLEI{Type: "noop"},

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[HIGH] Fail-open default: this line silently flips lei from hard-off to enabled with the checks waived.

Before this PR, lei was rejected everywhere with IDENTIFIER_KIND_UNSUPPORTED. With this default, any deployment that upgrades without adding a vlei: block starts serving live lei registrations through the noop adapter — Authorization returns Authorized: true for any well-formed qb64 AID, and VerifySignature is isQB64(subjectAID) && isQB64(signature) (noop.go:85, :94). The resulting IDENTITY_VERIFIED events seal into the append-only TL with the same lei-vlei-acdc proof method as real verifications, so there is no after-the-fact way to tell them apart — and validateVLEI has no "off" value, so an operator without vlei-verifier infrastructure can't restore the pre-PR posture at all. The startup WARN is a good instinct, but it's one line that scrolls out of log retention while a misconfigured instance runs for months.

One more wrinkle worth naming: this noop is materially weaker than its siblings. The did:web noop resolver still genuinely verifies JWS signatures ("signature verification still genuinely runs, only the live-document binding is waived", config.go:166-170); this one waives signature verification entirely. An operator who internalized the existing noop contract will mis-model this one.

Suggestion — make off the default and keep noop as an explicit quickstart choice (ra-local.yaml already sets it explicitly, so the zero-infra quickstart is unaffected):

// defaults.go
VLEI: VLEI{Type: "off"},

// config.go validateVLEI
case "off", "noop":

// main.go selectLEIVerifier
case "noop":
    return leiverifier.NewNoop()
default: // "off"
    return nil

// identitykinds.go newControlVerifiers — register lei only when configured
if leiCtl != nil {
    m[domain.KindLEI] = &leiVerifier{v: leiCtl} // absent → IDENTIFIER_KIND_UNSUPPORTED, the pre-PR posture
}

If you'd rather keep noop-by-default for parity with dns.type/identity.resolver, two cheaper hardenings that still close most of the gap: reject the contradictory base-url-set-with-type: noop combo in validateVLEI (mirroring the existing acme + dns.noop rejection at config.go:427-430), and seal a distinguishable proof-method token in noop mode so noop-era seals are auditable later. This was the strongest consensus finding of the review pass (7 of 15 reviewers), so at minimum it deserves a deliberate decision on the record.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Suggestion committed. Vlei configuration now defaults to 'off' and endpoints return IDENTIFIER_KIND_UNSUPPORTED.

Comment thread internal/ra/service/identitykinds.go Outdated
// "PENDING") for the 202 body. It MUST NOT mutate the aggregate's
// Status or Challenge.Nonce (the conditional-persist guard columns —
// see the RACE INVARIANT on the interface doc).
RegisterPresentation(ctx context.Context, identity *domain.VerifiedIdentity, opts RegisterOptions, now time.Time) (port.PresentationStatus, error)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[HIGH] The RACE INVARIANT above is load-bearing, but nothing enforces it — and the doc it cites doesn't exist.

This doc comment is excellent, and the current lei implementation honors it (verified: StageSubjectAID touches only PendingSubjectAID + UpdatedAt). Three gaps, though, all about the next implementer — and this file already names did:ethr / did:plc as candidates:

  1. The capability receives the full mutable *domain.VerifiedIdentity, so the type system permits exactly the mutation the contract forbids.
  2. docs/identity-challenge-race.md (referenced a few lines up) isn't in the repo — the invariant's authority is a dangling pointer.
  3. No test pins it: the only mention of RegisterPresentation in the test files is a comment. A violation would surface as a probabilistic, production-only race that CI can't catch.

The cheapest structural improvement lives in identity.go challenge(): hoist the snapshot capture above the capability call, so a mutating plugin can never be absorbed into the snapshot (it would surface as a store conflict instead — fail-closed):

// Load-time snapshot for the conditional persist — captured BEFORE the
// presentation call so a plugin mutation of the guard columns can never
// be absorbed into the snapshot.
expectedStatus := identity.Status
expectedNonce := ""
if identity.Challenge != nil {
    expectedNonce = identity.Challenge.Nonce
}

var presentationStatus port.PresentationStatus
if pr, ok := verifier.(presentationRegistrar); ok {
    presentationStatus, err = pr.RegisterPresentation(ctx, identity, opt, now)
    if err != nil {
        return nil, err
    }
}

Alongside that: a pinning test (run challenge() with a fake registrar and assert Status/Challenge.Nonce are unchanged across the call), and either write the referenced doc or repoint the comment at the StageChallenge doc block in the sqlite store, where the guard semantics actually live.

Longer term — and fine as a follow-up — consider narrowing the capability to return derived facts instead of mutating the aggregate: RegisterPresentation(ctx, effectiveValue string, opts RegisterOptions) (subjectAID string, status port.PresentationStatus, err error), with challenge() calling identity.StageSubjectAID itself. The invariant then holds by construction and the comment becomes documentation instead of a guardrail.

@jhateley-godaddy jhateley-godaddy Jul 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Narrowed the presentationRegistrar capability so it returns the verifier-derived subject AID and advisory status rather than receiving the mutable *domain.VerifiedIdentity. challenge() now stages the AID itself via StageSubjectAID (touching only PendingSubjectAID + UpdatedAt), so the conditional-persist guard columns (Status, Challenge.Nonce) are unreachable from a presentation kind by construction — the race safety no longer rests on plugin discipline.

Repointed the interface doc at the StageChallenge doc block in the sqlite
store, where the guard semantics live.

@@ -0,0 +1,19 @@
-- lei (vLEI) subject AID pinning.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[HIGH] Numbering collision: main already owns 008_certificate_orders.sql (plus 009 and 010), so this file creates a duplicate 008_ prefix — and it's only fixable before merge.

Nothing breaks today: the runner keys schema_migrations on the full filename and both fresh and upgraded databases converge on the right schema (verified). But it breaks the runner's own documented contract ("the filename prefix (NNN_) determines ordering", sqlite.go:83-84), fresh vs. already-upgraded databases now apply this file in different positions relative to 009/010, the next author's "take the next number" heuristic is ambiguous, and any future move to version-keyed migration tooling (golang-migrate, goose) hard-errors on a duplicate version.

The trap is the fix window: once any environment records this filename in schema_migrations, a rename re-applies the ALTERs under the new name and fails startup with duplicate column name: subject_aid. So:

git mv internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql \
       internal/adapter/store/sqlite/migrations/011_identity_subject_aid.sql

(The branch history shows this got renamed 008 → 009 → 008 across rebases while main's numbers moved underneath it — a one-line CI check for unique NNN_ prefixes would stop this class recurring.)

For the record, the migration content itself is exactly right: nullable, no default, additive, instant per SQLite's ALTER TABLE rules, and rollback-safe against an old binary. Just the number.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

fixed

if !ok {
return
}
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB — matches registration.go

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[HIGH] This cap pass covers three of the file's four JSON routes — Link (line ~293) still decodes an unbounded body.

Nice hardening on Register/Rotate/VerifyControl. Link, in the same file, still does a bare json.NewDecoder(r.Body).Decode(&req) into linkRequest{AgentIDs []string}: there's no global body-size middleware (the router wires Recoverer/RequestID/Timeout/AllowContentType/auth only), and the service's maxLinkBatch = 256 check runs only after the full array is materialized. An authenticated caller streaming a large JSON array inside the 30s timeout is a memory-exhaustion vector — and since this PR is the hardening pass for this file, it's worth finishing the sweep here:

func (h *IdentityHandler) Link(w http.ResponseWriter, r *http.Request) {
    providerID, ok := callerSubject(w, r)
    if !ok {
        return
    }
    r.Body = http.MaxBytesReader(w, r.Body, 32<<10) // 32 KiB — maxLinkBatch (256) UUIDs fit well under this
    var req linkRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {

Related and non-blocking, while you're in this file: when these 1 MiB caps trip, *http.MaxBytesError currently surfaces as 422 "request body is not valid JSON" — factually wrong for a too-large-but-valid body, and lei is the first kind where a legitimate >1 MiB payload (a full-chain CESR export) is plausible. The TL handler already has the right pattern (errors.As(err, &maxErr) → 413 with the limit, tl/handler/handler.go:206-216); copying it here would spare a future support ticket where a registrant's valid JSON is called invalid.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I have added r.Body = http.MaxBytesReader(w, r.Body, 32<<10) before decoding in a new commit. I started down the path of returning 413 with application/problem+json formatted error response, but soon realized to keep the API consistent I would need to touch about 12 other sites and some are not related to this PR. I do think it is a worthwhile change and should be done in a separate PR.


func (s *vleiServer) handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/presentations/", func(w http.ResponseWriter, _ *http.Request) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[HIGH] Every handler in this stand-in discards the request — the wire contract with the real vlei-verifier is unpinned.

The response-side coverage in this suite is genuinely strong (the fail-closed decode, body-cap, and log-split tests are exactly what I'd want to see). What's missing is the other direction: nothing asserts what the adapter sends — the PUT /presentations/{said} path composition, the application/json+cesr content type, the body, or the signer_aid / signature / non_prefixed_digest field names on POST /signature/verify. A typo in any of those passes the entire suite green and fails every production call.

That matters more than usual here because the counterparty is an unpublished 0.x service built from a mutable git tag (docker-compose.yml:136), and the only end-to-end validation is the manual demo harness, which no CI runs. These request assertions are the only automated safety net available for the contract.

Suggested shape — record requests in the stand-in, assert once:

type vleiServer struct {
    // ... existing fields ...
    mu       sync.Mutex
    requests []recordedRequest // method, path, contentType, body
}

func (s *vleiServer) record(r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    s.mu.Lock()
    defer s.mu.Unlock()
    s.requests = append(s.requests, recordedRequest{
        method: r.Method, path: r.URL.Path,
        contentType: r.Header.Get("Content-Type"), body: string(body),
    })
}

then one test asserting: PUT /presentations/ECredSAID123 with body == validCESR and the CESR content type; GET /authorizations/EHolderAID; and exactly the three snake_case keys on POST /signature/verify.

Two smaller asks in the same vein: SHA-pin the compose build context (git tags are mutable, and up.sh --build re-resolves the ref on every run — a moved tag silently changes what every developer builds), and consider recorded contract fixtures captured from the real 0.1.5 service as a CI-runnable stand-in for the harness, so the adapter's contract survives upstream drift with a loud failure instead of a quiet one.

@jhateley-godaddy jhateley-godaddy Jul 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for flagging, there was a real gap here.
Fixed in 5fdc719. Added TestVerifierRequestShapes (leiverifier_test.go:253), which records every outbound request from the httptest handler and asserts the send direction end-to-end:

  • PUT /presentations/{said} — path composed from the leaf SAID in the CESR chain (/presentations/ECredSAID123), Content-Type: application/json+cesr, and the CESR export echoed byte-for-byte in the body
  • GET /authorizations/{aid} — path built from the subject AID returned by the present call, no body.
  • POST /signature/verify — Content-Type: application/json, body decoded into map[string]any and asserted to carry exactly the three snake_case tags signer_aid / signature / non_prefixed_digest bound to the right values, plus a strict field-count check. Decoding on the wire tags means a struct-tag typo (signerAid, nonPrefixedDigest, …) leaves the expected key absent and fails the test.

So a typo in any path, content type, or field name now fails the suite instead of passing green. (The same commit also swapped the hand-written response bodies for recorded 0.1.5 fixtures, so the response side is checked against the real contract too.)

I also updated docker-compose.yaml to use the commit hash. The fixtures are generated from that artifact.
While this does not guard against drift from upstream changes in vlei-verifier versions, it does verify the code works against that version.

…ing aggregate

Narrow the presentationRegistrar capability so it returns the
verifier-derived subject AID and advisory status rather than receiving
the mutable *domain.VerifiedIdentity. challenge() now stages the AID
itself via StageSubjectAID (touching only PendingSubjectAID +
UpdatedAt), so the conditional-persist guard columns (Status,
Challenge.Nonce) are unreachable from a presentation kind by
construction — the race safety no longer rests on plugin discipline.

Repoint the interface doc at the StageChallenge doc block in the sqlite
store, where the guard semantics live.

Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
Signed-off-by: James Hateley <jhateley@godaddy.com>
@jhateley-godaddy
jhateley-godaddy added this pull request to the merge queue Jul 15, 2026
Merged via the queue into main with commit deea171 Jul 15, 2026
2 checks passed
@jhateley-godaddy
jhateley-godaddy deleted the feat/lei-verification branch July 15, 2026 01:39
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.

4 participants