From aa614b085bf067e3254e47f420bc562818b863ee Mon Sep 17 00:00:00 2001 From: James Hateley Date: Thu, 11 Jun 2026 17:39:54 +1000 Subject: [PATCH 01/21] feat: lei verification Signed-off-by: James Hateley --- cmd/ans-ra/main.go | 27 +- config/ra-local.yaml | 21 + internal/adapter/docsui/openapi/ra.yaml | 77 +- internal/adapter/docsui/openapi/tl.yaml | 27 +- .../adapter/leiverifier/leiverifier_test.go | 358 ++++++ internal/adapter/leiverifier/noop.go | 138 +++ internal/adapter/leiverifier/verifier.go | 447 +++++++ internal/adapter/store/sqlite/identity.go | 13 +- .../migrations/008_identity_subject_aid.sql | 13 + internal/config/config.go | 46 + internal/config/config_test.go | 50 + internal/config/defaults.go | 1 + internal/domain/identity.go | 19 + internal/domain/identity_test.go | 26 + internal/port/leiverifier.go | 66 ++ internal/ra/handler/identity.go | 62 +- internal/ra/handler/identity_handler_test.go | 3 + internal/ra/service/identity.go | 62 +- internal/ra/service/identity_lei_test.go | 226 ++++ internal/ra/service/identity_test.go | 19 +- internal/ra/service/identitykinds.go | 48 +- internal/ra/service/leiverifier.go | 164 +++ scripts/demo/start.sh | 13 + scripts/demo/vlei/README.md | 262 +++++ scripts/demo/vlei/build-chain.sh | 54 + scripts/demo/vlei/docker-compose.yml | 206 ++++ scripts/demo/vlei/down.sh | 32 + scripts/demo/vlei/keria-docker.json | 15 + scripts/demo/vlei/run-vlei.sh | 80 ++ .../vlei/signify/out/ecr-presentation.json | 5 + .../demo/vlei/signify/out/tier1-outputs.json | 8 + .../vlei/signify/scripts_ts/build-chain.ts | 459 ++++++++ .../vlei/signify/scripts_ts/sign-proof.ts | 62 + scripts/demo/vlei/signify/scripts_ts/utils.ts | 1045 +++++++++++++++++ scripts/demo/vlei/up.sh | 74 ++ scripts/demo/vlei/verify-control-demo.sh | 259 ++++ .../demo/vlei/witness-config/main/wan.json | 8 + .../demo/vlei/witness-config/main/wes.json | 8 + .../demo/vlei/witness-config/main/wil.json | 8 + .../demo/vlei/witness-config/main/wit.json | 8 + .../demo/vlei/witness-config/main/wub.json | 8 + .../demo/vlei/witness-config/main/wyz.json | 8 + spec/api-spec-tl-v2.yaml | 27 +- spec/api-spec-v2.yaml | 77 +- 44 files changed, 4554 insertions(+), 85 deletions(-) create mode 100644 internal/adapter/leiverifier/leiverifier_test.go create mode 100644 internal/adapter/leiverifier/noop.go create mode 100644 internal/adapter/leiverifier/verifier.go create mode 100644 internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql create mode 100644 internal/port/leiverifier.go create mode 100644 internal/ra/service/identity_lei_test.go create mode 100644 internal/ra/service/leiverifier.go create mode 100644 scripts/demo/vlei/README.md create mode 100755 scripts/demo/vlei/build-chain.sh create mode 100644 scripts/demo/vlei/docker-compose.yml create mode 100755 scripts/demo/vlei/down.sh create mode 100755 scripts/demo/vlei/keria-docker.json create mode 100755 scripts/demo/vlei/run-vlei.sh create mode 100644 scripts/demo/vlei/signify/out/ecr-presentation.json create mode 100644 scripts/demo/vlei/signify/out/tier1-outputs.json create mode 100644 scripts/demo/vlei/signify/scripts_ts/build-chain.ts create mode 100644 scripts/demo/vlei/signify/scripts_ts/sign-proof.ts create mode 100644 scripts/demo/vlei/signify/scripts_ts/utils.ts create mode 100755 scripts/demo/vlei/up.sh create mode 100755 scripts/demo/vlei/verify-control-demo.sh create mode 100755 scripts/demo/vlei/witness-config/main/wan.json create mode 100755 scripts/demo/vlei/witness-config/main/wes.json create mode 100755 scripts/demo/vlei/witness-config/main/wil.json create mode 100755 scripts/demo/vlei/witness-config/main/wit.json create mode 100755 scripts/demo/vlei/witness-config/main/wub.json create mode 100755 scripts/demo/vlei/witness-config/main/wyz.json diff --git a/cmd/ans-ra/main.go b/cmd/ans-ra/main.go index 492f2d0..0b74a13 100644 --- a/cmd/ans-ra/main.go +++ b/cmd/ans-ra/main.go @@ -33,6 +33,7 @@ import ( "github.com/godaddy/ans/internal/adapter/docsui" "github.com/godaddy/ans/internal/adapter/eventbus" "github.com/godaddy/ans/internal/adapter/keymanager" + "github.com/godaddy/ans/internal/adapter/leiverifier" "github.com/godaddy/ans/internal/adapter/store/sqlite" "github.com/godaddy/ans/internal/adapter/tlclient" "github.com/godaddy/ans/internal/config" @@ -153,8 +154,13 @@ func run(cfgPath string) error { // did:web resolver — noop (quickstart) or hardened web fetch, // the identity surface's analog of the DNS verifier selection. didResolver := selectDIDResolver(cfg, logger) + // vLEI control verifier — noop (quickstart) or HTTP client for an internal vlei-verifier, + // the lei kind's analog of + // the did:web resolver selection. + leiVerifier := selectLEIVerifier(cfg) logger.Info(). Str("resolver", cfg.Identity.Resolver.Type). + Str("vleiVerifier", cfg.VLEI.Type). Dur("challengeTTL", cfg.Identity.ChallengeTTL). Msg("verified-identity surface configured") @@ -198,7 +204,7 @@ func run(cfgPath string) error { logger.Warn().Msg("TL client disabled — identity verify/revoke/link operations will fail with TL_UNAVAILABLE (seal-before-success)") } identitySvc := service.NewIdentityService( - identityStore, identityLinks, agents, didResolver, identitySealer, db, + identityStore, identityLinks, agents, didResolver, identitySealer, leiVerifier, db, ).WithSigner(service.EventSigner{ KeyManager: km, KeyID: signerKeyID, @@ -515,3 +521,22 @@ func selectDIDResolver(cfg *config.RAConfig, logger zerolog.Logger) port.DIDReso return didresolver.NewNoopResolver() } } + +// selectLEIVerifier returns the configured vLEI control verifier — the +// lei kind's analog of selectDIDResolver. "verifier" is the hardened +// HTTP client for an internal vlei-verifier (config-validated base +// URL); the default "noop" runs real Ed25519 crypto over the signing +// input but waives the GLEIF authorization binding, for self-contained +// local development. +func selectLEIVerifier(cfg *config.RAConfig) port.LEIControlVerifier { + switch cfg.VLEI.Type { + case "verifier": + var opts []leiverifier.VerifierOption + if cfg.VLEI.PresentTimeout > 0 { + opts = append(opts, leiverifier.WithTimeout(cfg.VLEI.PresentTimeout)) + } + return leiverifier.NewVerifier(cfg.VLEI.BaseURL, opts...) + default: + return leiverifier.NewNoop() + } +} diff --git a/config/ra-local.yaml b/config/ra-local.yaml index a9257fc..897c99e 100644 --- a/config/ra-local.yaml +++ b/config/ra-local.yaml @@ -77,6 +77,27 @@ identity: # minute (each can trigger an outbound did:web fetch). register-rate-limit: 10 +vlei: + # The lei (vLEI) control verifier behind the `lei` identifier kind, + # mirroring the DNS verifier's and did:web resolver's noop/real split: + # "noop" — no I/O; runs REAL Ed25519 crypto over the served + # signingInput, but waives the GLEIF/vlei-verifier + # authorization binding (anyone can present any LEI). + # Zero-infra quickstart only — NOT for production. + # "verifier" — a hardened HTTP client for an internal GLEIF + # vlei-verifier (present / authorize / verify). The RA + # never parses KERI key state itself; the verifier is + # the authoritative key-state oracle. REQUIRED for the + # real end-to-end flow that scripts/demo/vlei/up.sh + # brings up (keria, vlei-server, vlei-verifier, + # witnesses, signify). + type: noop + # base-url: required when type is "verifier" — the internal + # vlei-verifier service URL. + # base-url: "http://localhost:7676" + # present-timeout bounds each verifier HTTP request (default 5s). + # present-timeout: 5s + keys: type: file file: diff --git a/internal/adapter/docsui/openapi/ra.yaml b/internal/adapter/docsui/openapi/ra.yaml index 5b17e4e..90d48a2 100644 --- a/internal/adapter/docsui/openapi/ra.yaml +++ b/internal/adapter/docsui/openapi/ra.yaml @@ -927,9 +927,12 @@ paths: is the idempotent re-add: the same `identityId` returns with a fresh nonce (the prior nonce is superseded). A value already verified — by this owner or any other — returns 409 - `IDENTIFIER_DUPLICATE`. Kinds without an enabled control - verifier (`lei`, postponed) return 422 - `IDENTIFIER_KIND_UNSUPPORTED`. + `IDENTIFIER_DUPLICATE`. A recognized value whose kind has no + enabled control verifier (e.g. `did:plc`, `did:ion`, until + 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`. operationId: registerIdentity requestBody: required: true @@ -2056,16 +2059,38 @@ components: description: | Registers (POST) or rotates (PUT) an identifier. The kind is inferred from the value's lexical form — `did:web:` prefix, - `did:key:` prefix, or a 20-character LEI (recognized but - postponed) — never caller-asserted. + `did:key:` prefix, or a 20-character LEI — never + caller-asserted. properties: value: type: string description: The identifier to prove control of example: did:web:identity.acme-corp.com + vleiPresentation: + $ref: '#/components/schemas/VLEIPresentation' required: - value + VLEIPresentation: + type: object + description: | + The lei (vLEI) register-time credential presentation. REQUIRED + for the `lei` kind and omitted for the JWS kinds (`did:web`, + `did:key`). The RA submits the CESR to its configured + vlei-verifier, which derives and pins the subject AID; the + 202's `presentationStatus` reports the verifier's advisory + authorization decision. + properties: + cesr: + type: string + description: | + The full-chain CESR export of the vLEI credential and its + supporting KELs/ACDCs (the `credentials().get(said, true)` + shape). The RA never parses KERI key state itself — the + verifier is the authoritative key-state oracle. + required: + - cesr + IdentityChallengeResponse: type: object description: | @@ -2086,6 +2111,15 @@ components: description: The canonical identifier this round proves status: $ref: '#/components/schemas/IdentityLifecycleStatus' + presentationStatus: + type: string + description: | + The lei register-time advisory authorization status from + the vlei-verifier (`AUTHORIZED` | `PENDING`). Omitted for + kinds with no register-time presentation (`did:web`, + `did:key`). Advisory only — control is finally established + by a LIVE re-authorization at verify-control. + enum: ['AUTHORIZED', 'PENDING'] nonce: type: string description: Base64url 32-byte single-use anti-replay nonce @@ -2128,11 +2162,20 @@ components: VerifyControlRequest: type: object description: | - One compact JWS per proven key. Supported algorithms match - what the verifier implements: EdDSA (Ed25519), ES256 - (ECDSA P-256), and RS256 (RSA >= 2048). Key-agreement keys - (X25519) and curves without a verifier (secp256k1, - P-384/521) are rejected with a precise error. + The control proof. Its members are additive per identifier + kind, and EXACTLY ONE family is set per request: + + - JWS kinds (`did:web`, `did:key`) submit `signedProofs` — + one compact JWS per proven key. + - The `lei` kind submits `cesrSignature` — a single CESR + signature over the served signingInput by the subject + AID's current key. + + Supported JWS algorithms match what the verifier implements: + EdDSA (Ed25519), ES256 (ECDSA P-256), and RS256 (RSA >= + 2048). Key-agreement keys (X25519) and curves without a + verifier (secp256k1, P-384/521) are rejected with a precise + error. properties: signedProofs: type: array @@ -2146,8 +2189,18 @@ components: and MAY carry `jwk` (the signer's public key — required by the quickstart noop resolver, ignored by the web resolver, which always uses the resolved document). - required: - - signedProofs + cesrSignature: + type: string + description: | + The lei proof: a single CESR signature over the served + signingInput by the subject AID's current key. Set only + for the `lei` kind. The RA forwards it to the + vlei-verifier, which resolves the AID's key state from its + KEL and checks the signature over the exact signingInput + bytes (the same payload the JWS kinds sign). + oneOf: + - required: [signedProofs] + - required: [cesrSignature] IdentityLifecycleStatus: type: string diff --git a/internal/adapter/docsui/openapi/tl.yaml b/internal/adapter/docsui/openapi/tl.yaml index 4664a78..78cdcf7 100644 --- a/internal/adapter/docsui/openapi/tl.yaml +++ b/internal/adapter/docsui/openapi/tl.yaml @@ -1203,17 +1203,25 @@ components: conveniences (anyone can derive RFC 7638 from the sealed source) and are never part of the sealed contract. - The postponed `lei` kind is the one deliberate exception: - it will seal the subject AID + a key thumbprint only — there - is no document to quote, the ACDC is PII, and KERI's KEL is - already the authoritative key history. Seal verbatim what - has no other tamper-evident home; commit minimally where one - exists. + The `lei` kind is the one deliberate exception: it seals the + subject AID + a key thumbprint only (`{id: , type: + "vLEI-KERI-AID", thumbprint: base64url(SHA-256(AID))}`) — + there is no document to quote, the ACDC is PII, and KERI's + KEL is already the authoritative key history. Seal verbatim + what has no other tamper-evident home; commit minimally where + one exists. A `lei` seal is therefore NOT offline + re-verifiable from the seal alone: the KEL-backed key state + lives at the vlei-verifier (the documented lei trust + boundary), whereas a JWS seal carries the key material and so + the sealed proof re-verifies offline. required: [verificationMethod, signedProof] properties: verificationMethod: type: object - description: The DID document's verification-method object, verbatim + description: | + For JWS kinds, the DID document's verification-method + object, verbatim. For `lei`, the synthesized subject-AID + object (`id`, `type: vLEI-KERI-AID`, `thumbprint`). example: id: did:web:identity.acme-corp.com#key-1 type: JsonWebKey2020 @@ -1221,7 +1229,10 @@ components: publicKeyJwk: { kty: OKP, crv: Ed25519, x: "0-e2i2_..." } signedProof: type: string - description: The compact JWS over the served IdentityProofInput + description: | + The proof over the served IdentityProofInput — a compact + JWS for the JWS kinds, or the CESR signature by the + subject AID's current key for `lei`. LinkedIdentityView: type: object diff --git a/internal/adapter/leiverifier/leiverifier_test.go b/internal/adapter/leiverifier/leiverifier_test.go new file mode 100644 index 0000000..23b4a9d --- /dev/null +++ b/internal/adapter/leiverifier/leiverifier_test.go @@ -0,0 +1,358 @@ +package leiverifier + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/godaddy/ans/internal/domain" +) + +// b64 is the unpadded base64url encoding the noop wire shape uses. +func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) } + +// noopFixture mints an Ed25519 keypair and the matching noop +// presentation cesr + subject AID for the public key. +func noopFixture(t *testing.T, lei string) (ed25519.PrivateKey, string, string) { + t.Helper() + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + aid := b64(pub) + raw, err := json.Marshal(noopPresentation{PublicKey: aid, LEI: lei}) + if err != nil { + t.Fatal(err) + } + return priv, aid, b64(raw) +} + +func TestNoopPresentAndVerify(t *testing.T) { + ctx := context.Background() + n := NewNoop() + priv, aid, cesr := noopFixture(t, "5493001KJTIIGC8Y1R17") + + // Present recovers the AID + echoes the LEI + always AUTHORIZED. + res, err := n.Present(ctx, cesr) + if err != nil { + t.Fatalf("Present: %v", err) + } + if res.SubjectAID != aid || res.LEI != "5493001KJTIIGC8Y1R17" || res.Status != "AUTHORIZED" { + t.Fatalf("present result: %+v", res) + } + + // Authorization authorizes a well-formed AID, asserts no LEI binding. + auth, err := n.Authorization(ctx, aid) + if err != nil { + t.Fatalf("Authorization: %v", err) + } + if !auth.Authorized || auth.LEI != "" { + t.Fatalf("authorization: %+v", auth) + } + + // VerifySignature: a real Ed25519 signature over the signing input. + const signingInput = "the-served-signing-input" + sig := ed25519.Sign(priv, []byte(signingInput)) + ok, err := n.VerifySignature(ctx, aid, signingInput, b64(sig)) + if err != nil || !ok { + t.Fatalf("verify good sig: ok=%v err=%v", ok, err) + } + // Tampered payload does not verify. + if ok, _ := n.VerifySignature(ctx, aid, "other-input", b64(sig)); ok { + t.Fatal("tampered payload should not verify") + } +} + +func TestNoopPresentFailures(t *testing.T) { + ctx := context.Background() + n := NewNoop() + _, validAID, _ := noopFixture(t, "X") + + noLEI, _ := json.Marshal(noopPresentation{PublicKey: validAID}) + badPub, _ := json.Marshal(noopPresentation{PublicKey: "not-base64url-key", LEI: "X"}) + + cases := []struct { + name string + cesr string + }{ + {"not base64url", "!!!not-base64!!!"}, + {"not a json object", b64([]byte("not json"))}, + {"bad public key", b64(badPub)}, + {"missing lei", b64(noLEI)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if _, err := n.Present(ctx, tc.cesr); !isCode(err, "LEI_PRESENTATION_INVALID") { + t.Fatalf("want LEI_PRESENTATION_INVALID, got %v", err) + } + }) + } + + // A malformed AID to Authorization is an error (not a silent allow). + if _, err := n.Authorization(ctx, "bogus-aid"); err == nil { + t.Fatal("malformed AID should error") + } + + // VerifySignature treats malformed AID / signature as a non-verifying + // false, never an I/O error. + if ok, err := n.VerifySignature(ctx, "bogus-aid", "in", b64([]byte("sig"))); ok || err != nil { + t.Fatalf("bad aid: ok=%v err=%v", ok, err) + } + if ok, err := n.VerifySignature(ctx, validAID, "in", "!!!"); ok || err != nil { + t.Fatalf("bad sig encoding: ok=%v err=%v", ok, err) + } + if ok, err := n.VerifySignature(ctx, validAID, "in", b64([]byte("too-short"))); ok || err != nil { + t.Fatalf("wrong-length sig: ok=%v err=%v", ok, err) + } +} + +// vleiServer is a programmable stand-in for the vlei-verifier service. +type vleiServer struct { + presentStatus int + presentBody string + authStatus int + authBody string + verifyStatus int +} + +func (s *vleiServer) handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("/presentations/", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(s.presentStatus) + _, _ = w.Write([]byte(s.presentBody)) + }) + mux.HandleFunc("/authorizations/", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(s.authStatus) + _, _ = w.Write([]byte(s.authBody)) + }) + mux.HandleFunc("/signature/verify", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(s.verifyStatus) + }) + return mux +} + +// validCESR is a minimal full-chain export: a leading ACDC frame whose +// self-addressing `d` is the presented credential SAID. +const validCESR = `{"v":"ACDC10JSON00011c_","d":"ECredSAID123","i":"EHolderAID","s":"ESchema","a":{"LEI":"5493001KJTIIGC8Y1R17"}}-CESR-attachments` + +func newVerifierFor(t *testing.T, s *vleiServer) *Verifier { + t.Helper() + srv := httptest.NewServer(s.handler()) + t.Cleanup(srv.Close) + return NewVerifier(srv.URL+"/", WithHTTPClient(srv.Client()), WithTimeout(2*time.Second), WithMaxBodyBytes(1<<16)) +} + +func TestVerifierPresentHappy(t *testing.T) { + s := &vleiServer{ + presentStatus: http.StatusAccepted, + presentBody: `{"aid":"EHolderAID","said":"ECredSAID123"}`, + authStatus: http.StatusOK, + authBody: `{"aid":"EHolderAID","lei":"5493001KJTIIGC8Y1R17","role":"OOR"}`, + } + v := newVerifierFor(t, s) + res, err := v.Present(context.Background(), validCESR) + if err != nil { + t.Fatalf("Present: %v", err) + } + if res.SubjectAID != "EHolderAID" || res.LEI != "5493001KJTIIGC8Y1R17" || res.Status != "AUTHORIZED" { + t.Fatalf("present result: %+v", res) + } +} + +func TestVerifierPresentPendingAuthorization(t *testing.T) { + // Presentation accepted but authorization still processing → PENDING. + s := &vleiServer{ + presentStatus: http.StatusOK, + presentBody: `{"aid":"EHolderAID","said":"ECredSAID123"}`, + authStatus: http.StatusNotFound, + } + v := newVerifierFor(t, s) + res, err := v.Present(context.Background(), validCESR) + if err != nil { + t.Fatalf("Present: %v", err) + } + if res.Status != "PENDING" || res.SubjectAID != "EHolderAID" { + t.Fatalf("present result: %+v", res) + } +} + +func TestVerifierPresentFailures(t *testing.T) { + t.Run("no ACDC frame", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{}) + if _, err := v.Present(context.Background(), "no acdc here"); !isCode(err, "LEI_PRESENTATION_INVALID") { + t.Fatalf("want LEI_PRESENTATION_INVALID, got %v", err) + } + }) + t.Run("verifier rejects 4xx", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{presentStatus: http.StatusBadRequest}) + if _, err := v.Present(context.Background(), validCESR); !isCode(err, "LEI_PRESENTATION_INVALID") { + t.Fatalf("want LEI_PRESENTATION_INVALID, got %v", err) + } + }) + t.Run("path-injecting SAID rejected before dial", func(t *testing.T) { + // A leaf SAID carrying path/query characters must be rejected by the + // qb64 guard — never interpolated into the request path. + v := newVerifierFor(t, &vleiServer{presentStatus: http.StatusOK, presentBody: `{"aid":"EAID"}`}) + injecting := `{"v":"ACDC10JSON_","d":"../authorizations/EVIL?x=1"}` + if _, err := v.Present(context.Background(), injecting); !isCode(err, "LEI_PRESENTATION_INVALID") { + t.Fatalf("want LEI_PRESENTATION_INVALID, got %v", err) + } + }) + t.Run("verifier 5xx unavailable", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{presentStatus: http.StatusInternalServerError}) + if _, err := v.Present(context.Background(), validCESR); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) + } + }) + t.Run("empty aid unavailable", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{presentStatus: http.StatusOK, presentBody: `{"said":"x"}`}) + if _, err := v.Present(context.Background(), validCESR); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) + } + }) +} + +func TestVerifierAuthorization(t *testing.T) { + ctx := context.Background() + t.Run("authorized", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{authStatus: http.StatusOK, authBody: `{"lei":"L1"}`}) + auth, err := v.Authorization(ctx, "EAID") + if err != nil || !auth.Authorized || auth.LEI != "L1" { + t.Fatalf("auth=%+v err=%v", auth, err) + } + }) + for _, code := range []int{http.StatusUnauthorized, http.StatusNotFound} { + v := newVerifierFor(t, &vleiServer{authStatus: code}) + auth, err := v.Authorization(ctx, "EAID") + if err != nil || auth.Authorized { + t.Fatalf("status %d: auth=%+v err=%v", code, auth, err) + } + } + t.Run("5xx unavailable", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{authStatus: http.StatusBadGateway}) + if _, err := v.Authorization(ctx, "EAID"); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) + } + }) + t.Run("non-qb64 AID rejected before dial", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{authStatus: http.StatusOK, authBody: `{"lei":"L1"}`}) + if _, err := v.Authorization(ctx, "../signature/verify"); !isCode(err, "LEI_SUBJECT_AID_INVALID") { + t.Fatalf("want LEI_SUBJECT_AID_INVALID, got %v", err) + } + }) +} + +func TestVerifierVerifySignature(t *testing.T) { + ctx := context.Background() + t.Run("verifies", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{verifyStatus: http.StatusAccepted}) + ok, err := v.VerifySignature(ctx, "EAID", "input", "0Bsig") + if err != nil || !ok { + t.Fatalf("ok=%v err=%v", ok, err) + } + }) + // 401: bad signature; 400: malformed input; 404: AID unknown to the + // verifier's KEL — all non-verifying signatures, never outages. + for _, code := range []int{http.StatusUnauthorized, http.StatusBadRequest, http.StatusNotFound} { + v := newVerifierFor(t, &vleiServer{verifyStatus: code}) + ok, err := v.VerifySignature(ctx, "EAID", "input", "0Bsig") + if err != nil || ok { + t.Fatalf("status %d: ok=%v err=%v", code, ok, err) + } + } + t.Run("5xx unavailable", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{verifyStatus: http.StatusInternalServerError}) + if _, err := v.VerifySignature(ctx, "EAID", "input", "0Bsig"); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) + } + }) +} + +func TestVerifierUnreachable(t *testing.T) { + // A base URL pointing nowhere → the client.Do error path → unavailable. + v := NewVerifier("http://127.0.0.1:1", WithTimeout(500*time.Millisecond)) + if _, err := v.Authorization(context.Background(), "EAID"); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) + } +} + +func TestVerifierMalformedSuccessBodyFailsClosed(t *testing.T) { + // A 200 carrying malformed JSON must surface as LEI_VERIFIER_UNAVAILABLE + // instead of silently leaving out zero-valued — otherwise an authorized + // response with junk JSON would degrade to the noop waiver (auth.LEI == "") + // and the service's AID↔LEI binding check would be skipped. + t.Run("present", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{presentStatus: http.StatusOK, presentBody: `{not-json`}) + if _, err := v.Present(context.Background(), validCESR); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) + } + }) + t.Run("authorize", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{authStatus: http.StatusOK, authBody: `{not-json`}) + if _, err := v.Authorization(context.Background(), "EAID"); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) + } + }) +} + +func TestVerifierBodyCapExceeded(t *testing.T) { + // A response larger than the configured cap is treated as a protocol + // failure (unavailable), never decoded — the response-size control. + s := &vleiServer{authStatus: http.StatusOK, authBody: `{"lei":"a-body-far-larger-than-the-cap"}`} + srv := httptest.NewServer(s.handler()) + t.Cleanup(srv.Close) + v := NewVerifier(srv.URL, WithHTTPClient(srv.Client()), WithMaxBodyBytes(8)) + if _, err := v.Authorization(context.Background(), "EAID"); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) + } +} + +func TestPresentedCredentialSAID(t *testing.T) { + cases := []struct { + name, in, want string + }{ + {"single credential", validCESR, "ECredSAID123"}, + {"no marker", "plain text", ""}, + {"escaped strings before d", `{"v":"ACDC10JSON_","note":"a \"quoted\" }brace","d":"EReal"}`, "EReal"}, + {"unterminated object", `{"v":"ACDC10JSON_","d":"x"`, ""}, + {"marker but no d, then a real one", `{"v":"ACDC10JSON_","x":1}{"v":"ACDC10JSON_","d":"ESecond"}`, "ESecond"}, + // Full-chain exports: the leaf is the credential no other + // credential's edge `n` references — independent of frame order. + // KERIA emits issuer-first (leaf last); we must not pick the first. + {"chain leaf serialized last", + `{"v":"ACDC10JSON_","d":"EQVI","a":{"LEI":"L"}}` + + `{"v":"ACDC10JSON_","d":"ELE","e":{"d":"Eedge1","qvi":{"n":"EQVI","s":"S"}}}` + + `{"v":"ACDC10JSON_","d":"EECR","e":{"d":"Eedge2","le":{"n":"ELE","s":"S"}}}`, + "EECR"}, + {"chain leaf serialized first", + `{"v":"ACDC10JSON_","d":"EECR","e":{"d":"Eedge2","le":{"n":"ELE","s":"S"}}}` + + `{"v":"ACDC10JSON_","d":"ELE","e":{"d":"Eedge1","qvi":{"n":"EQVI","s":"S"}}}` + + `{"v":"ACDC10JSON_","d":"EQVI","a":{"LEI":"L"}}`, + "EECR"}, + // An edge group may be an ARRAY of edges (multi-source), and a + // non-string `n` is ignored — both edge-walk branches exercised. + {"edge group as array", + `{"v":"ACDC10JSON_","d":"EROOT","a":{"LEI":"L"}}` + + `{"v":"ACDC10JSON_","d":"ELEAF","e":{"d":"Eb","grp":[{"n":"EROOT","s":"S"},{"n":123}]}}`, + "ELEAF"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := presentedCredentialSAID(tc.in); got != tc.want { + t.Fatalf("presentedCredentialSAID = %q, want %q", got, tc.want) + } + }) + } +} + +func isCode(err error, code string) bool { + var de *domain.Error + return errors.As(err, &de) && de.Code == code +} diff --git a/internal/adapter/leiverifier/noop.go b/internal/adapter/leiverifier/noop.go new file mode 100644 index 0000000..18150c5 --- /dev/null +++ b/internal/adapter/leiverifier/noop.go @@ -0,0 +1,138 @@ +// Package leiverifier provides the two port.LEIControlVerifier +// adapters behind the lei (vLEI) identifier kind: +// +// - Noop — zero-infra quickstart verifier; runs REAL Ed25519 +// crypto over the signing input but waives the GLEIF/vlei-verifier +// authorization binding. +// - Verifier — the real thing: a hardened HTTP client for an +// internal vlei-verifier service (present / authorize / verify). +// +// Selected by `vlei.type` ("noop" | "verifier") in the RA config — +// the same pattern as the DNS verifier's `dns.type` ("noop" | +// "lookup") and the did:web resolver's `identity.resolver.type` +// ("noop" | "web"). +package leiverifier + +import ( + "context" + "crypto/ed25519" + "encoding/base64" + "encoding/json" + + "github.com/godaddy/ans/internal/domain" + "github.com/godaddy/ans/internal/port" +) + +// Noop is the quickstart vLEI verifier. It never dials anywhere. +// +// What this preserves and what it waives, stated precisely (the noop +// DNS / noop did:web precedent — real crypto, waived external-world +// binding): +// +// - PRESERVED: VerifySignature runs a genuine Ed25519 verification +// of the registrant's signature over the served signingInput, so +// the sealed proof is not a rubber stamp. The subject AID encodes +// the registrant's public key, so the verify key is recoverable +// from the AID alone — no KEL, no state. +// - WAIVED: "is this CESR really an authorized vLEI credential, and +// is the AID↔LEI binding real?" Anyone can mint a keypair and +// present any LEI. Authorization therefore returns Authorized +// with an empty LEI (no binding asserted), and the service skips +// the LEI-equality check accordingly. +// +// In noop mode the presentation `cesr` is a base64url (unpadded) +// encoding of a small JSON object {"publicKey": "", "lei": ""}, and a signature is the +// base64url (unpadded) Ed25519 signature over the exact signingInput +// bytes. Strictly for local development and tests. NOT for production. +type Noop struct{} + +// NewNoop returns the quickstart verifier. +func NewNoop() *Noop { return &Noop{} } + +// noopPresentation is the noop's stand-in for a full-chain CESR export. +type noopPresentation struct { + PublicKey string `json:"publicKey"` + LEI string `json:"lei"` +} + +// Present decodes the noop presentation, recovers the registrant's +// Ed25519 public key, and reports a subject AID that IS the base64url +// encoding of that key (so VerifySignature can recover it). The LEI is +// echoed verbatim and the status is always AUTHORIZED. +func (n *Noop) Present(_ context.Context, cesr string) (port.PresentationResult, error) { + pres, pub, err := decodeNoopPresentation(cesr) + if err != nil { + return port.PresentationResult{}, err + } + return port.PresentationResult{ + SubjectAID: base64.RawURLEncoding.EncodeToString(pub), + LEI: pres.LEI, + Status: "AUTHORIZED", + }, nil +} + +// Authorization always authorizes a well-formed AID and asserts NO +// LEI binding (the waived check) — the service treats the empty LEI +// as "verifier does not constrain the LEI". +func (n *Noop) Authorization(_ context.Context, subjectAID string) (port.AuthorizationResult, error) { + if _, err := decodeSubjectAID(subjectAID); err != nil { + return port.AuthorizationResult{}, err + } + return port.AuthorizationResult{Authorized: true, LEI: ""}, nil +} + +// VerifySignature recovers the public key from the subject AID and +// runs a real Ed25519 verification of the signature over the +// signingInput bytes. A malformed AID or signature is a false (not an +// error) — a non-verifying proof, not an I/O failure. +func (n *Noop) VerifySignature(_ context.Context, subjectAID, signingInput, signature string) (bool, error) { + pub, err := decodeSubjectAID(subjectAID) + if err != nil { + return false, nil //nolint:nilerr // malformed AID is a non-verifying proof (false), not an I/O failure + } + sig, err := base64.RawURLEncoding.DecodeString(signature) + if err != nil || len(sig) != ed25519.SignatureSize { + return false, nil //nolint:nilerr // malformed signature is a non-verifying proof (false), not an I/O failure + } + return ed25519.Verify(pub, []byte(signingInput), sig), nil +} + +// decodeNoopPresentation parses the base64url-wrapped JSON presentation +// and validates the embedded Ed25519 public key. +func decodeNoopPresentation(cesr string) (noopPresentation, ed25519.PublicKey, error) { + raw, err := base64.RawURLEncoding.DecodeString(cesr) + if err != nil { + return noopPresentation{}, nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "vlei presentation is not valid base64url") + } + var pres noopPresentation + if err := json.Unmarshal(raw, &pres); err != nil { + return noopPresentation{}, nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "vlei presentation is not a valid noop presentation object") + } + pub, err := decodeSubjectAID(pres.PublicKey) + if err != nil { + return noopPresentation{}, nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "vlei presentation publicKey is not a base64url Ed25519 public key") + } + if pres.LEI == "" { + return noopPresentation{}, nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "vlei presentation carries no lei") + } + return pres, pub, nil +} + +// decodeSubjectAID recovers the Ed25519 public key a noop subject AID +// encodes. +func decodeSubjectAID(aid string) (ed25519.PublicKey, error) { + b, err := base64.RawURLEncoding.DecodeString(aid) + if err != nil || len(b) != ed25519.PublicKeySize { + return nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "subject AID is not a base64url Ed25519 public key") + } + return ed25519.PublicKey(b), nil +} + +// compile-time conformance. +var _ port.LEIControlVerifier = (*Noop)(nil) diff --git a/internal/adapter/leiverifier/verifier.go b/internal/adapter/leiverifier/verifier.go new file mode 100644 index 0000000..9f35421 --- /dev/null +++ b/internal/adapter/leiverifier/verifier.go @@ -0,0 +1,447 @@ +package leiverifier + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/godaddy/ans/internal/domain" + "github.com/godaddy/ans/internal/port" +) + +// Verifier is the production vLEI control verifier: a hardened HTTP +// client for an internal GLEIF vlei-verifier service. The RA is the +// single touchpoint for the verifier — it never parses KERI key state +// itself; the verifier is the authoritative key-state oracle. +// +// It speaks three vlei-verifier endpoints (the real reference API): +// +// - PUT /presentations/{said} (application/json+cesr) — submit the +// full-chain CESR export; the verifier validates it cryptographically +// and reports the holder AID + credential SAID. The {said} is read +// out of the (registrant-supplied) CESR, so it is qb64-validated +// before it is interpolated into the path (see isQB64); the verifier +// then re-derives and re-validates it, and the SUBJECT AID we pin +// comes from the verifier's response, never from the caller. +// - GET /authorizations/{aid} — the LIVE authorization for the AID: +// 200 with {aid, said, lei, role} while authorized, 401 when not, +// 404 before the presentation has been processed. +// - POST /signature/verify — verify a CESR signature: the +// verifier resolves the AID's current key from its KEL and checks +// the signature over the supplied bytes verbatim. +// +// The base URL is operator-configured (a trusted internal service), so +// the host can never be attacker-chosen the way the did:web resolver's +// can; the controls are a hard timeout, a response-size cap, error +// details that never echo the configured host, and qb64 validation of +// every identifier interpolated into a request path (the {said} read +// from registrant-supplied CESR, the subject AID) so it cannot re-target +// the path or inject a query against that host. +type Verifier struct { + baseURL string + client *http.Client + maxBodyBytes int64 +} + +// VerifierOption customizes the Verifier. +type VerifierOption func(*Verifier) + +// WithTimeout overrides the per-request HTTP timeout (default 5s). +func WithTimeout(d time.Duration) VerifierOption { + return func(v *Verifier) { + if d > 0 { + v.client.Timeout = d + } + } +} + +// WithHTTPClient injects an HTTP client (tests). Its Timeout is +// preserved unless WithTimeout follows. +func WithHTTPClient(c *http.Client) VerifierOption { + return func(v *Verifier) { + if c != nil { + v.client = c + } + } +} + +// WithMaxBodyBytes overrides the response-size cap (default 1 MiB). +func WithMaxBodyBytes(n int64) VerifierOption { + return func(v *Verifier) { + if n > 0 { + v.maxBodyBytes = n + } + } +} + +// NewVerifier constructs the production verifier against baseURL (e.g. +// "http://vlei-verifier:7676"), with the trailing slash trimmed. +func NewVerifier(baseURL string, opts ...VerifierOption) *Verifier { + v := &Verifier{ + baseURL: strings.TrimRight(baseURL, "/"), + client: &http.Client{Timeout: 5 * time.Second}, + maxBodyBytes: 1 << 20, + } + for _, opt := range opts { + opt(v) + } + return v +} + +// presentationResponse is the PUT /presentations/{said} body. +type presentationResponse struct { + AID string `json:"aid"` + SAID string `json:"said"` + Msg string `json:"msg"` +} + +// authorizationResponse is the GET /authorizations/{aid} body. +type authorizationResponse struct { + AID string `json:"aid"` + SAID string `json:"said"` + LEI string `json:"lei"` + Role string `json:"role"` + Msg string `json:"msg"` +} + +// Present submits the full-chain CESR export and returns the verifier's +// view of the holder. The subject AID is read from the verifier's +// response — never extracted by us, never caller-asserted. The {said} +// path segment is the only thing we read out of the CESR (a content +// address the verifier re-derives), routing the submission to the +// presented credential. +func (v *Verifier) Present(ctx context.Context, cesr string) (port.PresentationResult, error) { + said := presentedCredentialSAID(cesr) + if said == "" { + return port.PresentationResult{}, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "vlei presentation carries no ACDC credential") + } + // said is read from registrant-supplied CESR and interpolated into the + // path below — reject anything outside the qb64 alphabet so it cannot + // re-target the path ('/', '..') or inject a query ('?', '#', '%'). + if !isQB64(said) { + return port.PresentationResult{}, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "the presented credential SAID is not a valid qb64 identifier") + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPut, + v.baseURL+"/presentations/"+said, strings.NewReader(cesr)) + if err != nil { + return port.PresentationResult{}, v.unavailable("present") + } + req.Header.Set("Content-Type", "application/json+cesr") + + var pres presentationResponse + status, err := v.do(req, &pres) + if err != nil { + return port.PresentationResult{}, err + } + switch { + case status == http.StatusAccepted || status == http.StatusOK: + // processed below + case status >= 400 && status < 500: + return port.PresentationResult{}, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "the vlei verifier rejected the presented credential") + default: + return port.PresentationResult{}, v.unavailable("present") + } + if pres.AID == "" { + return port.PresentationResult{}, v.unavailable("present") + } + + // The presentation is accepted; authorization is processed + // asynchronously, so the holder may still be PENDING. A live + // authorization check resolves the status + LEI. + auth, err := v.Authorization(ctx, pres.AID) + if err != nil { + return port.PresentationResult{}, err + } + status0 := "PENDING" + if auth.Authorized { + status0 = "AUTHORIZED" + } + return port.PresentationResult{ + SubjectAID: pres.AID, + LEI: auth.LEI, + Status: status0, + }, nil +} + +// Authorization reports the verifier's live authorization for the AID. +func (v *Verifier) Authorization(ctx context.Context, subjectAID string) (port.AuthorizationResult, error) { + // On the real path subjectAID is verifier-derived, but it is + // interpolated into the path below all the same — qb64-validate it for + // the same reason as the {said} in Present (defense in depth). + if !isQB64(subjectAID) { + return port.AuthorizationResult{}, domain.NewValidationError("LEI_SUBJECT_AID_INVALID", + "subject AID is not a valid qb64 identifier") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, + v.baseURL+"/authorizations/"+subjectAID, nil) + if err != nil { + return port.AuthorizationResult{}, v.unavailable("authorize") + } + var auth authorizationResponse + status, err := v.do(req, &auth) + if err != nil { + return port.AuthorizationResult{}, err + } + switch status { + case http.StatusOK: + return port.AuthorizationResult{Authorized: true, LEI: auth.LEI}, nil + case http.StatusUnauthorized, http.StatusNotFound: + // 401: presented but not authorized; 404: not yet processed. + return port.AuthorizationResult{Authorized: false}, nil + default: + return port.AuthorizationResult{}, v.unavailable("authorize") + } +} + +// signatureVerifyRequest is the POST /signature/verify body. The +// verifier resolves the AID's current key from its KEL and checks the +// signature over the UTF-8 bytes of non_prefixed_digest verbatim — so +// non_prefixed_digest carries the served signingInput, the exact bytes +// the registrant signed (the same payload the JWS kinds sign). +type signatureVerifyRequest struct { + SignerAID string `json:"signer_aid"` + Signature string `json:"signature"` + NonPrefixedDigest string `json:"non_prefixed_digest"` +} + +// VerifySignature checks the CESR signature over the signing input via +// the verifier's KEL-backed key state. A well-formed but non-verifying +// signature is a false; an I/O or protocol failure reaching the +// verifier is an error. +func (v *Verifier) VerifySignature(ctx context.Context, subjectAID, signingInput, signature string) (bool, error) { + body, err := json.Marshal(signatureVerifyRequest{ + SignerAID: subjectAID, + Signature: signature, + NonPrefixedDigest: signingInput, + }) + if err != nil { + return false, v.unavailable("verify-signature") + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, + v.baseURL+"/signature/verify", bytes.NewReader(body)) + if err != nil { + return false, v.unavailable("verify-signature") + } + req.Header.Set("Content-Type", "application/json") + + status, err := v.do(req, nil) + if err != nil { + return false, err + } + switch status { + case http.StatusAccepted, http.StatusOK: + return true, nil + case http.StatusUnauthorized, http.StatusBadRequest, http.StatusNotFound: + // 401: signature does not verify against the AID's current key. + // 400: malformed input (a non-verifying signature, not an outage). + // 404: AID is unknown to the verifier's KEL — also a non-verifying + // proof from the registrant's perspective, not a verifier outage. + return false, nil + default: + return false, v.unavailable("verify-signature") + } +} + +// do executes the request, enforces the response-size cap, and (when +// out is non-nil and the status carries a JSON body) decodes it. +// Returns the status code so callers map it to domain semantics. +func (v *Verifier) do(req *http.Request, out any) (int, error) { + // The request URL is built only from the operator-configured baseURL + // (a trusted internal vlei-verifier) plus verifier-controlled path + // segments — never from registrant input — so the SSRF posture the + // did:web resolver needs does not apply here. (See the type doc.) + resp, err := v.client.Do(req) //nolint:gosec // baseURL is operator-configured; no caller-controlled host + + if err != nil { + return 0, v.unavailable(req.Method) + } + defer func() { _ = resp.Body.Close() }() + + body, err := io.ReadAll(io.LimitReader(resp.Body, v.maxBodyBytes+1)) + if err != nil { + return resp.StatusCode, v.unavailable(req.Method) + } + if int64(len(body)) > v.maxBodyBytes { + return resp.StatusCode, v.unavailable(req.Method) + } + // Decode strictly on a 2xx success — the contract callers rely on. + // A 200 with malformed JSON would otherwise leave `out` zero-valued + // (e.g. auth.LEI == ""), and the service treats an empty LEI as the + // noop waiver of the AID↔LEI binding — silently degrading the + // production verifier to noop semantics. Fail-closed instead. + // Non-2xx bodies are caller-mapped status text (plain or JSON) and + // are not consumed by callers, so we leave them undecoded. + if out != nil && len(body) > 0 && resp.StatusCode >= 200 && resp.StatusCode < 300 { + if err := json.Unmarshal(body, out); err != nil { + return resp.StatusCode, v.unavailable("decode") + } + } + return resp.StatusCode, nil +} + +// unavailable builds the operator-facing error for a verifier I/O or +// protocol failure. The detail names the operation but never the +// configured host (no internal-topology leak). +func (v *Verifier) unavailable(op string) error { + return domain.NewInternalError("LEI_VERIFIER_UNAVAILABLE", + fmt.Sprintf("the vlei verifier is unavailable (%s)", op), nil) +} + +// isQB64 reports whether s is a non-empty CESR qb64 token — the +// base64url alphabet ([A-Za-z0-9_-]) and nothing else. KERI SAIDs and +// AIDs are qb64, so this is the guard that lets us safely interpolate a +// verifier SAID / subject AID into a request path: it rejects '/', '.', +// '?', '#', '%', and every other character that could re-target the path +// or inject a query against the operator-configured verifier host. The +// fixed baseURL bounds the host; this bounds the path. +func isQB64(s string) bool { + if s == "" { + return false + } + for i := range len(s) { + c := s[i] + switch { + case c >= 'A' && c <= 'Z', + c >= 'a' && c <= 'z', + c >= '0' && c <= '9', + c == '-', c == '_': + default: + return false + } + } + return true +} + +// presentedCredentialSAID extracts the SAID of the *presented* (leaf) +// credential from a full-chain CESR export — the minimal, targeted read +// the real verifier path needs to route PUT /presentations/{said}. It is +// NOT a CESR codec: KERI/ACDC serializations are version-string-first, so +// an ACDC credential message is always a JSON object whose first member +// is `"v":"ACDC…"`; we locate those frames by brace-balancing (respecting +// JSON string escaping), read each frame's self-addressing `d`, and +// collect the edge node SAIDs (the `n` of each edge) from each frame's +// `e` block. +// +// The presented credential is the most-derived one — the ECR/role +// credential at the bottom of the ECR→LE→QVI chain — identified +// structurally as the lone credential whose SAID is NOT referenced by any +// other credential's edge. This is position-independent: KERIA's +// `credentials().get(said, true)` exporter emits the chain in topological +// (issuer-first) order, so the leaf is serialized LAST, but we never rely +// on frame order. A single-credential export (no chain) has no references, +// so its one frame is the leaf. The end-to-end demo (scripts/demo/vlei) +// exercises this against the live verifier. +func presentedCredentialSAID(cesr string) string { + const marker = `{"v":"ACDC` + type acdcFrame struct { + D string `json:"d"` + E json.RawMessage `json:"e"` + } + var saids []string + referenced := make(map[string]struct{}) + offset := 0 + for { + rel := strings.Index(cesr[offset:], marker) + if rel < 0 { + break + } + start := offset + rel + obj, end := balancedJSONObject(cesr, start) + if obj == "" { + offset = start + 1 + continue + } + offset = end + var frame acdcFrame + if err := json.Unmarshal([]byte(obj), &frame); err != nil || frame.D == "" { + continue + } + saids = append(saids, frame.D) + if len(frame.E) > 0 { + collectEdgeNodes(frame.E, referenced) + } + } + // The leaf is the credential no other credential chains to. A + // well-formed linear chain has exactly one such SAID. + for _, d := range saids { + if _, ok := referenced[d]; !ok { + return d + } + } + return "" +} + +// collectEdgeNodes walks an ACDC `e` (edge) block and records every edge +// node SAID — the `n` field of each edge — into seen. Edge group names +// are arbitrary (le, qvi, auth, …) and the block may nest, so it +// recurses; the edge block's own `d` (a SAID of the edge block itself, +// not a referenced credential) is ignored because only `n` values are +// collected. +func collectEdgeNodes(raw json.RawMessage, seen map[string]struct{}) { + var doc any + if err := json.Unmarshal(raw, &doc); err != nil { + return + } + var walk func(v any) + walk = func(v any) { + switch t := v.(type) { + case map[string]any: + for k, val := range t { + if k == "n" { + if s, ok := val.(string); ok && s != "" { + seen[s] = struct{}{} + } + } + walk(val) + } + case []any: + for _, el := range t { + walk(el) + } + } + } + walk(doc) +} + +// balancedJSONObject returns the JSON object beginning at start +// (cesr[start] must be '{') and the index just past it, balancing +// braces while respecting strings and escapes. Returns "" if the object +// does not close. +func balancedJSONObject(s string, start int) (string, int) { + depth := 0 + inStr := false + escaped := false + for i := start; i < len(s); i++ { + c := s[i] + switch { + case escaped: + escaped = false + case c == '\\' && inStr: + escaped = true + case c == '"': + inStr = !inStr + case inStr: + // skip + case c == '{': + depth++ + case c == '}': + depth-- + if depth == 0 { + return s[start : i+1], i + 1 + } + } + } + return "", len(s) +} + +// compile-time conformance. +var _ port.LEIControlVerifier = (*Verifier)(nil) diff --git a/internal/adapter/store/sqlite/identity.go b/internal/adapter/store/sqlite/identity.go index ea35bc4..35a10a6 100644 --- a/internal/adapter/store/sqlite/identity.go +++ b/internal/adapter/store/sqlite/identity.go @@ -25,6 +25,7 @@ type identityRow struct { Status string `db:"status"` ProofMethod string `db:"proof_method"` PendingValue string `db:"pending_value"` + SubjectAID sql.NullString `db:"subject_aid"` ChallengeNonce sql.NullString `db:"challenge_nonce"` ChallengeExpiresAtMs sql.NullInt64 `db:"challenge_expires_at_ms"` ChallengeConsumedAtMs sql.NullInt64 `db:"challenge_consumed_at_ms"` @@ -34,7 +35,7 @@ type identityRow struct { } const identityCols = `identity_id, provider_id, kind, value, status, proof_method, - pending_value, challenge_nonce, challenge_expires_at_ms, + pending_value, subject_aid, challenge_nonce, challenge_expires_at_ms, challenge_consumed_at_ms, verified_at_ms, created_at_ms, updated_at_ms` func (r identityRow) toDomain() *domain.VerifiedIdentity { @@ -46,6 +47,7 @@ func (r identityRow) toDomain() *domain.VerifiedIdentity { Status: domain.IdentityStatus(r.Status), ProofMethod: r.ProofMethod, PendingValue: r.PendingValue, + SubjectAID: r.SubjectAID.String, CreatedAt: msToTime(r.CreatedAtMs), UpdatedAt: msToTime(r.UpdatedAtMs), } @@ -85,14 +87,19 @@ func (s *IdentityStore) Save(ctx context.Context, v *domain.VerifiedIdentity) er if !v.VerifiedAt.IsZero() { verifiedAt = sql.NullInt64{Int64: v.VerifiedAt.UnixMilli(), Valid: true} } + var subjectAID sql.NullString + if v.SubjectAID != "" { + subjectAID = sql.NullString{String: v.SubjectAID, Valid: true} + } const q = ` INSERT INTO identities (` + identityCols + `) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(identity_id) DO UPDATE SET value = excluded.value, status = excluded.status, proof_method = excluded.proof_method, pending_value = excluded.pending_value, + subject_aid = excluded.subject_aid, challenge_nonce = excluded.challenge_nonce, challenge_expires_at_ms = excluded.challenge_expires_at_ms, challenge_consumed_at_ms = excluded.challenge_consumed_at_ms, @@ -106,7 +113,7 @@ func (s *IdentityStore) Save(ctx context.Context, v *domain.VerifiedIdentity) er updated_at_ms = excluded.updated_at_ms` _, err := s.db.extx(ctx).ExecContext(ctx, q, v.IdentityID, v.ProviderID, string(v.Kind), v.Value, string(v.Status), - v.ProofMethod, v.PendingValue, + v.ProofMethod, v.PendingValue, subjectAID, nonce, expiresAt, consumedAt, verifiedAt, v.CreatedAt.UnixMilli(), v.UpdatedAt.UnixMilli(), ) diff --git a/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql b/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql new file mode 100644 index 0000000..4cd32da --- /dev/null +++ b/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql @@ -0,0 +1,13 @@ +-- lei (vLEI) subject AID pinning. +-- +-- The lei kind carries its credential presentation at REGISTER time; +-- the verifier extracts the holder AID from that presentation and the +-- RA pins it on the aggregate (the §3.6 pinning rule — the caller +-- never re-supplies the signer at verify-control). The AID must +-- therefore persist between register and verify-control. +-- +-- Nullable: every other kind (did:web, did:key, and future DID +-- methods) carries no register-time presentation and leaves this NULL. +-- No CHECK and no index — the column is read only on the verify-control +-- path for the row already loaded by identity_id. +ALTER TABLE identities ADD COLUMN subject_aid TEXT; diff --git a/internal/config/config.go b/internal/config/config.go index f2e48a2..109fa22 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -172,6 +172,25 @@ type IdentityResolver struct { Type string `koanf:"type"` // "noop" | "web" } +// VLEI selects the vLEI (lei kind) control verifier — the GLEIF / +// vlei-verifier interaction behind the lei identifier kind. Top-level, +// matching the DNS verifier's placement (not nested under identity), +// because it is a distinct outbound dependency with its own service +// endpoint. +// +// "noop" runs real Ed25519 crypto over the signing input but waives +// the GLEIF authorization binding (quickstart — NOT for production); +// "verifier" is a hardened HTTP client for an internal vlei-verifier +// service. +type VLEI struct { + Type string `koanf:"type"` // "noop" | "verifier" + // BaseURL is the internal vlei-verifier service URL, required when + // type is "verifier" (e.g. "http://vlei-verifier:7676"). + BaseURL string `koanf:"base-url"` + // PresentTimeout bounds each verifier HTTP request (default 5s). + PresentTimeout time.Duration `koanf:"present-timeout"` +} + // Keys holds key-manager configuration. type Keys struct { Type string `koanf:"type"` // "file" @@ -259,6 +278,7 @@ type RAConfig struct { CA CA `koanf:"ca"` DNS DNS `koanf:"dns"` Identity Identity `koanf:"identity"` + VLEI VLEI `koanf:"vlei"` Keys Keys `koanf:"keys"` Store Store `koanf:"store"` TLClient TLClient `koanf:"tl-client"` @@ -418,6 +438,9 @@ func (c *RAConfig) Validate() error { if c.Identity.RegisterRateLimit < 0 { return errors.New("identity.register-rate-limit must not be negative") } + if err := validateVLEI(&c.VLEI); err != nil { + return err + } if err := validateKeys(&c.Keys); err != nil { return err } @@ -495,6 +518,29 @@ func validateCAServer(s *CAServer) error { return nil } +// validateVLEI checks the vLEI control-verifier selection: "noop" +// needs nothing, "verifier" needs a valid http(s) base URL, and the +// per-request timeout may not be negative. +func validateVLEI(v *VLEI) error { + switch v.Type { + case "noop": + case "verifier": + if v.BaseURL == "" { + return errors.New("vlei.base-url is required when vlei.type is 'verifier'") + } + u, err := url.Parse(v.BaseURL) + if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") { + return fmt.Errorf("vlei.base-url must be a valid http(s) URL, got %q", v.BaseURL) + } + default: + return fmt.Errorf("vlei.type %q not supported (expected 'noop' or 'verifier')", v.Type) + } + if v.PresentTimeout < 0 { + return errors.New("vlei.present-timeout must not be negative") + } + return nil +} + func validateAuth(a *Auth) error { switch a.Type { case "static": diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 90184e7..3aaacb4 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -153,6 +153,56 @@ tl-client: {base-url: ""} } } +// ----- VLEI validation ----- + +func TestRAConfig_ValidateVLEI(t *testing.T) { + cases := []struct { + name string + mutate func(*RAConfig) + wantErr string // substring; "" means must pass + }{ + {"noop default", func(*RAConfig) {}, ""}, + {"verifier with valid url", func(c *RAConfig) { + c.VLEI = VLEI{Type: "verifier", BaseURL: "http://vlei-verifier:7676"} + }, ""}, + {"verifier https", func(c *RAConfig) { + c.VLEI = VLEI{Type: "verifier", BaseURL: "https://vlei.internal"} + }, ""}, + {"verifier missing base-url", func(c *RAConfig) { + c.VLEI = VLEI{Type: "verifier"} + }, "vlei.base-url is required"}, + {"verifier non-http scheme", func(c *RAConfig) { + c.VLEI = VLEI{Type: "verifier", BaseURL: "ftp://host"} + }, "valid http(s) URL"}, + {"verifier no host", func(c *RAConfig) { + c.VLEI = VLEI{Type: "verifier", BaseURL: "http:///path"} + }, "valid http(s) URL"}, + {"unsupported type", func(c *RAConfig) { + c.VLEI = VLEI{Type: "bogus"} + }, "vlei.type"}, + {"negative present-timeout", func(c *RAConfig) { + c.VLEI = VLEI{Type: "noop", PresentTimeout: -time.Second} + }, "vlei.present-timeout must not be negative"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cfg := defaultRAConfig() + cfg.Auth.Static.APIKey = "test-key" // satisfy the auth check ahead of vlei + tc.mutate(cfg) + err := cfg.Validate() + if tc.wantErr == "" { + if err != nil { + t.Fatalf("expected pass, got %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("want error containing %q, got %v", tc.wantErr, err) + } + }) + } +} + // ----- LoadTL ----- func TestLoadTL_MissingFile(t *testing.T) { diff --git a/internal/config/defaults.go b/internal/config/defaults.go index f12e9e7..c325798 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -27,6 +27,7 @@ func defaultRAConfig() *RAConfig { LinkRateLimit: 60, SealTimeout: 5 * time.Second, }, + VLEI: VLEI{Type: "noop"}, Keys: Keys{ Type: "file", File: &KeysFile{Path: "./data/ra/keys"}, diff --git a/internal/domain/identity.go b/internal/domain/identity.go index 85e0dc0..5caff07 100644 --- a/internal/domain/identity.go +++ b/internal/domain/identity.go @@ -92,6 +92,13 @@ type VerifiedIdentity struct { // (§4.2): set by StageRotation, applied by CompleteVerification. // While staged, the previously sealed state stands. PendingValue string + // SubjectAID is the lei (vLEI) holder AID the verifier extracted + // from the presentation at register time and the RA pinned on the + // aggregate — the signer the verify-control proof is checked + // against (§3.6 pinning rule; the caller never re-supplies it). + // Empty for kinds with no register-time presentation (did:web, + // did:key). + SubjectAID string // Challenge is the live anti-replay nonce, if any. Challenge *IdentityChallenge VerifiedAt time.Time // zero until first proof @@ -385,6 +392,18 @@ func (v *VerifiedIdentity) StageRotation(rawValue string, now time.Time) error { return nil } +// SetSubjectAID pins the lei holder AID the verifier derived from the +// presentation (§3.6). Rejects an empty AID — pinning a blank signer +// would let any key satisfy verify-control. +func (v *VerifiedIdentity) SetSubjectAID(aid string, now time.Time) error { + if aid == "" { + return NewValidationError("LEI_PRESENTATION_INVALID", "subject AID is required") + } + v.SubjectAID = aid + v.UpdatedAt = now.UTC() + return nil +} + // CompleteVerification applies a successful control proof: // // - PENDING_CONTROL → VERIFIED (first proof; seals IDENTITY_VERIFIED) diff --git a/internal/domain/identity_test.go b/internal/domain/identity_test.go index 88000f9..a401ed9 100644 --- a/internal/domain/identity_test.go +++ b/internal/domain/identity_test.go @@ -308,3 +308,29 @@ func TestInferIdentifierKind_DIDWebSegmentRejections(t *testing.T) { t.Fatalf("multi-segment: %v %v %v", kind, canonical, err) } } + +func TestSetSubjectAID(t *testing.T) { + v := newPendingIdentity(t, "5493001KJTIIGC8Y1R17") + + // Empty AID is rejected and mutates nothing. + err := v.SetSubjectAID("", idNow) + var domainErr *Error + if !errors.As(err, &domainErr) || domainErr.Code != "LEI_PRESENTATION_INVALID" { + t.Fatalf("want LEI_PRESENTATION_INVALID, got %v", err) + } + if v.SubjectAID != "" { + t.Fatalf("subject AID should remain unset, got %q", v.SubjectAID) + } + + // A non-empty AID pins the field and stamps UpdatedAt. + later := idNow.Add(time.Minute) + if err := v.SetSubjectAID("EAID123", later); err != nil { + t.Fatalf("SetSubjectAID: %v", err) + } + if v.SubjectAID != "EAID123" { + t.Fatalf("subject AID = %q, want EAID123", v.SubjectAID) + } + if !v.UpdatedAt.Equal(later.UTC()) { + t.Fatalf("UpdatedAt = %v, want %v", v.UpdatedAt, later.UTC()) + } +} diff --git a/internal/port/leiverifier.go b/internal/port/leiverifier.go new file mode 100644 index 0000000..73fe7b9 --- /dev/null +++ b/internal/port/leiverifier.go @@ -0,0 +1,66 @@ +package port + +import "context" + +// PresentationResult is what a vLEI presentation yields once the +// verifier has parsed the full-chain CESR export: the holder's subject +// AID (derived FROM the presentation, never caller-asserted — the +// §3.6 pinning rule), the credential's authorized LEI, and the +// verifier's register-time authorization status. +// +// Status is advisory: it records what the verifier saw at present +// time. The authoritative gate is the LIVE Authorization re-check at +// verify-control — a credential may age out of authorization (the +// vlei-verifier's TimeoutAuth window) between register and prove. +type PresentationResult struct { + // SubjectAID is the holder AID the verifier extracted from the + // presentation. The RA pins it on the identity aggregate; the + // caller never supplies it. + SubjectAID string + // LEI is the LEI the presented credential authorizes the AID for. + LEI string + // Status is "AUTHORIZED" or "PENDING". + Status string +} + +// AuthorizationResult is the verifier's LIVE view of an AID's vLEI +// authorization at verify-control time. +type AuthorizationResult struct { + // Authorized reports whether the AID currently holds a valid, + // unexpired vLEI authorization. + Authorized bool + // LEI is the authorized LEI, when the verifier asserts one. The + // noop adapter waives the AID↔LEI binding and returns "" — the + // service then skips the LEI-equality assertion (the documented + // noop waiver, mirroring noop-DNS waiving the zone binding). + LEI string +} + +// LEIControlVerifier is the outbound port for the GLEIF / vlei-verifier +// interaction behind the lei (vLEI) identifier kind. lei is NOT a DID +// method, so it does not ride port.DIDResolver; it gets its own port, +// following the DNS/DID precedent — a noop adapter for the quickstart +// and a real adapter selected by config (`vlei.type: noop | verifier`). +// +// The RA never parses CESR/KERI: the verifier is the authoritative +// key-state oracle. Present reports the subject AID, Authorization +// re-checks live authorization, and VerifySignature owns the KEL/key +// state used to check the registrant's signature. +type LEIControlVerifier interface { + // Present submits the full-chain CESR export to the verifier and + // returns the parsed subject AID + authorized LEI + presentation + // status. The subject AID is derived from the presentation, never + // caller-asserted. + Present(ctx context.Context, cesr string) (PresentationResult, error) + + // Authorization reports the verifier's LIVE authorization for the + // AID (re-checked on every verify-control; the register-time + // status is advisory). + Authorization(ctx context.Context, subjectAID string) (AuthorizationResult, error) + + // VerifySignature checks that `signature` over `signingInput` was + // produced by the AID's current signing key (the verifier owns the + // KEL/key state); an error signals an + // I/O or protocol failure reaching the verifier. + VerifySignature(ctx context.Context, subjectAID, signingInput, signature string) (bool, error) +} diff --git a/internal/ra/handler/identity.go b/internal/ra/handler/identity.go index 7f451ff..bffcc0c 100644 --- a/internal/ra/handler/identity.go +++ b/internal/ra/handler/identity.go @@ -31,6 +31,15 @@ func NewIdentityHandler(svc *service.IdentityService) *IdentityHandler { // — never caller-asserted. type identityRegisterRequest struct { Value string `json:"value"` + // VLEIPresentation carries the lei full-chain CESR export at + // register time (the credential + KELs). Set only for lei; the + // JWS kinds omit it. + VLEIPresentation *vleiPresentationDTO `json:"vleiPresentation,omitempty"` +} + +// vleiPresentationDTO is the lei register-time credential presentation. +type vleiPresentationDTO struct { + CESR string `json:"cesr"` } // identityChallengeDTO is one entry of the 202 challenge list. @@ -42,13 +51,17 @@ type identityChallengeDTO struct { // identityChallengeResponse is the 202 body returned by register and // rotate: the identity's id plus the challenge round to sign. type identityChallengeResponse struct { - IdentityID string `json:"identityId"` - Kind string `json:"kind"` - Value string `json:"value"` - Status string `json:"status"` - Nonce string `json:"nonce"` - ExpiresAt string `json:"expiresAt"` - Challenges []identityChallengeDTO `json:"challenges"` + IdentityID string `json:"identityId"` + Kind string `json:"kind"` + Value string `json:"value"` + Status string `json:"status"` + // PresentationStatus is the lei register-time advisory status + // ("AUTHORIZED" | "PENDING"); omitted for kinds with no + // register-time presentation (did:web, did:key). + PresentationStatus string `json:"presentationStatus,omitempty"` + Nonce string `json:"nonce"` + ExpiresAt string `json:"expiresAt"` + Challenges []identityChallengeDTO `json:"challenges"` } // verifyControlRequest is the POST .../verify-control body. Members @@ -61,6 +74,10 @@ type verifyControlRequest struct { // SignedProofs — one compact JWS per proven key, every payload // equal to the served signingInput verbatim. SignedProofs []string `json:"signedProofs"` + // CESRSignature — the lei proof: one CESR signature over the + // served signingInput by the subject AID's current key. Set only + // for lei. + CESRSignature string `json:"cesrSignature"` } // identityDetailResponse is the identity object echoed by @@ -107,7 +124,7 @@ func (h *IdentityHandler) Register(w http.ResponseWriter, r *http.Request) { WriteError(w, domain.NewValidationError("INVALID_IDENTIFIER", "value is required")) return } - res, err := h.svc.Register(r.Context(), providerID, req.Value) + res, err := h.svc.Register(r.Context(), providerID, req.Value, req.registerOptions()) if err != nil { WriteError(w, err) return @@ -115,6 +132,16 @@ func (h *IdentityHandler) Register(w http.ResponseWriter, r *http.Request) { WriteJSON(w, http.StatusAccepted, toChallengeResponse(res)) } +// registerOptions maps the kind-specific request members to the +// service's additive RegisterOptions. Empty for non-lei kinds. +func (req identityRegisterRequest) registerOptions() service.RegisterOptions { + var opt service.RegisterOptions + if req.VLEIPresentation != nil { + opt.VLEIPresentation = req.VLEIPresentation.CESR + } + return opt +} + // Rotate handles PUT /v2/ans/identities/{identityId} → 202 + fresh // challenges over the staged replacement. func (h *IdentityHandler) Rotate(w http.ResponseWriter, r *http.Request) { @@ -131,7 +158,7 @@ func (h *IdentityHandler) Rotate(w http.ResponseWriter, r *http.Request) { WriteError(w, domain.NewValidationError("INVALID_IDENTIFIER", "value is required")) return } - res, err := h.svc.Rotate(r.Context(), providerID, chi.URLParam(r, "identityId"), req.Value) + res, err := h.svc.Rotate(r.Context(), providerID, chi.URLParam(r, "identityId"), req.Value, req.registerOptions()) if err != nil { WriteError(w, err) return @@ -153,7 +180,7 @@ func (h *IdentityHandler) VerifyControl(w http.ResponseWriter, r *http.Request) return } identity, err := h.svc.VerifyControl(r.Context(), providerID, chi.URLParam(r, "identityId"), - service.ProofSubmission{SignedProofs: req.SignedProofs}) + service.ProofSubmission{SignedProofs: req.SignedProofs, CESRSignature: req.CESRSignature}) if err != nil { WriteError(w, err) return @@ -306,13 +333,14 @@ func toChallengeResponse(res *service.IdentityChallengeResponse) identityChallen challenges = append(challenges, identityChallengeDTO{Kid: c.Kid, SigningInput: c.SigningInput}) } return identityChallengeResponse{ - IdentityID: res.Identity.IdentityID, - Kind: string(res.Identity.Kind), - Value: res.Identity.EffectiveValue(), - Status: string(res.Identity.Status), - Nonce: res.Nonce, - ExpiresAt: res.ExpiresAt.UTC().Format(time.RFC3339), - Challenges: challenges, + IdentityID: res.Identity.IdentityID, + Kind: string(res.Identity.Kind), + Value: res.Identity.EffectiveValue(), + Status: string(res.Identity.Status), + PresentationStatus: res.PresentationStatus, + Nonce: res.Nonce, + ExpiresAt: res.ExpiresAt.UTC().Format(time.RFC3339), + Challenges: challenges, } } diff --git a/internal/ra/handler/identity_handler_test.go b/internal/ra/handler/identity_handler_test.go index 406b98d..1d1c134 100644 --- a/internal/ra/handler/identity_handler_test.go +++ b/internal/ra/handler/identity_handler_test.go @@ -26,6 +26,7 @@ import ( "github.com/godaddy/ans/internal/adapter/cert" "github.com/godaddy/ans/internal/adapter/didresolver" "github.com/godaddy/ans/internal/adapter/eventbus" + "github.com/godaddy/ans/internal/adapter/leiverifier" "github.com/godaddy/ans/internal/adapter/store/sqlite" anscrypto "github.com/godaddy/ans/internal/crypto" "github.com/godaddy/ans/internal/domain" @@ -87,6 +88,8 @@ func newIdentityHTTPFixture(t *testing.T) *identityHTTPFixture { agents, didresolver.NewNoopResolver(), okSealer{}, + leiverifier.NewNoop(), + outbox, db, ).WithChallengeTTL(30 * time.Minute) diff --git a/internal/ra/service/identity.go b/internal/ra/service/identity.go index e83d2c8..2b16ec6 100644 --- a/internal/ra/service/identity.go +++ b/internal/ra/service/identity.go @@ -72,6 +72,11 @@ type IdentityChallengeResponse struct { Nonce string ExpiresAt time.Time Challenges []ProofChallenge + // PresentationStatus is the advisory register-time status a kind + // with a register-time presentation reports ("AUTHORIZED" | + // "PENDING"); empty for kinds without one (did:web, did:key). The + // handler emits it on the 202 only when set. + PresentationStatus string } // IdentityService owns the Verified Identity lifecycle: register → @@ -111,13 +116,14 @@ func NewIdentityService( agents port.AgentStore, resolver port.DIDResolver, sealer IdentityEventSealer, + leiCtl port.LEIControlVerifier, uow port.UnitOfWork, ) *IdentityService { return &IdentityService{ identities: identities, links: links, agents: agents, - verifiers: newControlVerifiers(resolver), + verifiers: newControlVerifiers(resolver, leiCtl), sealer: sealer, uow: uow, challengeTTL: time.Hour, @@ -237,7 +243,8 @@ func (s *IdentityService) verifierFor(kind domain.IdentifierKind) (controlVerifi // superseded). IDENTIFIER_DUPLICATE is reserved for genuine // conflicts: already VERIFIED by this owner (rotate instead), or // proven by another owner. -func (s *IdentityService) Register(ctx context.Context, providerID, rawValue string) (*IdentityChallengeResponse, error) { +func (s *IdentityService) Register(ctx context.Context, providerID, rawValue string, opts ...RegisterOptions) (*IdentityChallengeResponse, error) { + opt := firstRegisterOption(opts) if providerID == "" { return nil, domain.NewValidationError("INVALID_PROVIDER_ID", "authenticated owner is required") } @@ -263,7 +270,7 @@ func (s *IdentityService) Register(ctx context.Context, providerID, rawValue str "identifier is already verified by this owner; rotate it with PUT instead") case err == nil: // PENDING_CONTROL → idempotent re-challenge on the same row. - return s.challenge(ctx, existing, now, false) + return s.challenge(ctx, existing, now, false, opt) case errors.Is(err, domain.ErrNotFound): // fall through to creation default: @@ -288,14 +295,25 @@ func (s *IdentityService) Register(ctx context.Context, providerID, rawValue str if err != nil { return nil, err } - return s.challenge(ctx, identity, now, true) + return s.challenge(ctx, identity, now, true, opt) +} + +// firstRegisterOption collapses the variadic options to a single +// value: the additive register material is at most one struct, so a +// caller passes zero (non-lei kinds, all current callers) or one. +func firstRegisterOption(opts []RegisterOptions) RegisterOptions { + if len(opts) > 0 { + return opts[0] + } + return RegisterOptions{} } // Rotate stages a same-kind replacement (§4.2 PUT) and returns fresh // challenges over it. The previously sealed state stands until the // new proof lands; a replacement that never verifies expires with its // nonce. -func (s *IdentityService) Rotate(ctx context.Context, providerID, identityID, rawValue string) (*IdentityChallengeResponse, error) { +func (s *IdentityService) Rotate(ctx context.Context, providerID, identityID, rawValue string, opts ...RegisterOptions) (*IdentityChallengeResponse, error) { + opt := firstRegisterOption(opts) if !s.limiter.Allow(providerID, s.clock()) { return nil, domain.NewValidationError("RATE_LIMITED", "too many identity register/rotate calls; retry later") @@ -308,7 +326,7 @@ func (s *IdentityService) Rotate(ctx context.Context, providerID, identityID, ra if err := identity.StageRotation(rawValue, now); err != nil { return nil, err } - return s.challenge(ctx, identity, now, false) + return s.challenge(ctx, identity, now, true, opt) } // challenge mints a fresh nonce on the identity, runs the kind's @@ -321,7 +339,24 @@ func (s *IdentityService) Rotate(ctx context.Context, providerID, identityID, ra // load and persist spans seconds, and a blind upsert here could // clobber a verify or revoke that committed in that window (status // regression = a different owner could then take the identifier). -func (s *IdentityService) challenge(ctx context.Context, identity *domain.VerifiedIdentity, now time.Time, isNew bool) (*IdentityChallengeResponse, error) { +func (s *IdentityService) challenge(ctx context.Context, identity *domain.VerifiedIdentity, now time.Time, isNew bool, opt RegisterOptions) (*IdentityChallengeResponse, error) { + verifier, err := s.verifierFor(identity.Kind) + if err != nil { + return nil, err + } + + // Kinds carrying a register-time presentation (lei) submit it to + // their verifier here, pinning the verifier-derived subject AID on + // the aggregate before the challenge enumerates it. Discovered by + // capability — non-presentation kinds skip this entirely. + var presentationStatus string + if pr, ok := verifier.(presentationRegistrar); ok { + presentationStatus, err = pr.RegisterPresentation(ctx, identity, opt, now) + if err != nil { + return nil, err + } + } + // Load-time snapshot for the conditional persist. expectedStatus := identity.Status expectedNonce := "" @@ -350,10 +385,6 @@ func (s *IdentityService) challenge(ctx context.Context, identity *domain.Verifi return nil, domain.NewInternalError("CHALLENGE_GENERATION", "could not build signing input", err) } - verifier, err := s.verifierFor(identity.Kind) - if err != nil { - return nil, err - } challenges, err := verifier.Challenges(ctx, identity, signingInput) if err != nil { return nil, err @@ -369,10 +400,11 @@ func (s *IdentityService) challenge(ctx context.Context, identity *domain.Verifi } } return &IdentityChallengeResponse{ - Identity: identity, - Nonce: nonce, - ExpiresAt: identity.Challenge.ExpiresAt, - Challenges: challenges, + Identity: identity, + PresentationStatus: presentationStatus, + Nonce: nonce, + ExpiresAt: identity.Challenge.ExpiresAt, + Challenges: challenges, }, nil } diff --git a/internal/ra/service/identity_lei_test.go b/internal/ra/service/identity_lei_test.go new file mode 100644 index 0000000..7cd03af --- /dev/null +++ b/internal/ra/service/identity_lei_test.go @@ -0,0 +1,226 @@ +package service_test + +// lei (vLEI) lane tests for IdentityService: the register-time +// presentation (subject-AID pinning + LEI reconciliation), the single +// CESR-signature control proof, the live re-authorization at +// verify-control, and the AID+thumbprint seal. A programmable fake +// LEIControlVerifier stands in for the noop/real adapters so every +// failure code is reachable deterministically. + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "testing" + + "github.com/godaddy/ans/internal/domain" + "github.com/godaddy/ans/internal/port" + "github.com/godaddy/ans/internal/ra/service" + identityevent "github.com/godaddy/ans/internal/tl/event/identity" +) + +// the LEI the lei tests register; a valid 20-char LEI so the kind infers. +const testLEI = "5493001KJTIIGC8Y1R17" + +// fakeLEI is a programmable port.LEIControlVerifier. +type fakeLEI struct { + present port.PresentationResult + presentErr error + auth port.AuthorizationResult + authErr error + verifyOK bool + verifyErr error +} + +func (f *fakeLEI) Present(context.Context, string) (port.PresentationResult, error) { + return f.present, f.presentErr +} + +func (f *fakeLEI) Authorization(context.Context, string) (port.AuthorizationResult, error) { + return f.auth, f.authErr +} + +func (f *fakeLEI) VerifySignature(context.Context, string, string, string) (bool, error) { + return f.verifyOK, f.verifyErr +} + +// authorizedFakeLEI is the all-clear fake: presents the testLEI for AID +// "EHolderAID", authorizes it, and verifies any signature. +func authorizedFakeLEI() *fakeLEI { + return &fakeLEI{ + present: port.PresentationResult{SubjectAID: "EHolderAID", LEI: testLEI, Status: "AUTHORIZED"}, + auth: port.AuthorizationResult{Authorized: true, LEI: testLEI}, + verifyOK: true, + } +} + +func leiCode(t *testing.T, err error, want string) { + t.Helper() + var de *domain.Error + if !errors.As(err, &de) || de.Code != want { + t.Fatalf("want %s, got %v", want, err) + } +} + +func TestIdentityLifecycle_LEIHappy(t *testing.T) { + t.Parallel() + fx := newIdentityFixtureWithLEI(t, nil, authorizedFakeLEI()) + ctx := context.Background() + + // Register with the presentation → 202 with the advisory status and + // the single AID-kid challenge. + res, err := fx.svc.Register(ctx, fx.providerID, testLEI, + service.RegisterOptions{VLEIPresentation: "full-chain-cesr-blob"}) + if err != nil { + t.Fatalf("register: %v", err) + } + if res.Identity.Kind != domain.KindLEI { + t.Fatalf("kind = %s, want lei", res.Identity.Kind) + } + if res.PresentationStatus != "AUTHORIZED" { + t.Fatalf("presentation status = %q", res.PresentationStatus) + } + if len(res.Challenges) != 1 || res.Challenges[0].Kid != "EHolderAID" || res.Challenges[0].SigningInput == "" { + t.Fatalf("challenge shape: %+v", res.Challenges) + } + + // verify-control with the CESR signature → VERIFIED, seal emitted. + identity, err := fx.svc.VerifyControl(ctx, fx.providerID, res.Identity.IdentityID, + service.ProofSubmission{CESRSignature: "0Bcesr-signature-bytes"}) + if err != nil { + t.Fatalf("verify-control: %v", err) + } + if identity.Status != domain.IdentityVerified || identity.ProofMethod != "lei-vlei-acdc" { + t.Fatalf("verified state: %+v", identity) + } + + rows := fx.drainOutbox(t) + if len(rows) != 1 { + t.Fatalf("outbox rows: %d", len(rows)) + } + inner := fx.decodeOutboxEvent(t, rows[0]) + if inner.EventType != identityevent.TypeIdentityVerified || len(inner.Keys) != 1 { + t.Fatalf("sealed event: %+v", inner) + } + key := inner.Keys[0] + // The lei seal commits the subject AID as the id, a vLEI-KERI-AID + // type, and a base64url(SHA-256(AID)) thumbprint — no JWK, no doc. + if key.ID() != "EHolderAID" || key.SignedProof != "0Bcesr-signature-bytes" { + t.Fatalf("sealed key: id=%q proof=%q", key.ID(), key.SignedProof) + } + var vm struct { + ID string `json:"id"` + Type string `json:"type"` + Thumbprint string `json:"thumbprint"` + } + if err := json.Unmarshal(key.VerificationMethod, &vm); err != nil { + t.Fatalf("verification method not an object: %v", err) + } + wantThumb := base64.RawURLEncoding.EncodeToString(sha256Sum("EHolderAID")) + if vm.ID != "EHolderAID" || vm.Type != "vLEI-KERI-AID" || vm.Thumbprint != wantThumb { + t.Fatalf("sealed verification method: %+v", vm) + } +} + +func sha256Sum(s string) []byte { + sum := sha256.Sum256([]byte(s)) + return sum[:] +} + +func TestIdentityRegister_LEIFailures(t *testing.T) { + t.Parallel() + ctx := context.Background() + + t.Run("presentation required", func(t *testing.T) { + fx := newIdentityFixtureWithLEI(t, nil, authorizedFakeLEI()) + _, err := fx.svc.Register(ctx, fx.providerID, testLEI) + leiCode(t, err, "IDENTIFIER_PRESENTATION_REQUIRED") + }) + + t.Run("present error propagates", func(t *testing.T) { + fake := &fakeLEI{presentErr: domain.NewInternalError("LEI_VERIFIER_UNAVAILABLE", "down", nil)} + fx := newIdentityFixtureWithLEI(t, nil, fake) + _, err := fx.svc.Register(ctx, fx.providerID, testLEI, service.RegisterOptions{VLEIPresentation: "x"}) + leiCode(t, err, "LEI_VERIFIER_UNAVAILABLE") + }) + + t.Run("no subject AID", func(t *testing.T) { + fake := &fakeLEI{present: port.PresentationResult{LEI: testLEI, Status: "AUTHORIZED"}} + fx := newIdentityFixtureWithLEI(t, nil, fake) + _, err := fx.svc.Register(ctx, fx.providerID, testLEI, service.RegisterOptions{VLEIPresentation: "x"}) + leiCode(t, err, "LEI_PRESENTATION_INVALID") + }) + + t.Run("lei mismatch at presentation", func(t *testing.T) { + fake := &fakeLEI{present: port.PresentationResult{SubjectAID: "EAID", LEI: "OTHERLEI000000000000", Status: "AUTHORIZED"}} + fx := newIdentityFixtureWithLEI(t, nil, fake) + _, err := fx.svc.Register(ctx, fx.providerID, testLEI, service.RegisterOptions{VLEIPresentation: "x"}) + leiCode(t, err, "LEI_MISMATCH") + }) +} + +// registerLEI drives a lei identity to PENDING_CONTROL and returns the +// challenge response, for the verify-control failure cases. +func registerLEI(t *testing.T, fx *identityFixture) *service.IdentityChallengeResponse { + t.Helper() + res, err := fx.svc.Register(context.Background(), fx.providerID, testLEI, + service.RegisterOptions{VLEIPresentation: "x"}) + if err != nil { + t.Fatalf("register: %v", err) + } + return res +} + +func TestIdentityVerifyControl_LEIFailures(t *testing.T) { + t.Parallel() + ctx := context.Background() + + t.Run("missing cesr signature", func(t *testing.T) { + fx := newIdentityFixtureWithLEI(t, nil, authorizedFakeLEI()) + res := registerLEI(t, fx) + _, err := fx.svc.VerifyControl(ctx, fx.providerID, res.Identity.IdentityID, service.ProofSubmission{}) + leiCode(t, err, "IDENTIFIER_PROOF_INVALID") + }) + + t.Run("not authorized", func(t *testing.T) { + fake := authorizedFakeLEI() + fake.auth = port.AuthorizationResult{Authorized: false} + fx := newIdentityFixtureWithLEI(t, nil, fake) + res := registerLEI(t, fx) + _, err := fx.svc.VerifyControl(ctx, fx.providerID, res.Identity.IdentityID, + service.ProofSubmission{CESRSignature: "0Bsig"}) + leiCode(t, err, "LEI_NOT_AUTHORIZED") + }) + + t.Run("authorization lei mismatch", func(t *testing.T) { + fake := authorizedFakeLEI() + fake.auth = port.AuthorizationResult{Authorized: true, LEI: "OTHERLEI000000000000"} + fx := newIdentityFixtureWithLEI(t, nil, fake) + res := registerLEI(t, fx) + _, err := fx.svc.VerifyControl(ctx, fx.providerID, res.Identity.IdentityID, + service.ProofSubmission{CESRSignature: "0Bsig"}) + leiCode(t, err, "LEI_MISMATCH") + }) + + t.Run("signature does not verify", func(t *testing.T) { + fake := authorizedFakeLEI() + fake.verifyOK = false + fx := newIdentityFixtureWithLEI(t, nil, fake) + res := registerLEI(t, fx) + _, err := fx.svc.VerifyControl(ctx, fx.providerID, res.Identity.IdentityID, + service.ProofSubmission{CESRSignature: "0Bsig"}) + leiCode(t, err, "PRICC_SIGNATURE_INVALID") + }) + + t.Run("verify error propagates", func(t *testing.T) { + fake := authorizedFakeLEI() + fake.verifyErr = domain.NewInternalError("LEI_VERIFIER_UNAVAILABLE", "down", nil) + fx := newIdentityFixtureWithLEI(t, nil, fake) + res := registerLEI(t, fx) + _, err := fx.svc.VerifyControl(ctx, fx.providerID, res.Identity.IdentityID, + service.ProofSubmission{CESRSignature: "0Bsig"}) + leiCode(t, err, "LEI_VERIFIER_UNAVAILABLE") + }) +} diff --git a/internal/ra/service/identity_test.go b/internal/ra/service/identity_test.go index e9ad0a1..885d9eb 100644 --- a/internal/ra/service/identity_test.go +++ b/internal/ra/service/identity_test.go @@ -26,6 +26,7 @@ import ( "github.com/godaddy/ans/internal/adapter/didresolver" "github.com/godaddy/ans/internal/adapter/keymanager" + "github.com/godaddy/ans/internal/adapter/leiverifier" "github.com/godaddy/ans/internal/adapter/store/sqlite" anscrypto "github.com/godaddy/ans/internal/crypto" "github.com/godaddy/ans/internal/domain" @@ -105,8 +106,15 @@ type fakeClock struct{ now time.Time } func (c *fakeClock) Now() time.Time { return c.now } // newIdentityFixture wires the service against real SQLite + the -// given resolver (nil → noop). +// given resolver (nil → noop), with the noop lei verifier. func newIdentityFixture(t *testing.T, resolver port.DIDResolver) *identityFixture { + return newIdentityFixtureWithLEI(t, resolver, leiverifier.NewNoop()) +} + +// newIdentityFixtureWithLEI is newIdentityFixture with an injectable lei +// control verifier — the lei lane tests drive a programmable fake to +// reach every failure code deterministically. +func newIdentityFixtureWithLEI(t *testing.T, resolver port.DIDResolver, lei port.LEIControlVerifier) *identityFixture { t.Helper() db, err := sqlite.Open(context.Background(), ":memory:") if err != nil { @@ -137,6 +145,7 @@ func newIdentityFixture(t *testing.T, resolver port.DIDResolver) *identityFixtur sqlite.NewAgentStore(db), resolver, sealer, + lei, db, ).WithSigner(service.EventSigner{ KeyManager: km, @@ -325,10 +334,11 @@ func TestIdentityRegister_Rejections(t *testing.T) { !strings.Contains(err.Error(), "IDENTIFIER_KIND_UNSUPPORTED") { t.Errorf("bogus value: %v", err) } - // lei is recognized but postponed. + // lei is now enabled: a register with no presentation fails on the + // missing CESR, not on the kind being unsupported. if _, err := fx.svc.Register(ctx, fx.providerID, "5493001KJTIIGC8Y1R17"); err == nil || - !strings.Contains(err.Error(), "IDENTIFIER_KIND_UNSUPPORTED") { - t.Errorf("lei: %v", err) + !strings.Contains(err.Error(), "IDENTIFIER_PRESENTATION_REQUIRED") { + t.Errorf("lei without presentation: %v", err) } } @@ -1422,6 +1432,7 @@ func TestNilSealerFailsClosed(t *testing.T) { sqlite.NewAgentStore(db), didresolver.NewNoopResolver(), nil, // no sealer + leiverifier.NewNoop(), db, ) ctx := context.Background() diff --git a/internal/ra/service/identitykinds.go b/internal/ra/service/identitykinds.go index 19f7bad..45de40c 100644 --- a/internal/ra/service/identitykinds.go +++ b/internal/ra/service/identitykinds.go @@ -47,6 +47,7 @@ import ( "encoding/json" "fmt" "strings" + "time" anscrypto "github.com/godaddy/ans/internal/crypto" "github.com/godaddy/ans/internal/domain" @@ -62,6 +63,41 @@ type ProofSubmission struct { // and the future did:plc / did:ion): one compact JWS per proven // key, every payload equal to the served signingInput verbatim. SignedProofs []string + // CESRSignature is the lei (vLEI) proof: one CESR signature over + // the served signingInput, produced by the subject AID's current + // signing key. Set only for lei; the JWS kinds ignore it. + CESRSignature string +} + +// RegisterOptions carries the additive, per-kind material a register +// (or rotate) call may need beyond the identifier value. It is empty +// for kinds with no register-time presentation (did:web, did:key); +// lei populates VLEIPresentation. Additive by design — a new kind adds +// a member here, existing callers pass the zero value. +type RegisterOptions struct { + // VLEIPresentation is the lei full-chain CESR export submitted to + // the vlei-verifier at register time (the credential + KELs). The + // verifier derives the subject AID from it; the caller never + // asserts the AID. + VLEIPresentation string +} + +// presentationRegistrar is the optional capability a kind implements +// when it carries credential material at REGISTER time (lei's vLEI +// presentation). The service discovers it by type-assertion on the +// kind's controlVerifier — the same discover-by-capability pattern the +// 202 response uses for presentationStatus — so kinds with no +// register-time presentation (did:web, did:key) never grow a dead +// method. RegisterPresentation runs inside the shared challenge path, +// so an idempotent re-add (and a rotation) re-presents and refreshes +// the verifier's authorization window for free. +type presentationRegistrar interface { + // RegisterPresentation submits the kind's register-time credential + // material to its verifier, pins the derived subject identifier on + // the aggregate, reconciles it against the requested value, and + // returns the advisory presentation status ("AUTHORIZED" | + // "PENDING") for the 202 body. + RegisterPresentation(ctx context.Context, identity *domain.VerifiedIdentity, opts RegisterOptions, now time.Time) (string, error) } // controlVerifier is the per-kind control-proof gate — the design's @@ -86,14 +122,16 @@ type controlVerifier interface { // did:ion, and did:ethr slot in here when their verifiers are real; // until then domain.InferIdentifierKind may recognize a value's form // but the missing registry entry yields IDENTIFIER_KIND_UNSUPPORTED. -func newControlVerifiers(resolver port.DIDResolver) map[domain.IdentifierKind]controlVerifier { +func newControlVerifiers(resolver port.DIDResolver, leiCtl port.LEIControlVerifier) map[domain.IdentifierKind]controlVerifier { // NOTE: deliberately NOT exhaustive over IdentifierKind — a - // recognized-but-absent kind (lei, until its vlei-verifier - // integration ships) MUST fail with IDENTIFIER_KIND_UNSUPPORTED - // rather than register a stub. The 404-is-the-signal rule. - return map[domain.IdentifierKind]controlVerifier{ //nolint:exhaustive // absence == kind not enabled, by design + // recognized-but-absent kind (did:plc, did:ion, did:ethr, until + // their verifiers ship) MUST fail with IDENTIFIER_KIND_UNSUPPORTED + // rather than register a stub. The 404-is-the-signal rule. lei + // now registers — its noop adapter is the zero-infra quickstart. + return map[domain.IdentifierKind]controlVerifier{ domain.KindDIDWeb: &didWebVerifier{resolver: resolver}, domain.KindDIDKey: &didKeyVerifier{}, + domain.KindLEI: &leiVerifier{v: leiCtl}, } } diff --git a/internal/ra/service/leiverifier.go b/internal/ra/service/leiverifier.go new file mode 100644 index 0000000..f7b2ffb --- /dev/null +++ b/internal/ra/service/leiverifier.go @@ -0,0 +1,164 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/godaddy/ans/internal/domain" + "github.com/godaddy/ans/internal/port" + identityevent "github.com/godaddy/ans/internal/tl/event/identity" +) + +// leiVerifier is the lei (vLEI) controlVerifier — the per-kind gate +// behind the lei identifier kind. It owns no key state itself: every +// CESR/KERI question routes to the injected port.LEIControlVerifier +// (the noop quickstart adapter, or the real vlei-verifier HTTP client). +// +// lei differs from the JWS kinds in two structural ways, both absorbed +// behind the seam: +// +// - The credential presentation arrives at REGISTER time, so lei +// also implements presentationRegistrar: the shared challenge path +// submits the CESR, pins the verifier-derived subject AID on the +// aggregate, and reports the advisory presentation status. A +// re-add (or rotation) re-presents and refreshes the verifier's +// authorization window for free. +// - The proof is a single CESR signature over the served +// signingInput (not a JWS array), and the seal commits the subject +// AID + a thumbprint only — no JWK, no document. The KEL is the +// authoritative key history; the ACDC is PII. (event.go §lei seal +// exception.) +type leiVerifier struct { + v port.LEIControlVerifier +} + +// RegisterPresentation submits the register-time CESR to the verifier, +// pins the derived subject AID, and reconciles the credential's LEI +// against the requested value. Returns the advisory presentation +// status for the 202. +func (lv *leiVerifier) RegisterPresentation( + ctx context.Context, + identity *domain.VerifiedIdentity, + opts RegisterOptions, + now time.Time, +) (string, error) { + if opts.VLEIPresentation == "" { + return "", domain.NewValidationError("IDENTIFIER_PRESENTATION_REQUIRED", + "lei registration requires vleiPresentation.cesr") + } + res, err := lv.v.Present(ctx, opts.VLEIPresentation) + if err != nil { + return "", err + } + if res.SubjectAID == "" { + return "", domain.NewValidationError("LEI_PRESENTATION_INVALID", + "the vlei verifier returned no subject AID for the presentation") + } + // Reconcile the presented LEI against the registered value. The + // noop adapter waives the AID↔LEI binding and returns an empty LEI + // (the documented quickstart waiver, mirroring noop-DNS); skip the + // equality check in that case. + if res.LEI != "" && !strings.EqualFold(res.LEI, identity.EffectiveValue()) { + return "", domain.NewValidationError("LEI_MISMATCH", + fmt.Sprintf("presented credential authorizes LEI %q, not %q", res.LEI, identity.EffectiveValue())) + } + if err := identity.SetSubjectAID(res.SubjectAID, now); err != nil { + return "", err + } + return res.Status, nil +} + +// Challenges returns the single lei challenge entry: the pinned +// subject AID as the kid, the served signingInput as the payload to +// sign. RegisterPresentation has already run (same challenge path), so +// the subject AID is pinned on the aggregate. +func (lv *leiVerifier) Challenges( + _ context.Context, + identity *domain.VerifiedIdentity, + signingInput string, +) ([]ProofChallenge, error) { + if identity.SubjectAID == "" { + return nil, domain.NewInternalError("LEI_SUBJECT_AID_MISSING", + "subject AID was not pinned before challenge", nil) + } + return []ProofChallenge{{Kid: identity.SubjectAID, SigningInput: signingInput}}, nil +} + +// VerifyProofs runs the lei control proof: a LIVE authorization +// re-check against the verifier (the register-time status is +// advisory), then a CESR signature verification over the served +// signingInput by the pinned subject AID's current key. Seals one +// ProvenKey = subject AID + thumbprint (no JWK, no document). +func (lv *leiVerifier) VerifyProofs( + ctx context.Context, + identity *domain.VerifiedIdentity, + sub ProofSubmission, + signingInput string, +) ([]identityevent.ProvenKey, error) { + if sub.CESRSignature == "" { + return nil, domain.NewValidationError("IDENTIFIER_PROOF_INVALID", "cesrSignature is required") + } + aid := identity.SubjectAID + if aid == "" { + return nil, domain.NewInvalidStateError("LEI_SUBJECT_AID_MISSING", + "no subject AID is pinned; re-register the identifier with its presentation") + } + + auth, err := lv.v.Authorization(ctx, aid) + if err != nil { + return nil, err + } + if !auth.Authorized { + return nil, domain.NewValidationError("LEI_NOT_AUTHORIZED", + "the vlei verifier does not currently authorize this AID") + } + if auth.LEI != "" && !strings.EqualFold(auth.LEI, identity.EffectiveValue()) { + return nil, domain.NewValidationError("LEI_MISMATCH", + fmt.Sprintf("the AID is authorized for LEI %q, not %q", auth.LEI, identity.EffectiveValue())) + } + + ok, err := lv.v.VerifySignature(ctx, aid, signingInput, sub.CESRSignature) + if err != nil { + return nil, err + } + if !ok { + return nil, domain.NewValidationError("PRICC_SIGNATURE_INVALID", + "the CESR signature does not verify against the subject AID's current key") + } + + vm, err := json.Marshal(map[string]string{ + "id": aid, + "type": "vLEI-KERI-AID", + "thumbprint": aidThumbprint(aid), + }) + if err != nil { + return nil, domain.NewInternalError("PROOF_SEAL", "could not build lei verification method", err) + } + return []identityevent.ProvenKey{{ + VerificationMethod: vm, + SignedProof: sub.CESRSignature, + }}, nil +} + +// aidThumbprint is the sealed key fingerprint for a lei proof: +// base64url(SHA-256(subjectAID)). The subject AID is itself a KERI +// self-addressing identifier (a digest of the holder's inception key +// state), so a hash over it is a stable, content-bound fingerprint — +// the AID+thumbprint pair is what the seal commits in lieu of a JWK +// (the KEL is the authoritative key history; see event.go §lei seal). +func aidThumbprint(aid string) string { + sum := sha256.Sum256([]byte(aid)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +// compile-time conformance: lei implements both the control gate and +// the register-time presentation capability. +var ( + _ controlVerifier = (*leiVerifier)(nil) + _ presentationRegistrar = (*leiVerifier)(nil) +) diff --git a/scripts/demo/start.sh b/scripts/demo/start.sh index e265581..1f14d78 100755 --- a/scripts/demo/start.sh +++ b/scripts/demo/start.sh @@ -206,6 +206,19 @@ identity: type: ${ANS_IDENTITY_RESOLVER:-noop} challenge-ttl: 1h +vlei: + # The lei (vLEI) control verifier behind the "lei" identifier kind. + # "noop" runs real Ed25519 crypto but waives the GLEIF authorization + # binding; "verifier" routes CESR/KERI questions to a real + # vlei-verifier (scripts/demo/vlei brings one up on :7676). The + # base-url can't be set via ANS_RA_VLEI__BASE_URL — koanf maps a + # single underscore literally, so it would target vlei.base_url, not + # vlei.base-url — hence it is composed into the file here: + # ANS_VLEI_TYPE=verifier ANS_VLEI_BASE_URL=http://localhost:7676 \ + # scripts/demo/start.sh + type: ${ANS_VLEI_TYPE:-noop} + base-url: "${ANS_VLEI_BASE_URL:-}" + keys: type: file file: diff --git a/scripts/demo/vlei/README.md b/scripts/demo/vlei/README.md new file mode 100644 index 0000000..7f2a5c5 --- /dev/null +++ b/scripts/demo/vlei/README.md @@ -0,0 +1,262 @@ +# vLEI ecosystem + identifier / `verify-control` demo + +This directory stands up a **local, self-contained** GLEIF/KERI stack so +a genuine AID holding a (self-issued) vLEI can be registered with the RA +on the identity-scoped routes — `POST /v2/ans/identities` (carrying the +full-chain CESR) + `.../verify-control` — and the RA can present it to, +and verify the AID-signed `signingInput` against, a **real +`vlei-verifier`**, seal the `IDENTITY_VERIFIED` event on the TL, and link +the verified `lei` identity to an agent. + +Proves the *RA integration* against the stock +GLEIF verifier, including the credential-chain / authorized-LEI check. + +## No genuine LEI/vLEI required + +The entire ecosystem is self-issued against a **synthetic local GLEIF +root** registered via `POST /root_of_trust/{aid}` (the verifier runs +with `VERIFIER_ENV=development`, `VERIFY_ROOT_OF_TRUST=True`). The LEI is +any well-formed 20-char string you choose — the verifier checks the +chain to *your* local root, not `api.gleif.org`. The RA's `ValidateLEI` +checks ISO-17442 **format only** (20-char `[A-Z0-9]`), so any well-formed +string works; `build-chain.ts` uses LEI `875500ELOZEL05BVXV37`. + +A genuine vLEI is needed *only* if you point the verifier at the real +GLEIF production root — out of scope here. + +## Notes +- **Everything is version-pinned for reproducibility.** GLEIF's + KERI/KERIA/vLEI images and the `vlei-verifier` config schema move + between releases, so the compose file pins every image to a known-good + tag (`weboftrust/keri:1.2.0-rc4`, `gleif/vlei:1.0.0`, + `gleif/keria:0.3.0`) and builds the verifier from the `0.1.5` source. + The verifier uses its own bundled `verifier-config-docker-local.json` + (keri-style `iurls`/`durls` pointing at `witness-demo` + `vlei-server`), + so there is no local config file to keep in sync. Bumping any pin means + re-confirming flags/endpoints and the config shape against that release. +- **The RA is the single touchpoint for the verifier.** The holder hands + the RA their full-chain credential CESR via the `vleiPresentation` of + `POST /v2/ans/identities`; the RA reads the leaf credential SAID out of + it (the only thing it parses — never KERI key state), presents the chain + to the verifier (`PUT /presentations/{said}`), reads the verifier-reported + subject AID, and pins it on the identity. The holder never calls the + verifier directly. The one bootstrap the RA can't do is registering the + *synthetic local* GLEIF root of trust — that is a one-time admin step + against the verifier (`build-chain.ts` does it). + +## Components (`docker-compose.yml`) + +| Service | Image | Ports | Role | +|---|---|---|---| +| `witnesses` | `weboftrust/keri:1.2.0-rc4` | 5642-5644 | KERI witness network (key-event logs) | +| `vlei-server` | `gleif/vlei:1.0.0` | 7723 | ACDC schema + OOBI server (LE/OOR/ECR/QVI) | +| `keria` | `gleif/keria:0.3.0` | 3901-3903 | KERIA edge agent for the holder (signify-ts) | +| `vlei-verifier` | built from source @ `0.1.5` | **7676** | the service `ans-ra` calls | +| `signify` | `denoland/deno:alpine-2.8.2` | — | runs `build-chain.ts` (build chain, present, export) and `sign-proof.ts` | + +> `vlei-verifier` is not published to any registry, so the compose file +> builds it from the pinned [`GLEIF-IT/vlei-verifier`](https://github.com/GLEIF-IT/vlei-verifier) +> `0.1.5` tag via a git build context. The first `up.sh` therefore runs a +> `docker build` (git clone + `pip install`) that takes a few minutes; later +> runs reuse the cached `ans-vlei-verifier:0.1.5` image. The verifier loads +> its **bundled** `verifier-config-docker-local.json` (selected via +> `VERIFIER_CONFIG_FILE`), which already points at this stack's `witness-demo` +> and `vlei-server` hostnames — there is no local config file to edit. + +> **The SignifyTS runner is self-contained.** The `signify` service is the +> stock `denoland/deno` image — no custom build. It bind-mounts +> [`signify/`](signify/) in this directory, which holds the demo's +> [`scripts_ts/`](signify/scripts_ts/): `build-chain.ts` (the trust-chain build, +> converted from the old `ans-vlei-verifier.ipynb`), `sign-proof.ts` (the +> standalone proof signer), and `utils.ts` (the SignifyTS helpers, vendored from +> [GLEIF-IT/vlei-trainings](https://github.com/GLEIF-IT/vlei-trainings)). The +> container is on the same Docker network as the rest of the stack and reaches +> `keria`, `vlei-server`, `witness-demo`, and `vlei-verifier` by service name — +> no external network / `docker network connect` required. On start it pre-caches +> the npm deps (`signify-ts`, `libsodium`) so the first `deno run` is fast. The +> exported artifacts land in [`signify/out/`](signify/out/) via the bind mount. +> When re-vendoring, re-pull `utils.ts` from the upstream repo. + +## End-to-end sequence + +### Prerequisites (the RA — once) + +The vLEI stack is self-contained, but the RA owns its own lifecycle, so two +RA-side steps happen first: + +1. **Enable the verifier wiring.** Set the `vlei:` block in + `config/ra-local.yaml` to the real verifier (it ships as `type: noop`): + ```yaml + vlei: + type: verifier + base-url: "http://localhost:7676" + ``` + The identity routes (`POST /v2/ans/identities`, `.../verify-control`, + `.../links`) are always registered — `did:web`/`did:key` use them too. + `vlei.type` only selects which control verifier backs the `lei` kind: + `noop` runs real Ed25519 crypto but waives the GLEIF authorization + binding (zero-infra quickstart), while `verifier` routes every + CESR/KERI question to this stack's `vlei-verifier`. The real end-to-end + flow below requires `type: verifier`. +2. **Start the RA and register an agent.** `scripts/demo/start.sh` starts + `ans-ra`; `scripts/demo/run-lifecycle.sh` registers an agent and writes its + id to `data/demo/vlei/last-agent-id`. That id is the `AGENT_ID` below. + +### Commands + +```bash +ANS_VLEI_TYPE=verifier ANS_VLEI_BASE_URL=http://localhost:7676 ./scripts/demo/start.sh +AGENT_ID=$(scripts/demo/register.sh --v2) +scripts/demo/vlei/run-vlei.sh +``` + +`run-vlei.sh` checks the RA is reachable, then chains the three steps below +with **no manual paste**: + +1. **`up.sh`** — build + start the whole stack (witnesses, vlei-server, KERIA, + vlei-verifier, signify Deno runner) on one Docker network; wait for the + verifier's `/health` (`:7676`) and for the `signify` container to finish + pre-caching its deps. The first run includes a `docker build` of the + verifier image and the signify container's npm-dep download, which together + take a few minutes; later runs reuse the cached image and deps. +2. **`build-chain.sh`** — run [`build-chain.ts`](signify/scripts_ts/build-chain.ts) + via `deno run` in the `signify` container. It builds the synthetic + `GLEIF → QVI(delegated) → LE → ECR` chain, issues the ECR to the `role` + holder AID (LEI `875500ELOZEL05BVXV37`), presents it via IPEX, **registers + the local `gleif` root of trust** at the verifier, and exports two files into + the bind-mounted [`signify/out/`](signify/out/) dir: + - `ecr-presentation.json` — `{cesr, lei, aid}` the shell hands to the RA; + - `tier1-outputs.json` — carries the holder's `roleBran` for the signer. +3. **`verify-control-demo.sh`** (invoked with `AUTO_SIGN=1` and `DATA` pointed + at `build-chain.ts`'s exports) — the RA-mediated register + verify-control flow: + - `POST /v2/ans/identities { value: , vleiPresentation:{ cesr } }` — the + RA reads the leaf SAID, presents the chain to the verifier, pins the + verifier-reported subject AID, and returns the challenge round (nonce + + `signingInput`) plus the advisory `presentationStatus`; + - **auto-sign** — runs [`sign-proof.ts`](signify/scripts_ts/sign-proof.ts) + inside the `signify` container, reconstructing `roleClient` from the + exported `roleBran` and signing the served `signingInput` with the `role` + AID's KERIA-held keys; + - **re-present** — re-POST the same body while `PENDING_CONTROL` to refresh + the verifier's authorization window (same `identityId`, fresh nonce); + - `POST .../verify-control { cesrSignature }` — **no aid in the body**; the + RA pins the signer AID to the identity → expects `status: VERIFIED`, + then polls the TL for the sealed `IDENTITY_VERIFIED`; + - `POST .../links { agentIds: [ ] }` then + `GET /v2/ans/agents/` → the computed `identities[]` badge + carries the verified `lei` identity. + +Add `--down` to tear the stack down after a successful run. + +### Step by step / fallback + +Each stage is runnable on its own: + +```bash +scripts/demo/vlei/up.sh # stack +scripts/demo/vlei/build-chain.sh # headless chain build + export +AGENT_ID= DATA=scripts/demo/vlei/signify/out \ + AUTO_SIGN=1 scripts/demo/vlei/verify-control-demo.sh # present + verify +scripts/demo/vlei/down.sh # tear down +``` + +**Manual signing fallback.** To sign by hand, run `verify-control-demo.sh` +**without** `AUTO_SIGN`: it prints the served `signingInput`, then prints the +exact `deno run … sign-proof.ts ` command to sign it +in the `signify` container. Run that, copy the printed signature (indexed Siger +qb64, e.g. `AAB…`), and paste it back at the prompt. You can also pass a +signature non-interactively with `SIGNED_PROOF=`. + +The `lei` control proof is uniform with the JWS kinds: every kind signs the +served `signingInput` (the base64url of the JCS-canonical `IdentityProofInput`, +which binds the nonce, the identity id, the identifier, and the proof purpose). +The RA forwards the signature to the verifier as `non_prefixed_digest = signingInput`. + +**The 10-minute authorization window.** The `vlei-verifier` ages credential +authorizations off after `TimeoutAuth = 600s`. `verify-control` re-checks +authorization **live** on every call, so a slow manual signing step can lapse +the window and surface as `LEI_NOT_AUTHORIZED` even with a valid signature. The +script re-presents the chain (the idempotent re-add) immediately before the +verify to reset the window; if you still hit it, just re-run. + +**Registering the root of trust by hand.** `build-chain.sh` registers it for +you; if the verifier was restarted (its DB is in-container and ephemeral) and +you need to re-register without re-running the chain build, the raw call is: +```bash +curl -X POST http://localhost:7676/root_of_trust/{gleifRootAID} \ + -H 'Content-Type: application/json' \ + -d '{"vlei":"","oobi":""}' +``` + +## Troubleshooting + +### Step 1 (QVI Credential) fails with `unknown AID` + +Symptom — the IPEX grant in *Step 1* dies with: + +``` +HTTP POST /identifiers/gleif/ipex/grant - 400 Bad Request +{"description": "attempt to send to unknown AID="} +``` + +and the keria container loops forever on: + +``` +ERROR eventing .processEscrowDelegables Kevery unescrow failed: No delegation seal found for event. +keri.kering.MissingDelegableApprovalError: No delegation seal found for event. +INFO routing .acceptReply Revery: escrowing without key state for signer on reply ... +``` + +**Cause.** A *previous* run approved the QVI delegation incorrectly — e.g. +older setup code using `identifiers().interact()` (which only anchors +the seal) instead of `delegations().approve()` (which also ingests the +QVI's `dip`). That leaves a QVI `dip` that can never be promoted, churning +in gleif's `delegables` escrow. Because `gleif` uses a **fixed bran** (so +the same gleif agent is reused on every run) and the compose file mounts +**no data volume** for keria (agent DBs live in the container's ephemeral +writable layer), this poison survives across runs — and a plain +`docker compose restart keria` does **not** clear it (same container, same +writable layer). + +**Fix.** Recreate the keria container to wipe all agent state, then re-run +the chain build: + +```bash +docker compose -f scripts/demo/vlei/docker-compose.yml \ + up -d --force-recreate keria +``` + +gleif comes back with the **same prefix** (it is deterministic from the +fixed bran), so any root-of-trust registration still matches. Then just +re-run `scripts/demo/vlei/build-chain.sh`. `build-chain.ts` already uses +`delegations().approve()` in a retry loop, so on a clean keria the +delegation completes and the QVI credential grants/admits cleanly. + +### Benign noise + +`Unverified loc scheme reply URL=… SAID=…` (a `/loc/scheme` reply, often +with a `dt` of `2024-12-31`) is **not** an error you need to chase — it is +transient witness-resolution churn that self-resolves once the witness KEL +loads. Only delegation/escrow errors (`MissingDelegableApprovalError`, +`escrowing without key state`) indicate the poisoned-agent state above. + +## Scope + +This implements the **RA-mediated register-with-presentation + +verify-control** flow for the `lei` identifier kind on the identity-scoped +`/v2/ans/identities` routes: + +- The RA is the single touchpoint for the verifier: `POST /v2/ans/identities` + carries the holder's full-chain CESR in `vleiPresentation`, the RA presents + it and pins the verifier-reported subject AID on the identity; + `.../verify-control` is a CESR-signature proof over the served `signingInput` + that **pins the signer AID to the identity** — never a request-body value. +- On a clean verify the RA seals an `IDENTITY_VERIFIED` event on the identity's + TL stream (the demo polls the TL identity audit for it), and `.../links` + binds the verified `lei` identity to an agent so it surfaces in the agent's + computed `identities[]` badge. +- The seal commits the subject AID + a thumbprint only (no JWK, no document): + the KEL-backed key state lives at the verifier, so a `lei` seal is **not** + offline-re-verifiable from the seal alone — the documented `lei` trust + boundary (`ans-verify` enforces the AID+thumbprint shape, not an offline + signature re-check). diff --git a/scripts/demo/vlei/build-chain.sh b/scripts/demo/vlei/build-chain.sh new file mode 100755 index 0000000..14443f3 --- /dev/null +++ b/scripts/demo/vlei/build-chain.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# +# Build the vLEI trust chain headless, inside the signify (Deno) container. +# +# Runs build-chain.ts: the trust-chain build, ECR issuance, IPEX present, local +# root-of-trust registration, and the holder-state export. No notebook/kernel — +# it is plain SignifyTS run by Deno. +# +# On success build-chain.ts has written, into the bind-mounted out dir +# (host: scripts/demo/vlei/signify/out/): +# - ecr-presentation.json {cesr, lei, aid} consumed by verify-control-demo.sh +# - tier1-outputs.json {roleBran, ...} consumed by the nonce signer +# +# Usage: +# scripts/demo/vlei/build-chain.sh +# +# Env overrides: +# COMPOSE docker compose command (default: "docker compose") +# SCRIPT build script path inside the container (default: scripts_ts/build-chain.ts) + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../common.sh +. "$SCRIPT_DIR/../common.sh" + +COMPOSE="${COMPOSE:-docker compose}" +COMPOSE_FILE="$SCRIPT_DIR/docker-compose.yml" +SCRIPT="${SCRIPT:-scripts_ts/build-chain.ts}" +OUT_DIR="$SCRIPT_DIR/signify/out" + +require_cmd docker + +header "Building the vLEI trust chain headless — $SCRIPT" + +# Run the build script in the signify container. -A grants the file/net +# permissions the SignifyTS flow needs; the container is on the stack network so +# keria / vlei-server / witness-demo / vlei-verifier resolve by service name. +# shellcheck disable=SC2086 # COMPOSE may be a multi-word command +$COMPOSE -f "$COMPOSE_FILE" exec -T signify deno run -A "$SCRIPT" + +ok "build script executed" + +# Assert the exported artifacts landed on the host via the bind mount. +for f in ecr-presentation.json tier1-outputs.json; do + if [ ! -s "$OUT_DIR/$f" ]; then + fail "expected $OUT_DIR/$f to exist and be non-empty after the run — check the output above" + fi + ok "wrote $f" +done + +header "Chain build complete" +note "ecr-presentation.json + tier1-outputs.json are in $OUT_DIR" +note "next: $SCRIPT_DIR/verify-control-demo.sh (or run-vlei.sh for the full flow)" diff --git a/scripts/demo/vlei/docker-compose.yml b/scripts/demo/vlei/docker-compose.yml new file mode 100644 index 0000000..dc842bc --- /dev/null +++ b/scripts/demo/vlei/docker-compose.yml @@ -0,0 +1,206 @@ +# vLEI ecosystem for the ans verify-control demo. +# +# Brings up a self-contained, LOCAL GLEIF/KERI stack so a genuine AID +# holding a (self-issued) vLEI can sign the RA's nonce and the RA's +# verify-control endpoint can verify it against a real `vlei-verifier`. +# +# NO genuine LEI/vLEI is required: the whole chain is self-issued +# against a synthetic local GLEIF root registered via +# POST /root_of_trust/{aid} (VERIFIER_ENV=development). The LEI is any +# well-formed 20-char string; the verifier checks the chain to YOUR +# local root, not api.gleif.org. +# +# Image pinning: the sibling images are pinned to known-good tags for +# reproducibility (GLEIF's KERI/KERIA/vLEI images move fast and +# flag/endpoint shapes vary by release). The vlei-verifier image is NOT +# published to any registry — upstream builds it locally — so we build +# it from the pinned `0.1.5` source via a git build context and let it +# use its own bundled `verifier-config-docker-local.json`. See README.md. + +services: + # KERI witness network — irreducible: chain-walk needs the key-event + # logs. Exposes three demo witnesses (wan/wil/wes) on 5642-5644. + witnesses: + # Pinned to the same keripy the verifier is built on + # (verifier.dockerfile: FROM weboftrust/keri:1.2.0-rc4). `kli witness + # demo` mints the canonical wan/wil/wes demo AIDs the verifier's + # bundled config resolves at boot. + image: weboftrust/keri:1.2.0-rc4 + container_name: ans-vlei-witnesses + # The verifier's bundled verifier-config-docker-local.json resolves + # witness OOBIs at host `witness-demo`; alias this service to match. + networks: + default: + aliases: + - witness-demo + environment: + - PYTHONUNBUFFERED=1 + - PYTHONIOENCODING=UTF-8 + # `kli witness demo` reads each witness's config from + # scripts/keri/cf/main/.json (Configer headDirPath="scripts", + # WORKDIR /keripy). Without these files the witnesses advertise no + # reachable `curls`, so KERIA — in its own container — resolves their + # KELs but has "no http endpoint" to request receipts from, and AID + # inception hangs. These configs point each witness's curls at the + # `witness-demo` network alias so KERIA can reach them. + # Mounted read-write: keripy's Configer opens the config directory + # read-write (lock files), and a read-only mount makes it silently + # fall back to an empty ~/.keri/cf/main, leaving the witnesses with + # no curls again. + volumes: + - ./witness-config/main:/keripy/scripts/keri/cf/main + # weboftrust/keri's ENTRYPOINT is already `kli`; pass only its args. + command: + - witness + - demo + ports: + - "5642:5642" + - "5643:5643" + - "5644:5644" + # weboftrust/keri ships no curl; use the bundled python3 to probe the + # witness HTTP endpoint (127.0.0.1 to avoid IPv6-localhost refusal). + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:5642/oobi',timeout=3).status==200 else 1)"] + interval: 5s + timeout: 3s + retries: 30 + + # vLEI schema server — serves the ACDC schemas (LE/OOR/ECR/QVI) that + # the credential chain is typed against, on 7723. + vlei-server: + image: gleif/vlei:1.0.0 + container_name: ans-vlei-server + environment: + - PYTHONUNBUFFERED=1 + # Use the image's default entrypoint command (vLEI-server -s /vLEI/schema + # -c /vLEI/credentials -o /vLEI/oobis). Overriding the paths breaks schema + # OOBI resolution — gleif/vlei:1.0.0 ships schemas under /vLEI/schema, and + # the verifier's durls fail to parse an empty body if they're not served. + ports: + - "7723:7723" + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:7723/health"] + interval: 5s + timeout: 3s + retries: 30 + + # KERIA edge agent — hosts the holder's cloud agent so the signify scripts + # (build-chain.ts / sign-proof.ts) can incept the holder AID, resolve OOBIs, + # and receive/present credentials. Admin 3901, boot 3903. + keria: + image: gleif/keria:0.3.0 + container_name: ans-vlei-keria + environment: + - KERIA_CURLS=http://keria:3902/ + - PYTHONUNBUFFERED=1 + # gleif/keria's ENTRYPOINT is already `keria`; pass only its args. + # Mounted read-write: KERIA opens this config via + # configing.Configer(reopen=True), and a read-only mount makes it + # silently fall back to an empty ~/.keri/cf/keria.json — dropping the + # `iurls`. KERIA copies those iurls into every new agent's config at + # creation, which is how each agent bootstraps the witness endpoints. + # Without them, only AIDs whose client explicitly resolves the witness + # OOBIs can be incepted; the rest fail with "unknown witness". + volumes: + - ./keria-docker.json:/keria/config/keri/cf/keria.json + command: + - start + - --config-dir + - /keria/config + - --config-file + - keria + - --name + - agent + - --loglevel + - DEBUG + ports: + - "3901:3901" + - "3902:3902" + - "3903:3903" + depends_on: + witnesses: + condition: service_healthy + vlei-server: + condition: service_healthy + + # GLEIF vlei-verifier — the service ans-ra calls. development env so + # the local GLEIF root can be registered via POST /root_of_trust/{aid}; + # VERIFY_ROOT_OF_TRUST=True enables chain-to-root verification. + vlei-verifier: + # Not published to any registry — built from the pinned 0.1.5 source. + # The entrypoint reads VERIFIER_CONFIG_FILE and loads keri-style config + # from scripts/keri/cf/.json baked into the image; we point it at + # the bundled verifier-config-docker-local.json, which already targets + # our witness-demo + vlei-server hostnames. + build: + context: https://github.com/GLEIF-IT/vlei-verifier.git#0.1.5 + dockerfile: images/verifier.dockerfile + image: ans-vlei-verifier:0.1.5 + container_name: ans-vlei-verifier + environment: + # development env + VERIFY_ROOT_OF_TRUST enable POST /root_of_trust/{aid} + # so the local synthetic GLEIF root can be registered. + - VERIFIER_ENV=development + - VERIFY_ROOT_OF_TRUST=True + - VERIFIER_CONFIG_FILE=verifier-config-docker-local.json + - PYTHONUNBUFFERED=1 + ports: + - "7676:7676" + depends_on: + witnesses: + condition: service_healthy + vlei-server: + condition: service_healthy + # Built on weboftrust/keri (no curl); probe /health with python3. + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:7676/health',timeout=3).status==200 else 1)"] + interval: 5s + timeout: 3s + retries: 30 + + # Deno / SignifyTS runner — executes build-chain.ts (build the synthetic vLEI + # trust chain, issue the ECR to the holder AID, present it, register the local + # GLEIF root of trust, export the artifacts) and sign-proof.ts (sign the RA's + # verify-control signingInput with the holder AID). No Jupyter/notebook layer — the + # demo logic is plain SignifyTS run by Deno. On the same default network as + # the rest of the stack, so the scripts reach `keria`, `vlei-server`, + # `witness-demo`, and `vlei-verifier` by service name — no external network / + # `docker network connect` required. + # + # Pinned to a known-good Deno (GLEIF's KERI/KERIA/vLEI images move fast and so + # do their SignifyTS-facing shapes); bump deliberately. The container idles on + # `tail -f /dev/null` so build-chain.sh / verify-control-demo.sh can + # `docker compose exec` `deno run` into it; the npm deps are pre-cached at + # start so the first exec is fast and a `/tmp/ready` marker gates up.sh. + signify: + image: denoland/deno:alpine-2.8.2 + container_name: ans-vlei-signify + working_dir: /app + environment: + # Persist Deno's module cache inside the container for the session so the + # second exec (sign-proof.ts) reuses build-chain.ts's downloads. + - DENO_DIR=/deno-dir + # Bind the signify dir so edits are live AND the exported artifacts + # (out/ecr-presentation.json, out/tier1-outputs.json) land on the host for + # the shell demo to consume. + volumes: + - ./signify:/app + # Pre-cache npm deps, drop a readiness marker, then idle so the container + # stays available for `docker compose exec deno run`. + command: + - sh + - -c + - "deno cache scripts_ts/build-chain.ts scripts_ts/sign-proof.ts && touch /tmp/ready && tail -f /dev/null" + depends_on: + # keria has no healthcheck (it gates on witnesses + vlei-server itself); + # build-chain.ts retries against KERIA via signify's own operation waits. + keria: + condition: service_started + vlei-verifier: + condition: service_healthy + healthcheck: + test: ["CMD", "test", "-f", "/tmp/ready"] + interval: 5s + timeout: 3s + retries: 60 + restart: unless-stopped diff --git a/scripts/demo/vlei/down.sh b/scripts/demo/vlei/down.sh new file mode 100755 index 0000000..001f156 --- /dev/null +++ b/scripts/demo/vlei/down.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# +# Tear down the vLEI ecosystem. +# +# Usage: +# scripts/demo/vlei/down.sh # stop + remove containers +# KEEP_VOLUMES=1 scripts/demo/vlei/down.sh # keep named volumes +# +# Env overrides: +# COMPOSE docker compose command (default: "docker compose") + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +export DATA="${DATA:-$(cd "$SCRIPT_DIR/../../.." && pwd)/data/demo/vlei}" +# shellcheck source=../../common.sh +. "$SCRIPT_DIR/../common.sh" + +COMPOSE="${COMPOSE:-docker compose}" + +require_cmd docker + +header "vLEI ecosystem — down" + +DOWN_ARGS=(down --remove-orphans) +if [ "${KEEP_VOLUMES:-0}" != "1" ]; then + DOWN_ARGS+=(--volumes) +fi + +# shellcheck disable=SC2086 # COMPOSE may be a multi-word command +$COMPOSE -f "$SCRIPT_DIR/docker-compose.yml" "${DOWN_ARGS[@]}" +ok "stack stopped" diff --git a/scripts/demo/vlei/keria-docker.json b/scripts/demo/vlei/keria-docker.json new file mode 100755 index 0000000..250da36 --- /dev/null +++ b/scripts/demo/vlei/keria-docker.json @@ -0,0 +1,15 @@ +{ + "keria": { + "dt": "2024-12-31T14:06:30.123456+00:00", + "curls": ["http://keria:3902/"] + }, + "dt": "2024-12-31T14:06:30.123456+00:00", + "iurls": [ + "http://witness-demo:5642/oobi/BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha/controller?name=wan&tag=witness&tag=sample", + "http://witness-demo:5643/oobi/BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM/controller?name=wil&tag=witness&tag=sample", + "http://witness-demo:5644/oobi/BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX/controller?name=wes&tag=witness&tag=sample", + "http://witness-demo:5645/oobi/BM35JN8XeJSEfpxopjn5jr7tAHCE5749f0OobhMLCorE/controller?name=wit&tag=witness&tag=sample", + "http://witness-demo:5646/oobi/BIj15u5V11bkbtAxMA7gcNJZcax-7TgaBMLsQnMHpYHP/controller?name=wub&tag=witness&tag=sample", + "http://witness-demo:5647/oobi/BF2rZTW79z4IXocYRQnjjsOuvFUQv-ptCf8Yltd7PfsM/controller?name=wyz&tag=witness&tag=sample" + ] +} \ No newline at end of file diff --git a/scripts/demo/vlei/run-vlei.sh b/scripts/demo/vlei/run-vlei.sh new file mode 100755 index 0000000..4caffbb --- /dev/null +++ b/scripts/demo/vlei/run-vlei.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# +# One-command vLEI verify-control demo. +# +# Chains the whole self-contained flow: +# 1. up.sh — bring up the stack (witnesses, vlei-server, KERIA, +# vlei-verifier, signify Deno runner) on one network. +# 2. build-chain.sh — run build-chain.ts headless: build the synthetic +# vLEI trust chain, issue the ECR to the holder AID, +# present it, register the local GLEIF root of trust, +# and export ecr-presentation.json + tier1-outputs.json. +# 3. verify-control-demo.sh (AUTO_SIGN=1) — RA-mediated register + +# verify-control on /v2/ans/identities, signing the +# served signingInput in-container with the holder +# (role) AID, then linking the verified lei identity +# to the agent. No manual paste. +# +# The RA is NOT started here — it owns its own lifecycle (config + agent +# registration). This script requires it already running with an agent +# registered; it checks both up front and points you at the right script if not. +# +# Usage: +# AGENT_ID=$(scripts/demo/register.sh --v2) +# scripts/demo/vlei/run-vlei.sh [--down] +# +# Required env: +# AGENT_ID a registered ans agent id (e.g. from scripts/demo/register.sh +# +# Flags: +# --down tear the stack down (down.sh) after a successful run. +# +# Env overrides: +# COMPOSE docker compose command (default: "docker compose") +# RA_URL ans-ra base URL (default: http://localhost:18080) + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../common.sh +. "$SCRIPT_DIR/../common.sh" + +TEARDOWN=0 +for arg in "$@"; do + case "$arg" in + --down) TEARDOWN=1 ;; + *) fail "unknown argument: $arg (supported: --down)" ;; + esac +done + +OUT_DIR="$SCRIPT_DIR/signify/out" + +# AGENT_ID: from env +[ -n "${AGENT_ID:-}" ] || fail "set AGENT_ID — register an agent first (scripts/demo/register.sh)" + +header "vLEI verify-control demo — full run" +note "agent: $AGENT_ID RA: $RA_URL" + +# Fail fast if the RA isn't reachable, before standing the stack up. +if ! curl -sSf "$RA_URL/v2/admin/ready" >/dev/null 2>&1; then + fail "ans-ra isn't reachable at $RA_URL — run scripts/demo/start.sh first (and ensure the vlei: block in config/ra-local.yaml is enabled)" +fi +ok "ans-ra ready at $RA_URL" + +# 1. stack up +"$SCRIPT_DIR/up.sh" + +# 2. build the chain (headless): build chain, present, register root, export artifacts +"$SCRIPT_DIR/build-chain.sh" + +# 3. RA-mediated register + verify-control, auto-signing the signingInput +# in-container. DATA points the verify script at build-chain.ts's exported +# artifacts so it finds both ecr-presentation.json and tier1-outputs.json there. +AGENT_ID="$AGENT_ID" DATA="$OUT_DIR" AUTO_SIGN=1 "$SCRIPT_DIR/verify-control-demo.sh" + +if [ "$TEARDOWN" = "1" ]; then + "$SCRIPT_DIR/down.sh" +fi + +header "All done" +note "vLEI control proven end-to-end with no manual steps." diff --git a/scripts/demo/vlei/signify/out/ecr-presentation.json b/scripts/demo/vlei/signify/out/ecr-presentation.json new file mode 100644 index 0000000..27b66f6 --- /dev/null +++ b/scripts/demo/vlei/signify/out/ecr-presentation.json @@ -0,0 +1,5 @@ +{ + "cesr": "{\"v\":\"KERI10JSON0001b7_\",\"t\":\"icp\",\"d\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DOt6-9xBMvmyS9PmGVz3useCtbqJpuB3Yn-kMuaVRgH8\"],\"nt\":\"1\",\"n\":[\"EObUbg8u1gHxkwI33ZFIQzD4XFZQYNZQaerBpnvjSrBk\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[]}-VBq-AABAACW9PoEPZf9gtkUKUVCjY-3eThjE5YjZDxsSiyoAks_cuXlBXLPNiiodpHfsSgrH3ipkCpnt1Y3CoujtfpQjNQE-BADAAAK0Ci5-Vmb-w6030xkAxaMp5xbGt2Bx8T_BGnApUs3sDOGd0DSlW2GX8oGuKxY3hzLvSJEdcLLBGA-PLJ79WIAABAtpfJUYldswt3-YFDzlVfiBJsX4NMPbzhdLRKABHnlIPJEHj4Fc4pllzQll2XE2OrxhjAlTVCU3fH2fB2isy4AACAA4a3VsrCUGNSAO4qsGI5pobaceOfDJ7-STIrnQHd93NolKoKvNoz0nlmeHnBUBsz6nbDOWWramc9kk8kZgLwK-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d775436p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EAlosSU9P_6SG9rV9UhCf-xZ0TA-Q1xrJc6eFn4PWoEB\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"1\",\"p\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"a\":[{\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"0\",\"d\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\"}]}-VBq-AABAADgWppEnWN4KKZG3uxj5yze6h56gLSw9B3q3PrU-oUs4KOybPGSMmwSrgNnW5irQKtcRbyDNryadvrsD0RuvkQN-BADAADogN3qPVG4Wr10tNbzapl7_6u6q30E7HYPR2D9jPMZnWN_0KyIBt3sC1HeicBk7hiUqR0r4_Co3WfhQtIC1yYDABCc3MfcaYrl8L68bJhZuCH86UKsL1Mq_MsradrFMds0bcGC-7Y2698ekZuDH8R_SovKpkI7SdimYq-ffuewKd0LACCnIie-9_bPrDGuo23NfGcpYoT-zyPv_urgvjL7kjDBSC9KqNlfMCRxov8vsWPjkz42WXTrCGlEU4XEtO-1sq0N-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c15d778006p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"ENeuCZc-nwXwgI6-Q8L6RTvwqi7i9yqy3nqin7jH7dpw\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"2\",\"p\":\"EAlosSU9P_6SG9rV9UhCf-xZ0TA-Q1xrJc6eFn4PWoEB\",\"a\":[{\"i\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"s\":\"0\",\"d\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\"}]}-VBq-AABAAB0yD2ShRLE9bVA_sGR-fPw-wtcKuJVDdD6kvGHm9tyWR6HgJbBv_nlogSNQqnNeH0NRQLl18fKWhgxtYCTxoAP-BADAAATdsAgl8nIYBs2MDZvkQczgGjht20YOKgjfItz6BoAgGedMrS8JrZiOwINJ27ClV_g5pm12lxh9cyFv-Lv42YIABA2fr7H6fhaGrT3fvMWCEjpgjXlPi2ueusgDxO5WHftHeDXQAJPu7oWh6arKnD5ssUtYjJzJgJEh9yIraW2ci0AACDbNruEWQwrLOu4hPit65IxOh3UTlZJnieb6_Jn5ASa5to0X2CofwWo6nqlpSRCdSGB5eU51kQkHRnteNtb7iUB-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d319587p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EPpu0lh5fmbgWxrvRsDDNf0FhWXRBq7ckOZ95yGndJWl\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"3\",\"p\":\"ENeuCZc-nwXwgI6-Q8L6RTvwqi7i9yqy3nqin7jH7dpw\",\"a\":[{\"i\":\"EFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o\",\"s\":\"0\",\"d\":\"ECTZS9gF3NefkoXtXvL2dpP8OUSMYKQ2ODJtgv1uSedF\"}]}-VBq-AABAAAXbFIZjN6jviJfvO9aSG1XBlN_JTbbQOC4AVL48WALG4sawm3KL7SnQ11cLV1syJ_VFE2j3DdA_ydc6GodKlkE-BADAABjvthGNIZQ9q1oWclwfO3iUDut-CGi-GcHpAcW1JvXmgurbycqdKmBALeHsbbwTj0bK5IAqelk35ydrkFHMZgLABCNEZJ5l_ng1C5O_4-u4asrILdPi2rHcn-a7unX_RCqWc8QAGtrrPMN9CJ72qrv75YFNAF1jiiGLsC3Z42W7dIFACCD7OP5FKI-uD9Z9Rs3I3iLH3hrDXAN49Gu8d58woevKtpnPTt-8qD1DhDTjCL4yrXVaQit-nYo7DlItYrXs18A-EAB0AAAAAAAAAAAAAAAAAAAAAAD1AAG2026-06-11T05c26c38d348177p00c00{\"v\":\"KERI10JSON0001eb_\",\"t\":\"dip\",\"d\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DAK3yw9yruQOKWaEhJnMhASzNhTigNnpO05bZS6bON94\"],\"nt\":\"1\",\"n\":[\"ED9axlzJGRSShmIi5aT8acvww12urlP9qvL24Us7A1OA\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[],\"di\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\"}-VB8-AABAAALRoR4Q2Hdzq2I_KqR7Wq_1gbIMXhGNov4uaqUUr-sfdssr2msqrTQB3PnT16uSPoVzYY0IxHYl3iMSuhGf24E-BADAAC2L3XNeFndkopThWUGQPLghSatuQsLv0625cUlzmol3z42SlyruPJwxlm2RCjWqP6YQXhBLz6y-bT3L7e9n7kGABDRaDmi96BFrH2M508U4V54DNUUFYRqpI8tAjpubZW1umbsy6pe1K3o8GN_8aCv3MislfDZin5bsmqQqrLSWGoFACAjUiD_HUbhv0kkKS1o6IvCGa-csVkr5HvCHdhauJnJstYgObPjYcDqR7ixggGHmiZwadDf0uexIjukSHcS_UIK-GAB0AAAAAAAAAAAAAAAAAAAAAABEAlosSU9P_6SG9rV9UhCf-xZ0TA-Q1xrJc6eFn4PWoEB-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d780613p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"1\",\"p\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"a\":[{\"i\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"s\":\"0\",\"d\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\"}]}-VBq-AABAAB-zwO_a7m8TPQt70fZ_k12dL26cgOvB0by7JnyLu9ySizIvSZnTZ2px2WH8ARCKdAvOMHQvbS8Dkym4VlXSG8E-BADAAAnklHaQ9uraB__CqEfoDNliVPGUq5S0Hc2d9Ov8ixxshNVLCfnFlMusDPP_jv-kHCYVnkFUUu9cjiBZZeKYXECABC0wtUMJZx-bHnP-MZ7Y3VEo8AGP6u1CGY5H0aFcgnLPFqtuApz2tYkFRhrVs73XMhe3-8OPKG4FS060cPHP-wJACCB4oF2sMyA0eYrzPj6ukIM-jWDZMIwBtAqQ6mY610OFVCMEEGI71UBxIWJu4oVKT-Wgt4PYy31HnBJJauusPYB-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c38d413917p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EEO5ecpf-eQIX5kHGkYamO96wWWblQlwVgZnVckBJLGn\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"2\",\"p\":\"EAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_\",\"a\":[{\"i\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"s\":\"0\",\"d\":\"EAaMenfuD8insWq_MqOqntu_L0acrmL4RwHHqTwsClZs\"}]}-VBq-AABAADr7pniHv6hYHPTHl9U5uoNKzrjFuv8mlDr-hC682oooA_vnLAzCiu8r017VY5Ef6BNaLB-_6jZKoErAEQj_d8I-BADAAByP1LwRjvVYm2IHjbo4wyOjZg30ZEca5afzuT8gLbF8czYzl5Skgji-kkpJef3r-8kRghEM_wR-wfN7Z76jgwJABCcRVg8b9GbE4RA4QWnt4P6k_gUzHY9YqNOHhOQfFQlSou2vywzhcP9qTEfg8wTrPtIFvaCZBeX4XuB7xNeyhkAACCw2j_DgzVOpTctykyLrcU5lMWha_gsLn_IUYIKwabdgNK-p3i1vpKUwInE1k1q8_XyvIw43Pks9n0UL_G4fMAK-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d443212p00c00{\"v\":\"KERI10JSON000113_\",\"t\":\"vcp\",\"d\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"i\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"ii\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"0\",\"c\":[\"NB\"],\"bt\":\"0\",\"b\":[],\"n\":\"AJz_M1jOToVGPDIJBSjeDKA19kDFn9hSnXwwMzb38zFS\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAACENeuCZc-nwXwgI6-Q8L6RTvwqi7i9yqy3nqin7jH7dpw{\"v\":\"KERI10JSON0000ed_\",\"t\":\"iss\",\"d\":\"ECTZS9gF3NefkoXtXvL2dpP8OUSMYKQ2ODJtgv1uSedF\",\"i\":\"EFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o\",\"s\":\"0\",\"ri\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"dt\":\"2026-06-11T05:26:18.944000+00:00\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAADEPpu0lh5fmbgWxrvRsDDNf0FhWXRBq7ckOZ95yGndJWl{\"v\":\"ACDC10JSON000197_\",\"d\":\"EFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"ri\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"s\":\"EBfdlu8R27Fbx-ehrqwImnK-8Cm79sqbAQ4MmvEAYqao\",\"a\":{\"d\":\"EGw2h5vW3OEcki0tOcAnxBRD_8bwZ8qwwawVLXzRuzzb\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"LEI\":\"254900OPPU84GM83MG36\",\"dt\":\"2026-06-11T05:26:18.944000+00:00\"}}-IABEFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o0AAAAAAAAAAAAAAAAAAAAAAAECTZS9gF3NefkoXtXvL2dpP8OUSMYKQ2ODJtgv1uSedF{\"v\":\"KERI10JSON0001eb_\",\"t\":\"dip\",\"d\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DAK3yw9yruQOKWaEhJnMhASzNhTigNnpO05bZS6bON94\"],\"nt\":\"1\",\"n\":[\"ED9axlzJGRSShmIi5aT8acvww12urlP9qvL24Us7A1OA\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[],\"di\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\"}-VB8-AABAAALRoR4Q2Hdzq2I_KqR7Wq_1gbIMXhGNov4uaqUUr-sfdssr2msqrTQB3PnT16uSPoVzYY0IxHYl3iMSuhGf24E-BADAAC2L3XNeFndkopThWUGQPLghSatuQsLv0625cUlzmol3z42SlyruPJwxlm2RCjWqP6YQXhBLz6y-bT3L7e9n7kGABDRaDmi96BFrH2M508U4V54DNUUFYRqpI8tAjpubZW1umbsy6pe1K3o8GN_8aCv3MislfDZin5bsmqQqrLSWGoFACAjUiD_HUbhv0kkKS1o6IvCGa-csVkr5HvCHdhauJnJstYgObPjYcDqR7ixggGHmiZwadDf0uexIjukSHcS_UIK-GAB0AAAAAAAAAAAAAAAAAAAAAABEAlosSU9P_6SG9rV9UhCf-xZ0TA-Q1xrJc6eFn4PWoEB-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d780613p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"1\",\"p\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"a\":[{\"i\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"s\":\"0\",\"d\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\"}]}-VBq-AABAAB-zwO_a7m8TPQt70fZ_k12dL26cgOvB0by7JnyLu9ySizIvSZnTZ2px2WH8ARCKdAvOMHQvbS8Dkym4VlXSG8E-BADAAAnklHaQ9uraB__CqEfoDNliVPGUq5S0Hc2d9Ov8ixxshNVLCfnFlMusDPP_jv-kHCYVnkFUUu9cjiBZZeKYXECABC0wtUMJZx-bHnP-MZ7Y3VEo8AGP6u1CGY5H0aFcgnLPFqtuApz2tYkFRhrVs73XMhe3-8OPKG4FS060cPHP-wJACCB4oF2sMyA0eYrzPj6ukIM-jWDZMIwBtAqQ6mY610OFVCMEEGI71UBxIWJu4oVKT-Wgt4PYy31HnBJJauusPYB-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c38d413917p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EEO5ecpf-eQIX5kHGkYamO96wWWblQlwVgZnVckBJLGn\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"2\",\"p\":\"EAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_\",\"a\":[{\"i\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"s\":\"0\",\"d\":\"EAaMenfuD8insWq_MqOqntu_L0acrmL4RwHHqTwsClZs\"}]}-VBq-AABAADr7pniHv6hYHPTHl9U5uoNKzrjFuv8mlDr-hC682oooA_vnLAzCiu8r017VY5Ef6BNaLB-_6jZKoErAEQj_d8I-BADAAByP1LwRjvVYm2IHjbo4wyOjZg30ZEca5afzuT8gLbF8czYzl5Skgji-kkpJef3r-8kRghEM_wR-wfN7Z76jgwJABCcRVg8b9GbE4RA4QWnt4P6k_gUzHY9YqNOHhOQfFQlSou2vywzhcP9qTEfg8wTrPtIFvaCZBeX4XuB7xNeyhkAACCw2j_DgzVOpTctykyLrcU5lMWha_gsLn_IUYIKwabdgNK-p3i1vpKUwInE1k1q8_XyvIw43Pks9n0UL_G4fMAK-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d443212p00c00{\"v\":\"KERI10JSON0001b7_\",\"t\":\"icp\",\"d\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DHK3QY22__M-g-r6aenExqCZDkrDDjYAS4D9QNHDPIoS\"],\"nt\":\"1\",\"n\":[\"ENaBPETNOtxW0qFWWuM9ik-EWvkwjdkbBxszCdTAMWOw\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[]}-VBq-AABAADN_CZ_3eoMeBeDbUPG5u8mqT5xuGLUxnM-rkXEEv6P8vKygh5SgR4zwCrtSDZP9-DBqt1bXIBuUeKX4A0LzrQG-BADAABkb-TucbxzyCG2WSBXWG1pZdJj7YBAN7VSxuKrJ8eID4rHIivv62F8NjCBPHFR_WkJUJEfpT0jfJoi3TYkr9gKABD7MM1UJsZzDcwF-eCOQsIGhQ6QtrPaFdui7u-woPHeO6MUiYyIEsDRqFesa64RojvndtHgPwCglsDfhBIv3-AFACAHyigAReA-PblfZmNmgoXswdE1IRAJRKXHEe9u_Tm0vKjNaQ9ytBVwSifp-9Q-s38jtgXfvI-waLNiBVXANjgE-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d763350p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"1\",\"p\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"a\":[{\"i\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"s\":\"0\",\"d\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\"}]}-VBq-AABAABOHeZrhLDPHUoB-vcLhPGVNaSzZpRXaigmVoHEDH7at2JGc9ywO1upEF9vciH_hZNQAfoqeRUziuuZ52rYX0IF-BADAADgcyIB0_J2TjU3ynQWBv6Bf5bAiIRKsDz_3Ceiwxea79EVnZ_42LZro5KsNEmAz3i9xA4BRKBUYoNELDX1AlMKABDTobQWaJhKPowsE03sbZQR2k-vDLwpX_EXdv5-jg-zhoe6Rhvza0O2nFN2Yva4IH7IerVuzfdngeJODHVtqzgEACDIB7f13YZPWBqg94cJ8ti67ils6gXqNeLpUOVAiirvMZCMv7Dm5A4bVzIqKhuvlRhCx1srU7HNDIvx-qZsxxMJ-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c38d128107p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EPJ3yPRSBaDntd5YhrHzuSdMQtke7tm_rr0MJS0AAozM\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"2\",\"p\":\"EH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5\",\"a\":[{\"i\":\"EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo\",\"s\":\"0\",\"d\":\"EBHKMw2yQzRQqZuPa0xahKYhDUNlneTaEYiW176B3j6J\"}]}-VBq-AABAAC9_eSk2dI6Bd2kHTKFEyySUxocBK6KPfdvX-EyVgS-KYYIfAWUcp9bJXkI6yaMzOxi_DRm5MhtbCnKdiz3Rj4F-BADAAC2ONz9D2E_K7QKZyCyMD9yOEz8v3iLiOWNh7PWx7sLOa-3hjog79U3R539XiiMXMXg4KR1WxKi7nHzKwpAW5kPABAYuUlJ_fToLiqCILPVAe8NFsq_4Gpw6KVHIyexr2S5Mi-D-90RVtfGyTjQ3H5z2o8387YWhMr81tCigFjh9DYIACDp1-50CHrZERSwtpOiueHxceipF4bQf9o8oButC4Au_IjIPiOAHkqglbU2eCdIs5dGnIbd5Te5p0fX97-m8FYA-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d160699p00c00{\"v\":\"KERI10JSON000113_\",\"t\":\"vcp\",\"d\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"i\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"ii\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"0\",\"c\":[\"NB\"],\"bt\":\"0\",\"b\":[],\"n\":\"AJVgZbUEagvvBdKPc-VXOhdKwIc-vYLPnfukzFtZsImS\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAABEAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_{\"v\":\"KERI10JSON0000ed_\",\"t\":\"iss\",\"d\":\"EAaMenfuD8insWq_MqOqntu_L0acrmL4RwHHqTwsClZs\",\"i\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"s\":\"0\",\"ri\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"dt\":\"2026-06-11T05:26:27.161000+00:00\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAACEEO5ecpf-eQIX5kHGkYamO96wWWblQlwVgZnVckBJLGn{\"v\":\"ACDC10JSON0005c8_\",\"d\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"ri\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"s\":\"ENPXp1vQzRF6JwIuS-mp2U8Uf1MoADoP_GqQ62VsDZWY\",\"a\":{\"d\":\"ECakQY3CY0BAdwD-gCe-2Jurs7WibLea3ilNtZBdBi2X\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"LEI\":\"875500ELOZEL05BVXV37\",\"dt\":\"2026-06-11T05:26:27.161000+00:00\"},\"e\":{\"d\":\"EFyuG5XkRQkOKfHcubrp9cNTXkKrLdKTPSFky1ntcedI\",\"qvi\":{\"n\":\"EFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o\",\"s\":\"EBfdlu8R27Fbx-ehrqwImnK-8Cm79sqbAQ4MmvEAYqao\"}},\"r\":{\"d\":\"EGZ97EjPSINR-O-KHDN_uw4fdrTxeuRXrqT5ZHHQJujQ\",\"usageDisclaimer\":{\"l\":\"Usage of a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, does not assert that the Legal Entity is trustworthy, honest, reputable in its business dealings, safe to do business with, or compliant with any laws or that an implied or expressly intended purpose will be fulfilled.\"},\"issuanceDisclaimer\":{\"l\":\"All information in a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, is accurate as of the date the validation process was complete. The vLEI Credential has been issued to the legal entity or person named in the vLEI Credential as the subject; and the qualified vLEI Issuer exercised reasonable care to perform the validation process set forth in the vLEI Ecosystem Governance Framework.\"}}}-IABED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni0AAAAAAAAAAAAAAAAAAAAAAAEAaMenfuD8insWq_MqOqntu_L0acrmL4RwHHqTwsClZs{\"v\":\"KERI10JSON0001b7_\",\"t\":\"icp\",\"d\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DHK3QY22__M-g-r6aenExqCZDkrDDjYAS4D9QNHDPIoS\"],\"nt\":\"1\",\"n\":[\"ENaBPETNOtxW0qFWWuM9ik-EWvkwjdkbBxszCdTAMWOw\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[]}-VBq-AABAADN_CZ_3eoMeBeDbUPG5u8mqT5xuGLUxnM-rkXEEv6P8vKygh5SgR4zwCrtSDZP9-DBqt1bXIBuUeKX4A0LzrQG-BADAABkb-TucbxzyCG2WSBXWG1pZdJj7YBAN7VSxuKrJ8eID4rHIivv62F8NjCBPHFR_WkJUJEfpT0jfJoi3TYkr9gKABD7MM1UJsZzDcwF-eCOQsIGhQ6QtrPaFdui7u-woPHeO6MUiYyIEsDRqFesa64RojvndtHgPwCglsDfhBIv3-AFACAHyigAReA-PblfZmNmgoXswdE1IRAJRKXHEe9u_Tm0vKjNaQ9ytBVwSifp-9Q-s38jtgXfvI-waLNiBVXANjgE-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d763350p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"1\",\"p\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"a\":[{\"i\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"s\":\"0\",\"d\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\"}]}-VBq-AABAABOHeZrhLDPHUoB-vcLhPGVNaSzZpRXaigmVoHEDH7at2JGc9ywO1upEF9vciH_hZNQAfoqeRUziuuZ52rYX0IF-BADAADgcyIB0_J2TjU3ynQWBv6Bf5bAiIRKsDz_3Ceiwxea79EVnZ_42LZro5KsNEmAz3i9xA4BRKBUYoNELDX1AlMKABDTobQWaJhKPowsE03sbZQR2k-vDLwpX_EXdv5-jg-zhoe6Rhvza0O2nFN2Yva4IH7IerVuzfdngeJODHVtqzgEACDIB7f13YZPWBqg94cJ8ti67ils6gXqNeLpUOVAiirvMZCMv7Dm5A4bVzIqKhuvlRhCx1srU7HNDIvx-qZsxxMJ-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c38d128107p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EPJ3yPRSBaDntd5YhrHzuSdMQtke7tm_rr0MJS0AAozM\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"2\",\"p\":\"EH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5\",\"a\":[{\"i\":\"EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo\",\"s\":\"0\",\"d\":\"EBHKMw2yQzRQqZuPa0xahKYhDUNlneTaEYiW176B3j6J\"}]}-VBq-AABAAC9_eSk2dI6Bd2kHTKFEyySUxocBK6KPfdvX-EyVgS-KYYIfAWUcp9bJXkI6yaMzOxi_DRm5MhtbCnKdiz3Rj4F-BADAAC2ONz9D2E_K7QKZyCyMD9yOEz8v3iLiOWNh7PWx7sLOa-3hjog79U3R539XiiMXMXg4KR1WxKi7nHzKwpAW5kPABAYuUlJ_fToLiqCILPVAe8NFsq_4Gpw6KVHIyexr2S5Mi-D-90RVtfGyTjQ3H5z2o8387YWhMr81tCigFjh9DYIACDp1-50CHrZERSwtpOiueHxceipF4bQf9o8oButC4Au_IjIPiOAHkqglbU2eCdIs5dGnIbd5Te5p0fX97-m8FYA-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d160699p00c00{\"v\":\"KERI10JSON0001b7_\",\"t\":\"icp\",\"d\":\"EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ\",\"i\":\"EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DENUslY77aNd5ez5mQGnZLQi9YJSKCt2mer8mPCjHeNx\"],\"nt\":\"1\",\"n\":[\"EIVDLsI2ulIfhIlHlH-kCKqtiuCw_Pc642I0r98_Qo8u\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[]}-VBq-AABAABmYlUzVzuGTJXFr3zviRAPWtQHStBe2tLowYqNzjuAzpK5gknf0udEIiHZ-o_RPF2KrnjA5XCwA7zZVe2p57AF-BADAADOS7aLgNlCYnR1dO1Lfldd-MYBYiQHOtg32HDb0PTw7FEx2WEX5POITVnIeJWAHXlM137x9llZEh2t7LGP2GsNABAeSCw0ycKP_VDqkZxOBGM8e-L7Tsup1VJ3E_GzxQRM98YHgN5i1P0VZz7qTNi9NDHx7aVef8KZf2nrV3DdA90LACAfXhTVWETo3mxgdvv0vFtCt4uA7ls-TappbNRYtyC_7sYrlBwOyaUVSJwRy9ni3BGTpJUbHUDwTdxM_FcsSsYO-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c14d690903p00c00{\"v\":\"KERI10JSON000113_\",\"t\":\"vcp\",\"d\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"i\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"ii\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"0\",\"c\":[\"NB\"],\"bt\":\"0\",\"b\":[],\"n\":\"AMfztkZztZR2U0MFg-ee2Ln_OnMSo_FeLiZKdz_5f--M\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAABEH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5{\"v\":\"KERI10JSON0000ed_\",\"t\":\"iss\",\"d\":\"EBHKMw2yQzRQqZuPa0xahKYhDUNlneTaEYiW176B3j6J\",\"i\":\"EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo\",\"s\":\"0\",\"ri\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"dt\":\"2026-06-11T05:26:35.317000+00:00\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAACEPJ3yPRSBaDntd5YhrHzuSdMQtke7tm_rr0MJS0AAozM{\"v\":\"ACDC10JSON0007dc_\",\"d\":\"EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo\",\"u\":\"0ABn4IzwUDKKhmE7QsLHRaP4\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"ri\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"s\":\"EEy9PkikFcANV1l7EHukCeXqrzT1hNZjGlUk7wuMO5jw\",\"a\":{\"d\":\"EMQbEw2G0VSZN9DJuH5nyXRGMq4Ry6BesBykVDxGJPWt\",\"i\":\"EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ\",\"LEI\":\"875500ELOZEL05BVXV37\",\"personLegalName\":\"John Doe\",\"engagementContextRole\":\"Managing Director\",\"dt\":\"2026-06-11T05:26:35.317000+00:00\"},\"e\":{\"d\":\"EN-tndHWF0jJITEJYL2-iyif-yk-spZ_PZcfBvsv6NEk\",\"le\":{\"n\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"s\":\"ENPXp1vQzRF6JwIuS-mp2U8Uf1MoADoP_GqQ62VsDZWY\"}},\"r\":{\"d\":\"EIfq_m1DI2IQ1MgHhUl9sq3IQ_PJP9WQ1LhbMscngDCB\",\"usageDisclaimer\":{\"l\":\"Usage of a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, does not assert that the Legal Entity is trustworthy, honest, reputable in its business dealings, safe to do business with, or compliant with any laws or that an implied or expressly intended purpose will be fulfilled.\"},\"issuanceDisclaimer\":{\"l\":\"All information in a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, is accurate as of the date the validation process was complete. The vLEI Credential has been issued to the legal entity or person named in the vLEI Credential as the subject; and the qualified vLEI Issuer exercised reasonable care to perform the validation process set forth in the vLEI Ecosystem Governance Framework.\"},\"privacyDisclaimer\":{\"l\":\"It is the sole responsibility of Holders as Issuees of an ECR vLEI Credential to present that Credential in a privacy-preserving manner using the mechanisms provided in the Issuance and Presentation Exchange (IPEX) protocol specification and the Authentic Chained Data Container (ACDC) specification. https://github.com/WebOfTrust/IETF-IPEX and https://github.com/trustoverip/tswg-acdc-specification.\"}}}-IABEHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo0AAAAAAAAAAAAAAAAAAAAAAAEBHKMw2yQzRQqZuPa0xahKYhDUNlneTaEYiW176B3j6J", + "lei": "875500ELOZEL05BVXV37", + "aid": "EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ" +} \ No newline at end of file diff --git a/scripts/demo/vlei/signify/out/tier1-outputs.json b/scripts/demo/vlei/signify/out/tier1-outputs.json new file mode 100644 index 0000000..1f32957 --- /dev/null +++ b/scripts/demo/vlei/signify/out/tier1-outputs.json @@ -0,0 +1,8 @@ +{ + "gleifPrefix": "EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk", + "rolePrefix": "EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ", + "roleBran": "DWvi_zlnWH8sKWYLEsSh1", + "LEI": "875500ELOZEL05BVXV37", + "ecrCredentialSaid": "EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo", + "gleifOOBI": "http://keria:3902/oobi/EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk/agent/ENvos4PmBAa28ZTPKVrSgtXZ3bRhgRP_zpRk0Q914d2L" +} \ No newline at end of file diff --git a/scripts/demo/vlei/signify/scripts_ts/build-chain.ts b/scripts/demo/vlei/signify/scripts_ts/build-chain.ts new file mode 100644 index 0000000..56631bf --- /dev/null +++ b/scripts/demo/vlei/signify/scripts_ts/build-chain.ts @@ -0,0 +1,459 @@ +// ============================================================================ +// ANS demo. +// +// Builds the synthetic GLEIF → QVI(delegated) → LE → ECR vLEI trust chain, +// issues the ECR to the holder (role) AID, presents it via IPEX, registers the +// LOCAL synthetic GLEIF root of trust at the vlei-verifier, and exports the two +// artifacts the shell demo consumes: +// - out/ecr-presentation.json {cesr, lei, aid} → verify-control-demo.sh +// - out/tier1-outputs.json {roleBran, ...} → the nonce signer +// +// This is the headless equivalent of the old Jupyter notebook — same SignifyTS +// logic, no notebook/kernel layer. The interactive sign cell is gone entirely; +// sign-proof.ts is the standalone signer (run by verify-control-demo.sh). +// +// USAGE (inside the signify container, on the stack's docker network): +// deno run -A scripts_ts/build-chain.ts +// +// Service hostnames (keria, vlei-server, witness-demo, vlei-verifier) resolve +// because the container shares the compose default network — see utils.ts. +// ============================================================================ + +import "npm:libsodium-wrappers-sumo@0.7.15"; +import { randomPasscode, Saider } from "npm:signify-ts@^0.3.0-rc1"; +import { + initializeSignify, + initializeAndConnectClient, + createNewAID, + addEndRoleForAID, + generateOOBI, + resolveOOBI, + createCredentialRegistry, + issueCredential, + ipexGrantCredential, + waitForAndGetNotification, + ipexAdmitGrant, + markNotificationRead, + DEFAULT_IDENTIFIER_ARGS, + ROLE_AGENT, + IPEX_GRANT_ROUTE, + IPEX_ADMIT_ROUTE, + SCHEMA_SERVER_HOST, + prTitle, + prMessage, + prContinue, + sleep, +} from "./utils.ts"; + +const OUT_DIR = "out"; +const VERIFIER_URL = "http://vlei-verifier:7676"; + +const WITNESS_OOBIS = [ + { url: "http://witness-demo:5642/oobi/BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha/controller?name=wan&tag=witness", alias: "wan" }, + { url: "http://witness-demo:5643/oobi/BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM/controller?name=wil&tag=witness", alias: "wil" }, + { url: "http://witness-demo:5644/oobi/BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX/controller?name=wes&tag=witness", alias: "wes" }, +]; + +async function resolveWitnesses(client, who: string) { + for (const w of WITNESS_OOBIS) { + await resolveOOBI(client, w.url, `${who}-${w.alias}`); + } + prMessage(`Resolved witnesses for ${who}`); +} + +// Cross-step state. Each issuance step is wrapped in its own block so its local +// consts (credentialSaid, grantResponse, …) don't collide across steps; the +// credentials and the LE claim flow forward through these module-scope `let`s. +let qviCredential; +let leCredential; +let ecrCredential; +let leData; + +// --------------------------------------------------------------------------- +// Setup Phase — create the four actor clients/AIDs, OOBIs, and registries. +// --------------------------------------------------------------------------- +await initializeSignify(); + +prTitle("Creating clients setup"); + +// Fixed Bran to keep a consistent root of trust (DO NOT MODIFY or else +// validation with the verifier will break — the registered root AID is +// deterministic from this bran). +const gleifBran = "Dm8Tmz05CF6_JLX9sVlFe"; +const gleifAlias = "gleif"; +const { client: gleifClient } = await initializeAndConnectClient(gleifBran); +await resolveWitnesses(gleifClient, "gleif"); +let gleifPrefix; + +// GLEIF GEDA setup. GLEIF is the root, so it stays a plain (non-delegated) +// AID — the root of trust we register with the verifier. +try { + const gleifAid = await gleifClient.identifiers().get(gleifAlias); + gleifPrefix = gleifAid.prefix; +} catch { + prMessage("Creating GLEIF AID"); + const { aid: newAid } = await createNewAID(gleifClient, gleifAlias, DEFAULT_IDENTIFIER_ARGS); + await addEndRoleForAID(gleifClient, gleifAlias, ROLE_AGENT); + gleifPrefix = newAid.i; +} +const gleifOOBI = await generateOOBI(gleifClient, gleifAlias, ROLE_AGENT); +prMessage(`GLEIF Prefix: ${gleifPrefix}`); + +// QVI — DELEGATED by GLEIF. The vlei-verifier requires the QVI AID to be a +// delegated identifier whose delegator is the registered Root Of Trust (gleif). +const qviBran = randomPasscode(); +const qviAlias = "qvi"; +const { client: qviClient } = await initializeAndConnectClient(qviBran); +await resolveWitnesses(qviClient, "qvi"); // qvi's agent must know the witnesses +await resolveOOBI(qviClient, gleifOOBI, gleifAlias); // ...and the delegator's (gleif) KEL + +// 1. qvi initiates a delegated inception (delpre = gleif). The operation stays +// pending until the delegator anchors its approval. +const qviIcpResult = await qviClient.identifiers().create(qviAlias, { + delpre: gleifPrefix, + toad: DEFAULT_IDENTIFIER_ARGS.toad, + wits: DEFAULT_IDENTIFIER_ARGS.wits, +}); +const qviPrefix = qviIcpResult.serder.pre; +const qviIcpOp = await qviIcpResult.op(); +prMessage(`QVI delegated inception pending gleif approval: ${qviPrefix}`); + +// 2. gleif (the delegator) APPROVES the delegation. This MUST use +// delegations().approve() (POST /identifiers/gleif/delegation), NOT +// identifiers().interact(). Only the /delegation endpoint runs KERIA's +// approveDelegation: it promotes qvi's dip out of gleif's `delegables` +// escrow into gleif's kevers. A plain interact anchors the seal but never +// ingests qvi's KEL, so gleif later rejects qvi's dip as "unknown AID". +// For an inception event the seal digest equals the prefix. Retry: qvi's +// post may not have reached gleif's escrow on the first approve; the seal +// anchor is idempotent, so re-approving just re-runs the promotion. +const delegationSeal = { i: qviPrefix, s: "0", d: qviPrefix }; +let approved = false; +for (let attempt = 1; attempt <= 10 && !approved; attempt++) { + try { + const gleifApproval = await gleifClient.delegations().approve(gleifAlias, delegationSeal); + await gleifClient.operations().wait(await gleifApproval.op(), AbortSignal.timeout(30000)); + approved = true; + } catch (_e) { + prMessage(`Waiting for qvi's dip to reach gleif's delegation escrow (attempt ${attempt})...`); + await sleep(2000); + } +} +if (!approved) throw new Error("gleif failed to approve qvi's delegated inception"); + +// 3. qvi pulls gleif's anchoring event, then its delegated inception completes. +const qviQueryOp = await qviClient.keyStates().query(gleifPrefix); +await qviClient.operations().wait(qviQueryOp, AbortSignal.timeout(60000)); +await qviClient.operations().wait(qviIcpOp, AbortSignal.timeout(60000)); +await qviClient.operations().delete(qviIcpOp.name); + +await addEndRoleForAID(qviClient, qviAlias, ROLE_AGENT); +const qviOOBI = await generateOOBI(qviClient, qviAlias, ROLE_AGENT); +prMessage(`QVI Prefix (delegated by gleif): ${qviPrefix}`); + +// LE +const leBran = randomPasscode(); +const leAlias = "le"; +const { client: leClient } = await initializeAndConnectClient(leBran); +await resolveWitnesses(leClient, "le"); +const { aid: leAid } = await createNewAID(leClient, leAlias, DEFAULT_IDENTIFIER_ARGS); +await addEndRoleForAID(leClient, leAlias, ROLE_AGENT); +const leOOBI = await generateOOBI(leClient, leAlias, ROLE_AGENT); +const lePrefix = leAid.i; +prMessage(`LE Prefix: ${lePrefix}`); + +// Role Holder +const roleBran = randomPasscode(); +const roleAlias = "role"; +const { client: roleClient } = await initializeAndConnectClient(roleBran); +await resolveWitnesses(roleClient, "role"); +const { aid: roleAid } = await createNewAID(roleClient, roleAlias, DEFAULT_IDENTIFIER_ARGS); +await addEndRoleForAID(roleClient, roleAlias, ROLE_AGENT); +const roleOOBI = await generateOOBI(roleClient, roleAlias, ROLE_AGENT); +const rolePrefix = roleAid.i; +prMessage(`ROLE Prefix: ${rolePrefix}`); + +// Client OOBI resolution (create contacts) +prTitle("Resolving OOBIs"); +await Promise.all([ + resolveOOBI(gleifClient, qviOOBI, qviAlias), + resolveOOBI(qviClient, gleifOOBI, gleifAlias), + resolveOOBI(qviClient, leOOBI, leAlias), + resolveOOBI(qviClient, roleOOBI, roleAlias), + resolveOOBI(leClient, gleifOOBI, gleifAlias), + resolveOOBI(leClient, qviOOBI, qviAlias), + resolveOOBI(leClient, roleOOBI, roleAlias), + resolveOOBI(roleClient, gleifOOBI, gleifAlias), + resolveOOBI(roleClient, leOOBI, leAlias), + resolveOOBI(roleClient, qviOOBI, qviAlias), +]); + +// Create credential registries +prTitle("Creating Credential Registries"); + +let gleifRegistrySaid; +try { + const registries = await gleifClient.registries().list(gleifAlias); + gleifRegistrySaid = registries[0].regk; +} catch { + prMessage("Creating GLEIF Registry"); + const { registrySaid: newRegistrySaid } = await createCredentialRegistry(gleifClient, gleifAlias, "gleifRegistry"); + gleifRegistrySaid = newRegistrySaid; +} +const { registrySaid: qviRegistrySaid } = await createCredentialRegistry(qviClient, qviAlias, "qviRegistry"); +const { registrySaid: leRegistrySaid } = await createCredentialRegistry(leClient, leAlias, "leRegistry"); +prContinue(); + +// --------------------------------------------------------------------------- +// Schemas — well-known, preloaded into the local schema server. +// --------------------------------------------------------------------------- +const QVI_SCHEMA_SAID = "EBfdlu8R27Fbx-ehrqwImnK-8Cm79sqbAQ4MmvEAYqao"; +const LE_SCHEMA_SAID = "ENPXp1vQzRF6JwIuS-mp2U8Uf1MoADoP_GqQ62VsDZWY"; +const ECR_AUTH_SCHEMA_SAID = "EH6ekLjSr8V32WyFbGe1zXjTzFs9PkTYmupJ9H65O14g"; +const ECR_SCHEMA_SAID = "EEy9PkikFcANV1l7EHukCeXqrzT1hNZjGlUk7wuMO5jw"; +const OOR_AUTH_SCHEMA_SAID = "EKA57bKBKxr_kN7iN5i7lMUxpMG-s19dRcmov1iDxz-E"; +const OOR_SCHEMA_SAID = "EBNaNu-M9P5cgrnfl2Fvymy4E_jvxxyjb70PRtiANlJy"; + +const QVI_SCHEMA_URL = `${SCHEMA_SERVER_HOST}/oobi/${QVI_SCHEMA_SAID}`; +const LE_SCHEMA_URL = `${SCHEMA_SERVER_HOST}/oobi/${LE_SCHEMA_SAID}`; +const ECR_AUTH_SCHEMA_URL = `${SCHEMA_SERVER_HOST}/oobi/${ECR_AUTH_SCHEMA_SAID}`; +const ECR_SCHEMA_URL = `${SCHEMA_SERVER_HOST}/oobi/${ECR_SCHEMA_SAID}`; +const OOR_AUTH_SCHEMA_URL = `${SCHEMA_SERVER_HOST}/oobi/${OOR_AUTH_SCHEMA_SAID}`; +const OOR_SCHEMA_URL = `${SCHEMA_SERVER_HOST}/oobi/${OOR_SCHEMA_SAID}`; + +prTitle("Resolving Schemas"); +await Promise.all([ + resolveOOBI(gleifClient, QVI_SCHEMA_URL), + + resolveOOBI(qviClient, QVI_SCHEMA_URL), + resolveOOBI(qviClient, LE_SCHEMA_URL), + resolveOOBI(qviClient, ECR_AUTH_SCHEMA_URL), + resolveOOBI(qviClient, ECR_SCHEMA_URL), + resolveOOBI(qviClient, OOR_AUTH_SCHEMA_URL), + resolveOOBI(qviClient, OOR_SCHEMA_URL), + + resolveOOBI(leClient, QVI_SCHEMA_URL), + resolveOOBI(leClient, LE_SCHEMA_URL), + resolveOOBI(leClient, ECR_AUTH_SCHEMA_URL), + resolveOOBI(leClient, ECR_SCHEMA_URL), + resolveOOBI(leClient, OOR_AUTH_SCHEMA_URL), + resolveOOBI(leClient, OOR_SCHEMA_URL), + + resolveOOBI(roleClient, QVI_SCHEMA_URL), + resolveOOBI(roleClient, LE_SCHEMA_URL), + resolveOOBI(roleClient, ECR_AUTH_SCHEMA_URL), + resolveOOBI(roleClient, ECR_SCHEMA_URL), + resolveOOBI(roleClient, OOR_AUTH_SCHEMA_URL), + resolveOOBI(roleClient, OOR_SCHEMA_URL), +]); +prContinue(); + +// --------------------------------------------------------------------------- +// Step 1: QVI Credential — GLEIF issues a Qualified vLEI Issuer credential to +// the QVI. First link in the chain, so no edge block. +// --------------------------------------------------------------------------- +{ + const qviData = { + LEI: "254900OPPU84GM83MG36", // QVI LEI (arbitrary value) + }; + + prTitle("Issuing Credential"); + const { credentialSaid } = await issueCredential( + gleifClient, gleifAlias, gleifRegistrySaid, + QVI_SCHEMA_SAID, + qviPrefix, + qviData, + ); + + qviCredential = await gleifClient.credentials().get(credentialSaid); + + prTitle("Granting Credential"); + await ipexGrantCredential(gleifClient, gleifAlias, qviPrefix, qviCredential); + + const grantNotifications = await waitForAndGetNotification(qviClient, IPEX_GRANT_ROUTE); + const grantNotification = grantNotifications[0]; + + prTitle("Admitting Grant"); + await ipexAdmitGrant(qviClient, qviAlias, gleifPrefix, grantNotification.a.d); + await markNotificationRead(qviClient, grantNotification.i); + + const admitNotifications = await waitForAndGetNotification(gleifClient, IPEX_ADMIT_ROUTE); + await markNotificationRead(gleifClient, admitNotifications[0].i); + + prContinue(); +} + +// --------------------------------------------------------------------------- +// Step 2: LE Credential — QVI issues a Legal Entity credential to the LE, +// chained back to the QVI credential via the leEdge `n` pointer. +// --------------------------------------------------------------------------- +{ + leData = { + LEI: "875500ELOZEL05BVXV37", + }; + + const leEdge = Saider.saidify({ + d: "", + qvi: { + n: qviCredential.sad.d, + s: qviCredential.sad.s, + }, + })[1]; + + const leRules = Saider.saidify({ + d: "", + usageDisclaimer: { + l: "Usage of a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, does not assert that the Legal Entity is trustworthy, honest, reputable in its business dealings, safe to do business with, or compliant with any laws or that an implied or expressly intended purpose will be fulfilled.", + }, + issuanceDisclaimer: { + l: "All information in a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, is accurate as of the date the validation process was complete. The vLEI Credential has been issued to the legal entity or person named in the vLEI Credential as the subject; and the qualified vLEI Issuer exercised reasonable care to perform the validation process set forth in the vLEI Ecosystem Governance Framework.", + }, + })[1]; + + prTitle("Issuing Credential"); + const { credentialSaid } = await issueCredential( + qviClient, qviAlias, qviRegistrySaid, + LE_SCHEMA_SAID, + lePrefix, + leData, leEdge, leRules, + ); + + prTitle("Granting Credential"); + leCredential = await qviClient.credentials().get(credentialSaid); + + await ipexGrantCredential(qviClient, qviAlias, lePrefix, leCredential); + + const grantNotifications = await waitForAndGetNotification(leClient, IPEX_GRANT_ROUTE); + const grantNotification = grantNotifications[0]; + + prTitle("Admitting Grant"); + await ipexAdmitGrant(leClient, leAlias, qviPrefix, grantNotification.a.d); + await markNotificationRead(leClient, grantNotification.i); + + const admitNotifications = await waitForAndGetNotification(qviClient, IPEX_ADMIT_ROUTE); + await markNotificationRead(qviClient, admitNotifications[0].i); + + prContinue(); +} + +// --------------------------------------------------------------------------- +// Step 6 (Path 1): ECR Credential — LE directly issues an Engagement Context +// Role credential to the Role holder, chained to the LE's own vLEI credential. +// --------------------------------------------------------------------------- +{ + const ecrData = { + LEI: leData.LEI, + personLegalName: "John Doe", + engagementContextRole: "Managing Director", + }; + + const ecrEdge = Saider.saidify({ + d: "", + le: { + n: leCredential.sad.d, + s: leCredential.sad.s, + }, + })[1]; + + const ecrRules = Saider.saidify({ + d: "", + usageDisclaimer: { + l: "Usage of a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, does not assert that the Legal Entity is trustworthy, honest, reputable in its business dealings, safe to do business with, or compliant with any laws or that an implied or expressly intended purpose will be fulfilled.", + }, + issuanceDisclaimer: { + l: "All information in a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, is accurate as of the date the validation process was complete. The vLEI Credential has been issued to the legal entity or person named in the vLEI Credential as the subject; and the qualified vLEI Issuer exercised reasonable care to perform the validation process set forth in the vLEI Ecosystem Governance Framework.", + }, + privacyDisclaimer: { + l: "It is the sole responsibility of Holders as Issuees of an ECR vLEI Credential to present that Credential in a privacy-preserving manner using the mechanisms provided in the Issuance and Presentation Exchange (IPEX) protocol specification and the Authentic Chained Data Container (ACDC) specification. https://github.com/WebOfTrust/IETF-IPEX and https://github.com/trustoverip/tswg-acdc-specification.", + }, + })[1]; + + prTitle("Issuing Credential"); + const { credentialSaid } = await issueCredential( + leClient, leAlias, leRegistrySaid, + ECR_SCHEMA_SAID, + rolePrefix, + ecrData, ecrEdge, ecrRules, + true, + ); + + ecrCredential = await leClient.credentials().get(credentialSaid); + + prTitle("Granting Credential"); + await ipexGrantCredential(leClient, leAlias, rolePrefix, ecrCredential); + + const grantNotifications = await waitForAndGetNotification(roleClient, IPEX_GRANT_ROUTE); + const grantNotification = grantNotifications[0]; + + prTitle("Admitting Grant"); + await ipexAdmitGrant(roleClient, roleAlias, lePrefix, grantNotification.a.d); + await markNotificationRead(roleClient, grantNotification.i); + + const admitNotifications = await waitForAndGetNotification(leClient, IPEX_ADMIT_ROUTE); + await markNotificationRead(leClient, admitNotifications[0].i); + + prContinue(); +} + +// --------------------------------------------------------------------------- +// Register the local GLEIF root of trust + export the holder's full-chain ECR +// vLEI for the RA to present. +// +// The RA is the single touchpoint for the verifier, so this does NOT PUT the +// presentation or poll /authorizations — ans-ra does that itself inside POST +// /v2/ans/identities (the vleiPresentation). This only does the two things the +// RA cannot do: register the synthetic local GLEIF root of trust (an admin +// bootstrap of the verifier), and export the holder's full-chain CESR + LEI. +// --------------------------------------------------------------------------- +{ + const ecrSaid = ecrCredential.sad.d; + const ecrLEI = ecrCredential.sad.a.LEI; + + // Export the ECR credential as a self-contained CESR stream. KERIA's exporter + // walks the full edge chain (ECR -> LE -> QVI) and emits every issuer/subject + // KEL and TEL — including the local GLEIF root's KEL and the holder's (role) + // KEL — so this single blob is everything the verifier needs to verify the + // chain to root. The RA parses the leaf SAID + subject AID out of this blob. + const ecrCesr = await roleClient.credentials().get(ecrSaid, true); + + // Register the LOCAL `gleif` AID as a root of trust. The verifier ships + // trusting the real GLEIF external root; our synthetic chain roots at this + // `gleif` AID, so the verifier must be told to trust it or the presented + // chain will not verify. The chain CESR already contains gleif's KEL (it is + // the root issuer), so it doubles as the `vlei` payload. + const rotResp = await fetch(`${VERIFIER_URL}/root_of_trust/${gleifPrefix}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ vlei: ecrCesr, oobi: gleifOOBI }), + }); + console.log("root_of_trust:", rotResp.status, await rotResp.text()); + + // Export {cesr, lei, aid} for the shell demo. The RA parses said+aid out of + // the CESR itself and presents it to the verifier on the holder's behalf. + await Deno.mkdir(OUT_DIR, { recursive: true }); + const presentation = { cesr: ecrCesr, lei: ecrLEI, aid: rolePrefix }; + await Deno.writeTextFile(`${OUT_DIR}/ecr-presentation.json`, JSON.stringify(presentation, null, 2)); + + console.log("\n✅ root of trust registered and full-chain CESR exported."); + console.log(` holder AID : ${rolePrefix}`); + console.log(` LEI : ${ecrLEI}`); + console.log(` leaf SAID : ${ecrSaid}`); + console.log(` wrote ${OUT_DIR}/ecr-presentation.json`); +} + +// --------------------------------------------------------------------------- +// Export the holder state the proof signer needs (roleBran reconnects to the +// holder's KERIA agent so sign-proof.ts can sign with the role AID's keys). +// --------------------------------------------------------------------------- +{ + const outputs = { + gleifPrefix, + rolePrefix, + roleBran, + LEI: leData.LEI, + ecrCredentialSaid: ecrCredential.sad.d, + gleifOOBI, + }; + await Deno.writeTextFile(`${OUT_DIR}/tier1-outputs.json`, JSON.stringify(outputs, null, 2)); + console.log(` wrote ${OUT_DIR}/tier1-outputs.json`); +} diff --git a/scripts/demo/vlei/signify/scripts_ts/sign-proof.ts b/scripts/demo/vlei/signify/scripts_ts/sign-proof.ts new file mode 100644 index 0000000..f2bcec7 --- /dev/null +++ b/scripts/demo/vlei/signify/scripts_ts/sign-proof.ts @@ -0,0 +1,62 @@ +// ============================================================================ +// ANS demo — standalone holder-side proof signer. +// +// Signs the RA's verify-control `signingInput` with the holder (role) AID, +// OUTSIDE the notebook, so the verify-control flow needs no manual copy-paste. +// This is the automated equivalent of the notebook's interactive sign cell +// (tagged `skip-headless`); that cell stays in the notebook as the human +// fallback. +// +// WHY the signingInput and not the bare nonce: the lei control proof is +// uniform with the JWS kinds — every kind signs the served `signingInput` +// (the base64url of the JCS-canonical IdentityProofInput), never a bare +// nonce. The RA forwards the signature to the vlei-verifier as +// `non_prefixed_digest = signingInput`, and the verifier checks it over the +// exact UTF-8 bytes of that string. So we sign those bytes verbatim. +// +// USAGE (run inside the jupyter/signify container, on the stack network): +// deno run -A scripts_ts/sign-proof.ts +// +// Prints ONLY the indexed Siger qb64 signature to stdout (e.g. "AAB…") so a +// shell can capture it directly; all diagnostics go to stderr. +// +// WHY connect, not boot: utils.ts initializeAndConnectClient() calls +// client.boot() first, which fails (and is re-thrown) when the agent already +// exists. The role agent was booted by the notebook run, so here we ONLY +// connect. Reconnecting with the SAME roleBran re-attaches to that same +// persistent KERIA agent — the role AID's salty signing keys live server-side +// and are reachable through the keeper without any OOBI re-resolution. +// +// WHY the role AID and not `kli sign`: the holder is a KERIA/signify +// identifier whose keys live in the cloud agent reachable only via this +// client. A local kli keystore would be a different AID, and the verifier +// pins the signer to the credential's subject AID — so a kli signature is +// rejected as SIGNATURE_INVALID. +// ============================================================================ + +// Pinned to match build-chain.ts so both scripts (and the compose pre-cache) +// resolve the same signify-ts the holder's KERIA agent was created with. +import { ready, SignifyClient, Tier } from "npm:signify-ts@^0.3.0-rc1"; +import { DEFAULT_ADMIN_URL, DEFAULT_BOOT_URL } from "./utils.ts"; + +const ROLE_ALIAS = "role"; + +const [roleBran, signingInput] = Deno.args; +if (!roleBran || !signingInput) { + console.error("usage: deno run -A sign-proof.ts "); + Deno.exit(2); +} + +await ready(); + +// Connect only — do NOT boot an already-existing agent. +const client = new SignifyClient(DEFAULT_ADMIN_URL, roleBran, Tier.low, DEFAULT_BOOT_URL); +await client.connect(); + +const hab = await client.identifiers().get(ROLE_ALIAS); +const keeper = client.manager!.get(hab); +const sigs = await keeper.sign(new TextEncoder().encode(signingInput)); + +// stderr: human-readable context; stdout: the signature only. +console.error(`signerAid : ${hab.prefix}`); +console.log(sigs[0]); diff --git a/scripts/demo/vlei/signify/scripts_ts/utils.ts b/scripts/demo/vlei/signify/scripts_ts/utils.ts new file mode 100644 index 0000000..c0ca782 --- /dev/null +++ b/scripts/demo/vlei/signify/scripts_ts/utils.ts @@ -0,0 +1,1045 @@ +import { + randomPasscode, + ready, + SignifyClient, + Tier, + CreateIdentiferArgs, + State, + Operation, + Contact, + Salter, + Serder +} from 'npm:signify-ts'; + +class Ansi { + // Text Colors + static readonly BLACK = '\x1b[30m'; + static readonly RED = '\x1b[31m'; + static readonly GREEN = '\x1b[32m'; + static readonly YELLOW = '\x1b[33m'; + static readonly BLUE = '\x1b[34m'; + static readonly MAGENTA = '\x1b[35m'; + static readonly CYAN = '\x1b[36m'; + static readonly WHITE = '\x1b[37m'; + + // Bright/Light versions + static readonly BRIGHT_BLACK = '\x1b[90m'; + static readonly BRIGHT_RED = '\x1b[91m'; + static readonly BRIGHT_GREEN = '\x1b[92m'; + static readonly BRIGHT_YELLOW = '\x1b[93m'; + static readonly BRIGHT_BLUE = '\x1b[94m'; + static readonly BRIGHT_MAGENTA = '\x1b[95m'; + static readonly BRIGHT_CYAN = '\x1b[96m'; + static readonly BRIGHT_WHITE = '\x1b[97m'; + + // Background colors + static readonly BG_BLACK = '\x1b[40m'; + static readonly BG_RED = '\x1b[41m'; + static readonly BG_GREEN = '\x1b[42m'; + static readonly BG_YELLOW = '\x1b[43m'; + static readonly BG_BLUE = '\x1b[44m'; + static readonly BG_MAGENTA = '\x1b[45m'; + static readonly BG_CYAN = '\x1b[46m'; + static readonly BG_WHITE = '\x1b[47m'; + + // Bright Background colors + static readonly BG_BRIGHT_BLACK = '\x1b[100m'; + static readonly BG_BRIGHT_RED = '\x1b[101m'; + static readonly BG_BRIGHT_GREEN = '\x1b[102m'; + static readonly BG_BRIGHT_YELLOW = '\x1b[103m'; + static readonly BG_BRIGHT_BLUE = '\x1b[104m'; + static readonly BG_BRIGHT_MAGENTA = '\x1b[105m'; + static readonly BG_BRIGHT_CYAN = '\x1b[106m'; + static readonly BG_BRIGHT_WHITE = '\x1b[107m'; + + // Styles + static readonly BOLD = '\x1b[1m'; + static readonly UNDERLINE = '\x1b[4m'; + static readonly RESET = '\x1b[0m'; +} + +export function prTitle(message: string): void { + console.log(`\n${Ansi.BOLD}${Ansi.UNDERLINE}${Ansi.BG_BLUE}${Ansi.BRIGHT_BLACK} ${message} ${Ansi.RESET}\n`); +} + +export function prMessage(message: string): void { + console.log(`\n${Ansi.BOLD}${Ansi.BRIGHT_BLUE}${message}${Ansi.RESET}\n`); +} + +export function prAlert(message: string): void { + console.log(`\n${Ansi.BOLD}${Ansi.BG_YELLOW}${Ansi.BRIGHT_BLUE}${message}${Ansi.RESET}\n`); +} + +export function prContinue(): void { + const message = " You can continue ✅ "; + console.log(`\n${Ansi.BOLD}${Ansi.BG_GREEN}${Ansi.BRIGHT_BLACK}${message}${Ansi.RESET}\n\n`); +} + +// Helper function for sleeping +export function sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +// Function to check the health of a container +export async function isServiceHealthy(healthCheckUrl: string): Promise { + + console.log(`Checking health at: ${healthCheckUrl}`); + + try { + const response = await fetch(healthCheckUrl); + + if (response.ok) { + console.log(`Received status: ${response.status}. Service is healthy.`); + return true; + } else { + console.warn(`Received a non-ok status: ${response.status}. Service is running but may be unhealthy.`); + return false; + } + } catch (error) { + console.error(`Failed to connect to service. It may be down. Error:`, error.message); + return false; + } +} + +// Default KERIA connection parameters (adjust as needed for your environment) +export const DEFAULT_ADMIN_URL = 'http://keria:3901'; +export const DEFAULT_BOOT_URL = 'http://keria:3903'; +export const DEFAULT_TIMEOUT_MS = 30000; // 30 seconds for operations +export const DEFAULT_DELAY_MS = 5000; // 5 seconds for operations +export const DEFAULT_RETRIES = 5; // For retries +export const ROLE_AGENT = 'agent' +export const IPEX_GRANT_ROUTE = '/exn/ipex/grant' +export const IPEX_ADMIT_ROUTE = '/exn/ipex/admit' +export const IPEX_APPLY_ROUTE = '/exn/ipex/apply' +export const IPEX_OFFER_ROUTE = '/exn/ipex/offer' +export const SCHEMA_SERVER_HOST = 'http://vlei-server:7723'; + +export const DEFAULT_IDENTIFIER_ARGS = { + toad: 3, + wits: [ + 'BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha', + 'BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM', + 'BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX' + ] +}; + +/** + * Initializes the Signify-ts library. + */ +export async function initializeSignify() { + await ready(); + console.log('Signify-ts library initialized.'); +} + +/** + * Creates a new SignifyClient instance, boots it, and connects to the KERIA agent. + * + * @returns {Promise<{ client: SignifyClient; bran: string; clientState: State }>} + * The initialized client, its bran, and state. + */ +export async function initializeAndConnectClient( + bran: string, + adminUrl: string = DEFAULT_ADMIN_URL, + bootUrl: string = DEFAULT_BOOT_URL, + tier: Tier = Tier.low +): Promise<{ client: SignifyClient;clientState: State }> { + + console.log(`Using Passcode (bran): ${bran}`); + + const client = new SignifyClient(adminUrl, bran, tier, bootUrl); + + try { + await client.boot(); + console.log('Client boot process initiated with KERIA agent.'); + + await client.connect(); + const clientState = await client.state(); + + console.log(' Client AID Prefix: ', clientState?.controller?.state?.i); + console.log(' Agent AID Prefix: ', clientState?.agent?.i); + + return { client, clientState }; + } catch (error) { + console.error('Failed to initialize or connect client:', error); + throw error; + } +} + +/** + * Creates a new AID using the provided client. + * + * @param {SignifyClient} client - The initialized SignifyClient. + * @param {string} alias - A human-readable alias for the AID. + * @param {CreateIdentiferArgs} [identifierArgs=DEFAULT_IDENTIFIER_ARGS] - Configuration for the new AID. + * @returns {Promise<{ aid: any; operation: Operation }>} The created AID's inception event and the operation details. + */ +export async function createNewAID( + client: SignifyClient, + alias: string, + identifierArgs: CreateIdentiferArgs = DEFAULT_IDENTIFIER_ARGS +): Promise<{ aid: any; operation: Operation }> { + console.log(`Initiating AID inception for alias: ${alias}`); + try { + const inceptionResult = await client.identifiers().create(alias, identifierArgs as any); + const operationDetails = await inceptionResult.op(); + + const completedOperation = await client + .operations() + .wait(operationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + throw new Error(`AID creation failed: ${JSON.stringify(completedOperation.error)}`); + } + + const newAidInceptionEvent = completedOperation.response; + console.log(`Successfully created AID with prefix: ${newAidInceptionEvent?.i}`); + + await client.operations().delete(completedOperation.name); + + return { aid: newAidInceptionEvent, operation: completedOperation }; + } catch (error) { + console.error(`Failed to create AID for alias "${alias}":`, error); + throw error; + } +} + +/** + * Assigns an end role for a given AID to the client's KERIA Agent AID. + * + * @returns {Promise<{ operation: Operation }>} The operation details. + */ +export async function addEndRoleForAID( + client: SignifyClient, + aidAlias: string, + role: string +): Promise<{ operation: Operation }> { + if (!client.agent?.pre) { + throw new Error('Client agent prefix is not available.'); + } + const agentAIDPrefix = client.agent.pre; + + console.log(`Assigning '${role}' role to KERIA Agent ${agentAIDPrefix} for AID alias ${aidAlias}`); + try { + const addRoleResult = await client + .identifiers() + .addEndRole(aidAlias, role, agentAIDPrefix); + + const operationDetails = await addRoleResult.op(); + + const completedOperation = await client + .operations() + .wait(operationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + console.log(`Successfully assigned '${role}' role for AID alias ${aidAlias}.`); + + await client.operations().delete(completedOperation.name); + + return { operation: completedOperation }; + } catch (error) { + console.error(`Failed to add end role for AID alias "${aidAlias}":`, error); + throw error; + } +} + +/** + * Generates an OOBI URL for a given AID and role. + * The arguments for client.oobis().get() are passed directly. + * + * @returns {Promise} The generated OOBI URL. + */ +export async function generateOOBI( + client: SignifyClient, + aidAlias: string, + role: string = 'agent' +): Promise { + console.log(`Generating OOBI for AID alias ${aidAlias} with role ${role}`); + try { + const oobiResult = await client.oobis().get(aidAlias, role); + if (!oobiResult?.oobis?.length) { + throw new Error('No OOBI URL returned from KERIA agent.'); + } + const oobiUrl = oobiResult.oobis[0]; + console.log(`Generated OOBI URL: ${oobiUrl}`); + return oobiUrl; + } catch (error) { + console.error(`Failed to generate OOBI for AID alias "${aidAlias}":`, error); + throw error; + } +} + +/** + * Resolves an OOBI URL + * + * @returns {Promise<{ operation: Operation; contacts?: Contact[] }>} The operation details and the resolved contact. + */ +export async function resolveOOBI( + client: SignifyClient, + oobiUrl: string, + contactAlias?: string +): Promise<{ operation: Operation; contacts?: Contact[] }> { + console.log(`Resolving OOBI URL: ${oobiUrl} with alias ${contactAlias}`); + try { + const resolveOperationDetails = await client.oobis().resolve(oobiUrl, contactAlias); + const completedOperation = await client + .operations() + .wait(resolveOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + throw new Error(`OOBI resolution failed: ${JSON.stringify(completedOperation.error)}`); + } + console.log(`Successfully resolved OOBI URL. Response:`, completedOperation.response ? "OK" : "No response data"); + + const contact = await client.contacts().list(undefined, 'alias', contactAlias); + + if (contact) { + console.log(`Contact "${contactAlias}" added/updated.`); + } else { + console.warn(`Contact "${contactAlias}" not found after OOBI resolution.`); + } + + await client.operations().delete(completedOperation.name); + + return { operation: completedOperation, contact: contact }; + } catch (error) { + console.error(`Failed to resolve OOBI URL "${oobiUrl}":`, error); + throw error; + } +} + +/** + * Generates challenge words for authentication. + * @param {SignifyClient} client - The SignifyClient instance. + * @param {number} [strength=128] - The bit strength for the challenge (e.g., 128, 256). + * @returns {Promise} A promise that resolves to an array of challenge words. + */ +export async function generateChallengeWords( + client: SignifyClient, + strength: number = 128 +): Promise { + console.log(`Generating ${strength}-bit challenge words...`); + try { + const challenge = await client.challenges().generate(strength); + console.log('Generated challenge words:', challenge.words); + return challenge.words; + } catch (error) { + console.error('Failed to generate challenge words:', error); + throw error; + } +} + +/** + * Responds to a challenge by signing the words and sending them to the challenger. + * @param {SignifyClient} client - The SignifyClient instance of the responder. + * @param {string} sourceAidAlias - The alias of the AID that is responding (signing). + * @param {string} recipientAidPrefix - The AID prefix of the challenger (to whom the response is sent). + * @param {string[]} challengeWords - The array of challenge words to sign. + * @returns {Promise} A promise that resolves when the response is sent. + */ +export async function respondToChallenge( + client: SignifyClient, + sourceAidAlias: string, + recipientAidPrefix: string, + challengeWords: string[] +): Promise { + console.log(`AID alias '${sourceAidAlias}' responding to challenge from AID '${recipientAidPrefix}'...`); + try { + await client.challenges().respond(sourceAidAlias, recipientAidPrefix, challengeWords); + console.log('Challenge response sent.'); + } catch (error) { + console.error('Failed to respond to challenge:', error); + throw error; + } +} + +/** + * Verifies a challenge response received from another AID. + * @param {SignifyClient} client - The SignifyClient instance of the verifier. + * @param {string} allegedSenderAidPrefix - The AID prefix of the AID that allegedly sent the response. + * @param {string[]} originalChallengeWords - The original challenge words that were sent. + * @returns {Promise<{ verified: boolean; said?: string; operation?: Operation }>} + * A promise that resolves to an object indicating if verification was successful, + * the SAID of the signed exchange message, and the operation details. + */ +export async function verifyChallengeResponse( + client: SignifyClient, + allegedSenderAidPrefix: string, + originalChallengeWords: string[] +): Promise<{ verified: boolean; said?: string; operation?: Operation }> { + console.log(`Verifying challenge response from AID '${allegedSenderAidPrefix}'...`); + try { + const verifyOperation = await client.challenges().verify(allegedSenderAidPrefix, originalChallengeWords); + const completedOperation = await client + .operations() + .wait(verifyOperation, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + console.error('Challenge verification failed:', completedOperation.error); + await client.operations().delete(completedOperation.name); + return { verified: false, operation: completedOperation }; + } + + const said = completedOperation.response?.exn?.d; + console.log(`Challenge response verified successfully. SAID of exn: ${said}`); + + await client.operations().delete(completedOperation.name); + + return { verified: true, said: said, operation: completedOperation }; + } catch (error) { + console.error('Failed to verify challenge response:', error); + throw error; + } +} + +/** + * Marks a challenge for a contact as authenticated. + * This is done after successful verification of a challenge response. + * @param {SignifyClient} client - The SignifyClient instance. + * @param {string} contactAidPrefix - The AID prefix of the contact to mark as authenticated. + * @param {string} signedChallengeSaid - The SAID of the signed challenge exchange message (exn). + * @returns {Promise} A promise that resolves when the contact is marked. + */ +export async function markChallengeAuthenticated( + client: SignifyClient, + contactAidPrefix: string, + signedChallengeSaid: string +): Promise { + console.log(`Marking challenge for contact AID '${contactAidPrefix}' as authenticated with SAID '${signedChallengeSaid}'...`); + try { + await client.challenges().responded(contactAidPrefix, signedChallengeSaid); + console.log(`Contact AID '${contactAidPrefix}' marked as authenticated.`); + } catch (error) { + console.error(`Failed to mark challenge as authenticated for contact AID '${contactAidPrefix}':`, error); + throw error; + } +} + +export function createTimestamp() { + return new Date().toISOString().replace('Z', '000+00:00'); +} + +/** + * Creates a new credential registry for an AID. + * @param {SignifyClient} client - The SignifyClient instance. + * @param {string} aidAlias - The alias of the AID creating the registry. + * @param {string} registryName - A human-readable name for the registry. + * @returns {Promise<{ registry: any; operation: Operation }>} The created registry details and operation. + */ +export async function createCredentialRegistry( + client: SignifyClient, + aidAlias: string, + registryName: string +): Promise<{ registrySaid: any; operation: Operation }> { + console.log(`Creating credential registry "${registryName}" for AID alias "${aidAlias}"...`); + try { + const createRegistryResult = await client + .registries() + .create({ name: aidAlias, registryName: registryName }); + + const operationDetails = await createRegistryResult.op(); + const completedOperation = await client + .operations() + .wait(operationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + throw new Error(`Credential registry creation failed: ${JSON.stringify(completedOperation.error)}`); + } + + const registrySaid = completedOperation?.response?.anchor?.i; + console.log(`Successfully created credential registry: ${registrySaid}`); + + await client.operations().delete(completedOperation.name); + return { registrySaid, operation: completedOperation }; + } catch (error) { + console.error(`Failed to create credential registry "${registryName}":`, error); + throw error; + } +} + +/** + * Retrieves a schema by its SAID. + * @param {SignifyClient} client - The SignifyClient instance. + * @param {string} schemaSaid - The SAID of the schema to retrieve. + * @returns {Promise} The schema object. + */ +export async function getSchema( + client: SignifyClient, + schemaSaid: string +): Promise { + console.log(`Retrieving schema with SAID: ${schemaSaid}...`); + try { + const schema = await client.schemas().get(schemaSaid); + console.log(`Successfully retrieved schema: ${schemaSaid}`); + return schema; + } catch (error) { + console.error(`Failed to retrieve schema "${schemaSaid}":`, error); + throw error; + } +} + +/** + * Issues a new credential. + * @param {SignifyClient} client - The SignifyClient instance. + * @param {string} issuerAidAlias - The alias of the issuing AID. + * @param {string} registryIdentifier - The identifier (regk) of the registry. + * @param {string} schemaSaid - The SAID of the credential's schema. + * @param {string} holderAidPrefix - The prefix of the AID to whom the credential will be issued. + * @param {any} credentialClaims - The claims/attributes of the credential. + * @returns {Promise<{ credentialSad: any; credentialSaid: string; operation: Operation }>} The issued credential's SAD, SAID, and operation. + */ +export async function issueCredential( + client: SignifyClient, + issuerAidAlias: string, + registryIdentifier: string, + schemaSaid: string, + holderAidPrefix: string, + credentialClaims: any, + edges?: any, + rules?: any, + salt = false +): Promise<{ credentialSaid: string; operation: Operation }> { + console.log(`Issuing credential from AID "${issuerAidAlias}" to AID "${holderAidPrefix}"...`); + try { + const issueResult = await client + .credentials() + .issue( + issuerAidAlias, + { + ri: registryIdentifier, + s: schemaSaid, + u: salt ? new Salter({}).qb64 : undefined, + a: { + i: holderAidPrefix, + ...credentialClaims + }, + e: edges, + r: rules + }); + + const operationDetails = await issueResult.op; + const completedOperation = await client + .operations() + .wait(operationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + throw new Error(`Credential issuance failed: ${JSON.stringify(completedOperation.error)}`); + } + console.log(completedOperation) // ************ + const credentialSad = completedOperation.response; // The full Self-Addressing Data (SAD) of the credential + const credentialSaid = credentialSad?.ced?.d; // The SAID of the credential + console.log(`Successfully issued credential with SAID: ${credentialSaid}`); + + await client.operations().delete(completedOperation.name); + return { credentialSaid, operation: completedOperation }; + } catch (error) { + console.error('Failed to issue credential:', error); + throw error; + } +} + +/** + * Submits an IPEX grant for a credential. + * @param {SignifyClient} client - The SignifyClient instance of the issuer. + * @param {string} senderAidAlias - The alias of the AID granting the credential. + * @param {string} recipientAidPrefix - The AID prefix of the recipient (holder). + * @param {any} acdc - The ACDC (credential). + * @returns {Promise<{ operation: Operation }>} The operation details. + */ +export async function ipexGrantCredential( + client: SignifyClient, + senderAidAlias: string, + recipientAidPrefix: string, + acdc: any +): Promise<{ operation: Operation }> { + console.log(`AID "${senderAidAlias}" granting credential to AID "${recipientAidPrefix}" via IPEX...`); + try { + + const [grant, gsigs, gend] = await client.ipex().grant({ + senderName: senderAidAlias, + acdc: new Serder(acdc?.sad), + iss: new Serder(acdc?.iss), + anc: new Serder(acdc?.anc), + ancAttachment: acdc.ancatc, + recipient: recipientAidPrefix, + datetime: createTimestamp(), + }); + + const submitGrantOperationDetails = await client + .ipex() + .submitGrant(senderAidAlias, grant, gsigs, gend, [recipientAidPrefix]); + + const completedOperation = await client + .operations() + .wait(submitGrantOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + throw new Error(`IPEX grant submission failed: ${JSON.stringify(completedOperation.error)}`); + } + + console.log(`Successfully submitted IPEX grant from "${senderAidAlias}" to "${recipientAidPrefix}".`); + await client.operations().delete(completedOperation.name); + return { operation: completedOperation }; + } catch (error) { + console.error('Failed to submit IPEX grant:', error); + throw error; + } +} + +/** + * Retrieves the state of a credential. + * Includes retry logic as this might be called before the information has propagated. + * @param {SignifyClient} client - The SignifyClient instance. + * @param {string} registryIdentifier - The registry identifier (regk). + * @param {string} credentialSaid - The SAID of the credential. + * @param {number} [retries=DEFAULT_RETRIES] - Number of retry attempts. + * @param {number} [delayMs=DEFAULT_DELAY_MS] - Delay between retries in milliseconds. + * @returns {Promise} The credential state. + */ +export async function getCredentialState( + client: SignifyClient, + registryIdentifier: string, + credentialSaid: string, + retries: number = DEFAULT_RETRIES, + delayMs: number = DEFAULT_DELAY_MS +): Promise { + console.log(`Querying credential state for SAID "${credentialSaid}" in registry "${registryIdentifier}"...`); + for (let attempt = 1; attempt <= retries; attempt++) { + try { + const credentialState = await client.credentials().state(registryIdentifier, credentialSaid); + console.log('Successfully retrieved credential state.'); + return credentialState; + } catch (error: any) { + console.warn(`[Attempt ${attempt}/${retries}] Failed to get credential state: ${error.message}`); + if (attempt === retries) { + console.error(`Max retries (${retries}) reached for getting credential state.`); + throw error; + } + await new Promise(resolve => setTimeout(resolve, delayMs)); + } + } + // Should not be reached if retries > 0 + throw new Error('Failed to get credential state after all retries.'); +} + +/** + * Waits for and retrieves a specific notification. + * @param {SignifyClient} client - The SignifyClient instance. + * @param {string} expectedRoute - The expected route in the notification attributes (e.g., IPEX_GRANT_ROUTE). + * @param {number} [retries=DEFAULT_RETRIES] - Number of retry attempts. + * @param {number} [delayMs=DEFAULT_DELAY_MS] - Delay between retries in milliseconds. + * @returns {Promise} The first matching unread notification. + */ +export async function waitForAndGetNotification( + client: SignifyClient, + expectedRoute: string, + retries: number = DEFAULT_RETRIES, + delayMs: number = DEFAULT_DELAY_MS +): Promise { + console.log(`Waiting for notification with route "${expectedRoute}"...`); + + let notifications; + + // Retry loop to fetch notifications. + for (let attempt = 1; attempt <= DEFAULT_RETRIES ; attempt++) { + try{ + // List notifications, filtering for unread IPEX_GRANT_ROUTE messages. + let allNotifications = await client.notifications().list() + notifications = allNotifications.notes.filter( + (n) => n.a.r === expectedRoute && n.r === false // n.r is 'read' status + ); + if(notifications.length === 0){ + throw new Error("Notification not found yet."); // Throw error to trigger retry + } + return notifications; + } + catch (error){ + console.log(`[Retry] Grant notification not found on attempt #${attempt} of ${DEFAULT_RETRIES}`); + if (attempt === DEFAULT_RETRIES) { + console.error(`[Retry] Max retries (${DEFAULT_RETRIES}) reached for grant notification.`); + throw error; + } + console.log(`[Retry] Waiting ${DEFAULT_DELAY_MS}ms before next attempt...`); + await new Promise(resolve => setTimeout(resolve, DEFAULT_DELAY_MS)); + } + } +} + +/** + * Submits an IPEX admit (accepts a grant). + * @param {SignifyClient} client - The SignifyClient instance of the holder. + * @param {string} senderAidAlias - The alias of the AID admitting the grant. + * @param {string} recipientAidPrefix - The AID prefix of the original grantor. + * @param {string} grantSaid - The SAID of the grant being admitted. + * @param {string} [message=''] - Optional message for the admit. + * @returns {Promise<{ operation: Operation }>} The operation details. + */ +export async function ipexAdmitGrant( + client: SignifyClient, + senderAidAlias: string, + recipientAidPrefix: string, + grantSaid: string, + message: string = '' +): Promise<{ operation: Operation }> { + console.log(`AID "${senderAidAlias}" admitting IPEX grant "${grantSaid}" from AID "${recipientAidPrefix}"...`); + try { + const [admit, sigs, aend] = await client.ipex().admit({ + senderName: senderAidAlias, + message: message, + grantSaid: grantSaid, + recipient: recipientAidPrefix, + datetime: createTimestamp(), + }); + + const admitOperationDetails = await client + .ipex() + .submitAdmit(senderAidAlias, admit, sigs, aend, [recipientAidPrefix]); + + const completedOperation = await client + .operations() + .wait(admitOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + throw new Error(`IPEX admit submission failed: ${JSON.stringify(completedOperation.error)}`); + } + console.log(`Successfully submitted IPEX admit for grant "${grantSaid}".`); + await client.operations().delete(completedOperation.name); + return { operation: completedOperation }; + } catch (error) { + console.error('Failed to submit IPEX admit:', error); + throw error; + } +} + +/** + * Marks a notification as read. + * @param {SignifyClient} client - The SignifyClient instance. + * @param {string} notificationId - The ID of the notification to mark. + * @returns {Promise} + */ +export async function markNotificationRead( + client: SignifyClient, + notificationId: string +): Promise { + console.log(`Marking notification "${notificationId}" as read...`); + try { + await client.notifications().mark(notificationId); + console.log(`Notification "${notificationId}" marked as read.`); + } catch (error) { + console.error(`Failed to mark notification "${notificationId}" as read:`, error); + throw error; + } +} + +/** + * Deletes a notification. + * @param {SignifyClient} client - The SignifyClient instance. + * @param {string} notificationId - The ID of the notification to delete. + * @returns {Promise} + */ +export async function deleteNotification( + client: SignifyClient, + notificationId: string +): Promise { + console.log(`Deleting notification "${notificationId}"...`); + try { + await client.notifications().delete(notificationId); + console.log(`Notification "${notificationId}" deleted.`); + } catch (error) { + console.error(`Failed to delete notification "${notificationId}":`, error); + throw error; + } +} + + +//-------------------------------------------------------------------------------- + +// --- Credential Presentation Functions --- + +/** + * Submits an IPEX apply (presentation request). + * @param {SignifyClient} client - The SignifyClient instance of the verifier. + * @param {string} senderAidAlias - The alias of the AID applying for presentation. + * @param {string} recipientAidPrefix - The AID prefix of the holder. + * @param {string} schemaSaid - The SAID of the schema being requested. + * @param {any} attributes - The attributes being requested for the credential. + * @param {string} datetime - The timestamp for the apply. + * @returns {Promise<{ operation: Operation; applySaid: string }>} The operation details and SAID of the apply exn. + */ +export async function ipexApplyForCredential( + client: SignifyClient, + senderAidAlias: string, + recipientAidPrefix: string, + schemaSaid: string, + attributes: any, + datetime: string +): Promise<{ operation: Operation; applySaid: string }> { + console.log(`AID "${senderAidAlias}" applying for credential presentation from AID "${recipientAidPrefix}"...`); + try { + const [apply, sigs, _] = await client.ipex().apply({ + senderName: senderAidAlias, + schemaSaid: schemaSaid, + attributes: attributes, + recipient: recipientAidPrefix, + datetime: datetime, + }); + + const applySaid = new Serder(apply).said; // Get SAID of the apply message itself + + const applyOperationDetails = await client + .ipex() + .submitApply(senderAidAlias, apply, sigs, [recipientAidPrefix]); + + const completedOperation = await client + .operations() + .wait(applyOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + throw new Error(`IPEX apply submission failed: ${JSON.stringify(completedOperation.error)}`); + } + console.log(`Successfully submitted IPEX apply with SAID "${applySaid}".`); + await client.operations().delete(completedOperation.name); + return { operation: completedOperation, applySaid }; + } catch (error) { + console.error('Failed to submit IPEX apply:', error); + throw error; + } +} + +/** + * Finds matching credentials based on a filter. + * @param {SignifyClient} client - The SignifyClient instance of the holder. + * @param {any} filter - The filter object to apply (e.g., { '-s': schemaSaid, '-a-attributeName': value }). + * @returns {Promise} An array of matching credentials. + */ +export async function findMatchingCredentials( + client: SignifyClient, + filter: any +): Promise { + console.log('Finding matching credentials with filter:', filter); + try { + const matchingCredentials = await client.credentials().list({ filter }); + console.log(`Found ${matchingCredentials.length} matching credentials.`); + return matchingCredentials; + } catch (error) { + console.error('Failed to find matching credentials:', error); + throw error; + } +} + +/** + * Submits an IPEX offer (presents a credential). + * @param {SignifyClient} client - The SignifyClient instance of the holder. + * @param {string} senderAidAlias - The alias of the AID offering the credential. + * @param {string} recipientAidPrefix - The AID prefix of the verifier. + * @param {any} acdcSad - The Self-Addressing Data (SAD) of the ACDC being offered. + * @param {string} applySaid - The SAID of the IPEX apply message this offer is responding to. + * @param {string} datetime - The timestamp for the offer. + * @returns {Promise<{ operation: Operation }>} The operation details. + */ +export async function ipexOfferCredential( + client: SignifyClient, + senderAidAlias: string, + recipientAidPrefix: string, + acdcSad: any, // This is the SAD of the credential to be offered + applySaid: string, + datetime: string +): Promise<{ operation: Operation }> { + console.log(`AID "${senderAidAlias}" offering credential to AID "${recipientAidPrefix}" in response to apply "${applySaid}"...`); + try { + const [offer, sigs, end] = await client.ipex().offer({ + senderName: senderAidAlias, + recipient: recipientAidPrefix, + acdc: new Serder(acdcSad), // The credential SAD needs to be wrapped in Serder + applySaid: applySaid, + datetime: datetime, + }); + + const offerOperationDetails = await client + .ipex() + .submitOffer(senderAidAlias, offer, sigs, end, [recipientAidPrefix]); + + const completedOperation = await client + .operations() + .wait(offerOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + throw new Error(`IPEX offer submission failed: ${JSON.stringify(completedOperation.error)}`); + } + console.log(`Successfully submitted IPEX offer in response to apply "${applySaid}".`); + await client.operations().delete(completedOperation.name); + return { operation: completedOperation }; + } catch (error) { + console.error('Failed to submit IPEX offer:', error); + throw error; + } +} + +/** + * Submits an IPEX agree (verifier agrees to the offered credential). + * @param {SignifyClient} client - The SignifyClient instance of the verifier. + * @param {string} senderAidAlias - The alias of the AID agreeing to the offer. + * @param {string} recipientAidPrefix - The AID prefix of the holder who made the offer. + * @param {string} offerSaid - The SAID of the IPEX offer message being agreed to. + * @param {string} datetime - The timestamp for the agree. + * @returns {Promise<{ operation: Operation }>} The operation details. + */ +export async function ipexAgreeToOffer( + client: SignifyClient, + senderAidAlias: string, + recipientAidPrefix: string, + offerSaid: string, + datetime: string +): Promise<{ operation: Operation }> { + console.log(`AID "${senderAidAlias}" agreeing to IPEX offer "${offerSaid}" from AID "${recipientAidPrefix}"...`); + try { + const [agree, sigs, _] = await client.ipex().agree({ + senderName: senderAidAlias, + recipient: recipientAidPrefix, + offerSaid: offerSaid, + datetime: datetime, + }); + + const agreeOperationDetails = await client + .ipex() + .submitAgree(senderAidAlias, agree, sigs, [recipientAidPrefix]); + + const completedOperation = await client + .operations() + .wait(agreeOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + + if (completedOperation.error) { + throw new Error(`IPEX agree submission failed: ${JSON.stringify(completedOperation.error)}`); + } + console.log(`Successfully submitted IPEX agree for offer "${offerSaid}".`); + await client.operations().delete(completedOperation.name); + return { operation: completedOperation }; + } catch (error) { + console.error('Failed to submit IPEX agree:', error); + throw error; + } +} + + + + + + + + + + + + + + + + + + + + + + +// --- Example Usage --- +export async function test() { + try { + await initializeSignify(); + + // --- Client A (Alfred) Setup --- + console.log('\n--- Initializing Client A (Alfred) ---'); + const { client: clientA, clientState: clientAState } = await initializeAndConnectClient(randomPasscode()); + const alfredClientAID = clientAState?.controller?.state?.i || 'Unknown Client AID A'; + const aidAAlias = 'alfredPrimaryAID'; + console.log('\n--- Creating AID for Alfred ---'); + const { aid: aidAObj} = await createNewAID(clientA, aidAAlias, DEFAULT_IDENTIFIER_ARGS); + const aidAPrefix = aidAObj?.i || 'Unknown AID A Prefix'; + console.log(`Alfred's primary AID: ${aidAPrefix}`); + console.log('\n--- Adding Agent End Role for Alfred ---'); + await addEndRoleForAID(clientA, aidAAlias, 'agent'); + console.log('\n--- Generating OOBI for Alfred ---'); + const alfredOOBI = await generateOOBI(clientA, aidAAlias, 'agent'); + + // --- Client B (Betty) Setup --- + console.log('\n\n--- Initializing Client B (Betty) ---'); + const { client: clientB, clientState: clientBState } = await initializeAndConnectClient(randomPasscode()); + const bettyClientAID = clientBState?.controller?.state?.i || 'Unknown Client AID B'; + const aidBAlias = 'bettyPrimaryAID'; + console.log('\n--- Creating AID for Betty ---'); + const { aid: aidBObj } = await createNewAID(clientB, aidBAlias, DEFAULT_IDENTIFIER_ARGS); + const aidBPrefix = aidBObj?.i || 'Unknown AID B Prefix'; + console.log(`Betty's primary AID: ${aidBPrefix}`); + console.log('\n--- Adding Agent End Role for Betty ---'); + await addEndRoleForAID(clientB, aidBAlias, 'agent'); + console.log('\n--- Generating OOBI for Betty ---'); + const bettyOOBI = await generateOOBI(clientB, aidBAlias, 'agent'); + + // --- OOBI Resolution --- + console.log('\n\n--- Betty resolving Alfred\'s OOBI ---'); + const contactAlfredAlias = 'AlfredsContactForBetty'; + await resolveOOBI(clientB, alfredOOBI, contactAlfredAlias); + + console.log('\n--- Alfred resolving Betty\'s OOBI ---'); + const contactBettyAlias = 'BettysContactForAlfred'; + await resolveOOBI(clientA, bettyOOBI, contactBettyAlias); + + // --- Challenge/Response: Alfred challenges Betty --- + console.log("\n\n--- MUTUAL AUTHENTICATION ---"); + console.log("\n--- Alfred challenges Betty ---"); + + // 1. Alfred generates challenge words for Betty + const alfredChallengeForBetty = await generateChallengeWords(clientA); + + // (Assume words are securely transmitted out-of-band to Betty) + + // 2. Betty responds to Alfred's challenge + console.log(`\nBetty (AID: ${aidBPrefix}) responding to Alfred's (AID: ${aidAPrefix}) challenge...`); + await respondToChallenge(clientB, aidBAlias, aidAPrefix, alfredChallengeForBetty); + + // 3. Alfred verifies Betty's response + console.log(`\nAlfred (AID: ${aidAPrefix}) verifying Betty's (AID: ${aidBPrefix}) response...`); + const verificationBetty = await verifyChallengeResponse(clientA, aidBPrefix, alfredChallengeForBetty); + + // 4. Alfred marks Betty as authenticated if verification succeeded + if (verificationBetty.verified && verificationBetty.said) { + await markChallengeAuthenticated(clientA, aidBPrefix, verificationBetty.said); + console.log(`Alfred has successfully authenticated Betty (AID: ${aidBPrefix}).`); + } else { + console.error(`Alfred failed to authenticate Betty (AID: ${aidBPrefix}).`); + } + + // --- Challenge/Response: Betty challenges Alfred --- + console.log("\n--- Betty challenges Alfred ---"); + + // 1. Betty generates challenge words for Alfred + const bettyChallengeForAlfred = await generateChallengeWords(clientB); + + // (Assume words are securely transmitted out-of-band to Alfred) + + // 2. Alfred responds to Betty's challenge + console.log(`\nAlfred (AID: ${aidAPrefix}) responding to Betty's (AID: ${aidBPrefix}) challenge...`); + await respondToChallenge(clientA, aidAAlias, aidBPrefix, bettyChallengeForAlfred); + + // 3. Betty verifies Alfred's response + console.log(`\nBetty (AID: ${aidBPrefix}) verifying Alfred's (AID: ${aidAPrefix}) response...`); + const verificationAlfred = await verifyChallengeResponse(clientB, aidAPrefix, bettyChallengeForAlfred); + + // 4. Betty marks Alfred as authenticated if verification succeeded + if (verificationAlfred.verified && verificationAlfred.said) { + await markChallengeAuthenticated(clientB, aidAPrefix, verificationAlfred.said); + console.log(`Betty has successfully authenticated Alfred (AID: ${aidAPrefix}).`); + } else { + console.error(`Betty failed to authenticate Alfred (AID: ${aidAPrefix}).`); + } + + console.log('\n\n--- Example scenario with mutual authentication completed! ---'); + console.log(`Alfred's Client AID: ${alfredClientAID}, Primary AID: ${aidAPrefix}`); + console.log(`Betty's Client AID: ${bettyClientAID}, Primary AID: ${aidBPrefix}`); + + // You can inspect contacts to see authentication status + const alfredsContacts = await clientA.contacts().list(); + console.log("\nAlfred's contacts:", JSON.stringify(alfredsContacts, null, 2)); + const bettysContacts = await clientB.contacts().list(); + console.log("\nBetty's contacts:", JSON.stringify(bettysContacts, null, 2)); + } catch (error) { + console.error('\n--- An error occurred in the main example: ---', error); + } +} diff --git a/scripts/demo/vlei/up.sh b/scripts/demo/vlei/up.sh new file mode 100755 index 0000000..fb47fa5 --- /dev/null +++ b/scripts/demo/vlei/up.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# +# Bring up the vLEI ecosystem (witnesses + schema server + KERIA + +# vlei-verifier + signify Deno runner) and wait for the verifier to come green +# and the signify container to finish pre-caching its deps. The whole stack — +# including the SignifyTS runner — lives in this one compose file; no second +# repo is required. +# +# Usage: +# scripts/demo/vlei/up.sh +# +# Env overrides: +# COMPOSE docker compose command (default: "docker compose") +# VERIFIER_URL verifier base URL to health-check (default: http://localhost:7676) + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +export DATA="${DATA:-$(cd "$SCRIPT_DIR/../../.." && pwd)/data/demo/vlei}" +# shellcheck source=../common.sh +. "$SCRIPT_DIR/../common.sh" + +COMPOSE="${COMPOSE:-docker compose}" +VERIFIER_URL="${VERIFIER_URL:-http://localhost:7676}" + +require_cmd docker +require_cmd curl + +header "vLEI ecosystem — up" +note "compose file: $SCRIPT_DIR/docker-compose.yml" + +# shellcheck disable=SC2086 # COMPOSE may be a multi-word command +$COMPOSE -f "$SCRIPT_DIR/docker-compose.yml" up -d --build + +note "waiting for vlei-verifier /health at $VERIFIER_URL …" +for _ in $(seq 1 60); do + if curl -fsS "$VERIFIER_URL/health" >/dev/null 2>&1; then + ok "vlei-verifier healthy at $VERIFIER_URL" + break + fi + sleep 2 +done + +if ! curl -fsS "$VERIFIER_URL/health" >/dev/null 2>&1; then + fail "vlei-verifier did not become healthy — check '$COMPOSE -f $SCRIPT_DIR/docker-compose.yml logs'" +fi + +# The signify container pre-caches its npm deps at start and touches /tmp/ready +# when done; probe that marker so the first `deno run` exec is fast. exec needs +# the container running (it is — it idles on tail), and returns non-zero until +# the marker exists. +note "waiting for the signify container to finish caching deps …" +signify_ready() { + # shellcheck disable=SC2086 # COMPOSE may be a multi-word command + $COMPOSE -f "$SCRIPT_DIR/docker-compose.yml" exec -T signify test -f /tmp/ready >/dev/null 2>&1 +} +for _ in $(seq 1 60); do + if signify_ready; then + ok "signify container ready" + break + fi + sleep 2 +done + +if ! signify_ready; then + fail "signify container did not become ready — check '$COMPOSE -f $SCRIPT_DIR/docker-compose.yml logs signify'" +fi + +header "Next steps" +note "Run the whole flow with one command: $SCRIPT_DIR/run-vlei.sh" +note " (requires ans-ra running with vlei.base-url=$VERIFIER_URL)" +note "Or step by step:" +note " 1. $SCRIPT_DIR/build-chain.sh — build the chain + present + export (headless)" +note " 2. $SCRIPT_DIR/verify-control-demo.sh — RA-mediated present + verify-control" diff --git a/scripts/demo/vlei/verify-control-demo.sh b/scripts/demo/vlei/verify-control-demo.sh new file mode 100755 index 0000000..82e9a15 --- /dev/null +++ b/scripts/demo/vlei/verify-control-demo.sh @@ -0,0 +1,259 @@ +#!/usr/bin/env bash +# +# vLEI demo: drive the ans-ra RA-mediated register-with-presentation + +# verify-control flow end-to-end against a REAL vlei-verifier, on the +# identity-scoped /v2/ans/identities routes. +# +# register+present → POST /v2/ans/identities +# { value: $LEI, vleiPresentation:{ cesr: $CESR } } +# the RA reads the leaf credential SAID out of the CESR, +# presents the full chain to the verifier itself, pins the +# verifier-reported subject AID on the identity, and +# returns the challenge round (nonce + signingInput) plus +# the advisory presentationStatus. +# sign → the HOLDER signs the served `signingInput` (NOT the bare +# nonce) with the role AID via signify (sign-proof.ts in +# the signify container) — see below. +# re-present → re-POST /v2/ans/identities (same body) while the row is +# PENDING_CONTROL to refresh the verifier's authorization +# window (it ages off after 10 minutes). Returns the SAME +# identityId with a fresh nonce; if the signingInput +# rotated, re-sign it. +# verify-control → POST /v2/ans/identities/{identityId}/verify-control +# { cesrSignature: $SIG } → status: VERIFIED (the RA pins +# the signer AID to the identity; it is never a body value) +# link → POST /v2/ans/identities/{identityId}/links +# { agentIds: [ $AGENT_ID ] } → { linked: 1 } +# show → GET /v2/ans/agents/{agentId} → the computed identities[] +# badge carries the lei identity; poll the TL identity +# audit for the sealed IDENTITY_VERIFIED. +# +# +# WHY sign the signingInput, not the nonce: the lei control proof is uniform +# with the JWS kinds — every kind signs the served `signingInput` (the +# base64url of the JCS-canonical IdentityProofInput), which binds the nonce, +# the identity id, the identifier, and the proof purpose. The RA forwards the +# signature to the verifier as `non_prefixed_digest = signingInput`. +# +# WHY re-present right before verify: the vlei-verifier ages credential +# authorizations off after TimeoutAuth = 600s (10 minutes). verify-control +# re-checks authorization LIVE on every call (it does NOT trust the AUTHORIZED +# status recorded at present time), so a slow manual signing step can let the +# window lapse — surfacing as LEI_NOT_AUTHORIZED even though the signature is +# valid. Re-presenting immediately before the verify keeps the window fresh. +# +# The RA is the SINGLE touchpoint for the verifier: this script never calls the +# verifier directly. build-chain.ts and sign-proof.ts only register the +# synthetic GLEIF root of trust, export the holder's full-chain CESR + LEI, and +# sign the signingInput with the holder key; everything else flows through the RA. +# +# PRECONDITIONS (manual — see README.md): +# 1. vLEI stack is up: scripts/demo/vlei/up.sh +# 2. ans-ra is running with vlei.type: verifier and vlei.base-url pointing at +# the verifier (the `vlei:` block in config/ra-local.yaml). +# 3. An agent owned by the same caller is registered and its id is in +# $AGENT_ID (e.g. from scripts/demo/run-lifecycle.sh). +# 4. build-chain.sh has run (scripts/demo/vlei/build-chain.sh) — it registered +# the root of trust and exported $PRESENTATION_FILE (the holder's +# full-chain CESR + claimed LEI + holder AID) and, for AUTO_SIGN, +# $OUTPUTS_FILE (which carries the holder's roleBran). The signify +# container stays up so the signingInput can be signed with the holder AID. +# +# Required env: +# AGENT_ID the registered agent to link the verified lei identity to +# +# Env overrides: +# PRESENTATION_FILE exported {cesr,lei,aid} JSON +# (default: $DATA/ecr-presentation.json) +# OUTPUTS_FILE exported {roleBran,...} JSON, used by AUTO_SIGN +# (default: alongside PRESENTATION_FILE / tier1-outputs.json) +# LEI claimed LEI (default: read from PRESENTATION_FILE) +# SIGNED_PROOF the signature over the signingInput (indexed Siger qb64). +# When set, the script uses it directly — highest +# precedence. NOTE: a re-present that rotates the nonce +# invalidates a pre-computed SIGNED_PROOF; prefer AUTO_SIGN +# for the live flow. +# AUTO_SIGN when 1 (and SIGNED_PROOF unset), sign the signingInput +# non-interactively by running sign-proof.ts in the signify +# container with the roleBran from $OUTPUTS_FILE. Falls back +# to the interactive /dev/tty paste when unset. +# COMPOSE docker compose command (default: "docker compose") +# RA_URL ans-ra base URL (default: http://localhost:18080) + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +export DATA="${DATA:-$(cd "$SCRIPT_DIR/../../.." && pwd)/data/demo/vlei}" +# shellcheck source=../common.sh +. "$SCRIPT_DIR/../common.sh" + +PRESENTATION_FILE="${PRESENTATION_FILE:-$DATA/ecr-presentation.json}" +OUTPUTS_FILE="${OUTPUTS_FILE:-$(dirname "$PRESENTATION_FILE")/tier1-outputs.json}" +COMPOSE="${COMPOSE:-docker compose}" + +require_cmd curl +require_cmd jq + +: "${AGENT_ID:?set AGENT_ID to the registered agent id}" +[ -f "$PRESENTATION_FILE" ] || fail "presentation file not found: $PRESENTATION_FILE — run build-chain.sh (README step 2) so it exports the artifacts" + +CESR="$(jq -r '.cesr' "$PRESENTATION_FILE")" +[ -n "$CESR" ] && [ "$CESR" != "null" ] || fail "no .cesr in $PRESENTATION_FILE" +LEI="${LEI:-$(jq -r '.lei' "$PRESENTATION_FILE")}" +[ -n "$LEI" ] && [ "$LEI" != "null" ] || fail "no LEI — set \$LEI or add .lei to $PRESENTATION_FILE" +# The holder AID is the credential's subject — exported by build-chain.ts and +# the value the RA pins at register time (read from the verifier, not the body). +# We use it only to sanity-check the challenge's kid; the RA derives it itself. +HOLDER_AID="$(jq -r '.aid // empty' "$PRESENTATION_FILE")" + +header "RA-mediated register + verify-control demo (identity routes)" +note "RA: $RA_URL verifier-backed agent: $AGENT_ID LEI: $LEI" +[ -n "$HOLDER_AID" ] && note "holder AID (credential subject): $HOLDER_AID" + +# register_identity — POST /v2/ans/identities { value, vleiPresentation }. +# Echoes the raw response body on stdout so the caller can extract fields and +# fail with the body on a non-2xx. The validate MUST live in the caller, not +# here: this runs inside a $(...) subshell, where `fail` (exit 1) only ends the +# subshell — under `set -e` that does NOT abort the parent. +register_identity() { + local body + body="$(jq -n --arg v "$LEI" --arg cesr "$CESR" \ + '{value:$v, vleiPresentation:{cesr:$cesr}}')" + curl_json POST "/v2/ans/identities" "$body" +} + +# sign_signing_input SIGNING_INPUT — apply the SIGNED_PROOF > AUTO_SIGN > +# interactive-paste precedence and echo ONLY the signature on stdout. The role +# AID's keys live in the KERIA cloud agent, so every path signs with signify. +sign_signing_input() { + local signing_input="$1" sig role_bran + if [ -n "${SIGNED_PROOF:-}" ]; then + printf '%s' "$SIGNED_PROOF" + return 0 + fi + if [ "${AUTO_SIGN:-0}" = "1" ]; then + [ -f "$OUTPUTS_FILE" ] || { echo "AUTO_SIGN=1 but $OUTPUTS_FILE not found — run build-chain.sh first" >&2; return 1; } + role_bran="$(jq -r '.roleBran // empty' "$OUTPUTS_FILE")" + [ -n "$role_bran" ] || { echo "no .roleBran in $OUTPUTS_FILE — re-run build-chain.sh" >&2; return 1; } + # sign-proof.ts prints ONLY the indexed Siger qb64 on stdout; diagnostics + # go to stderr, so command substitution captures just the signature. + # shellcheck disable=SC2086 # COMPOSE may be a multi-word command + sig="$($COMPOSE -f "$SCRIPT_DIR/docker-compose.yml" exec -T signify \ + deno run -A scripts_ts/sign-proof.ts "$role_bran" "$signing_input")" || return 1 + printf '%s' "$sig" + return 0 + fi + if [ -r /dev/tty ]; then + role_bran="$(jq -r '.roleBran // empty' "$OUTPUTS_FILE" 2>/dev/null)" + note "Sign this signingInput with the holder (role) AID, then paste the result:" >&2 + note " ROLE_BRAN=\$(jq -r .roleBran '$OUTPUTS_FILE')" >&2 + note " $COMPOSE -f $SCRIPT_DIR/docker-compose.yml exec -T signify \\" >&2 + note " deno run -A scripts_ts/sign-proof.ts \"\$ROLE_BRAN\" \"$signing_input\"" >&2 + note "(or just re-run this script with AUTO_SIGN=1 to do it automatically)" >&2 + printf "${C_BOLD}paste cesrSignature here:${C_RESET} " >&2 + IFS= read -r sig " >&2 + return 1 +} + +# ----- 1. register+present: RA presents to the verifier, pins the AID ----- +header "1. register+present — POST /v2/ans/identities { value, vleiPresentation }" +note "the RA reads the leaf SAID from the CESR and presents the chain itself" +REG_RESP="$(register_identity)" +IDENTITY_ID="$(printf '%s' "$REG_RESP" | jq -r '.identityId // empty')" +[ -n "$IDENTITY_ID" ] || fail "register did not return an identityId — response: $REG_RESP" +PRESENTATION_STATUS="$(printf '%s' "$REG_RESP" | jq -r '.presentationStatus // empty')" +NONCE="$(printf '%s' "$REG_RESP" | jq -r '.nonce // empty')" +SUBJECT_AID="$(printf '%s' "$REG_RESP" | jq -r '.challenges[0].kid // empty')" +SIGNING_INPUT="$(printf '%s' "$REG_RESP" | jq -r '.challenges[0].signingInput // empty')" +[ -n "$SIGNING_INPUT" ] || fail "register did not return a challenge signingInput — response: $REG_RESP" +ok "identity recorded: $IDENTITY_ID presentationStatus: ${PRESENTATION_STATUS:-}" +note "subject AID (challenge kid): $SUBJECT_AID" +note "nonce: $NONCE" +if [ -n "$HOLDER_AID" ] && [ -n "$SUBJECT_AID" ] && [ "$SUBJECT_AID" != "$HOLDER_AID" ]; then + fail "challenge kid ($SUBJECT_AID) != exported holder AID ($HOLDER_AID) — the signingInput must be signed by the credential subject, so these must match" +fi + +# ----- 2. holder signs the signingInput with the role AID (signify) ----- +header "2. Holder signs the signingInput with the role AID (signify)" +SIG="$(sign_signing_input "$SIGNING_INPUT")" || fail "sign failed — is the signify container up? ($COMPOSE -f $SCRIPT_DIR/docker-compose.yml logs signify)" +SIG="$(printf '%s' "$SIG" | tr -d '[:space:]')" +[ -n "$SIG" ] || fail "no cesrSignature provided" +ok "signature over signingInput: $SIG" + +# ----- 3. re-present: refresh the verifier's 10-min authorization window ----- +# verify-control checks authorization LIVE; the manual signing step above is +# human-paced and may exceed TimeoutAuth (600s). Re-POSTing the same value +# while PENDING_CONTROL is the idempotent re-add: it refreshes the window and +# returns the SAME identityId with a fresh nonce. If the nonce rotated, the +# signingInput changed too, so we re-sign it. +header "3. re-present — refresh the verifier's authorization window" +note "the verifier ages authorizations off after 10 minutes; re-present keeps it fresh" +REPRESENT_RESP="$(register_identity)" +REPRESENTED_ID="$(printf '%s' "$REPRESENT_RESP" | jq -r '.identityId // empty')" +[ -n "$REPRESENTED_ID" ] || fail "re-present did not return an identityId — response: $REPRESENT_RESP" +[ "$REPRESENTED_ID" = "$IDENTITY_ID" ] || fail "re-present returned a different identityId ($REPRESENTED_ID != $IDENTITY_ID) — the idempotent re-add must reuse the row" +SIGNING_INPUT2="$(printf '%s' "$REPRESENT_RESP" | jq -r '.challenges[0].signingInput // empty')" +[ -n "$SIGNING_INPUT2" ] || fail "re-present did not return a challenge signingInput — response: $REPRESENT_RESP" +ok "re-presented (same identity): $REPRESENTED_ID" +if [ "$SIGNING_INPUT2" != "$SIGNING_INPUT" ]; then + note "nonce rotated on re-present — re-signing the new signingInput" + SIGNING_INPUT="$SIGNING_INPUT2" + SIG="$(sign_signing_input "$SIGNING_INPUT")" || fail "re-sign failed" + SIG="$(printf '%s' "$SIG" | tr -d '[:space:]')" + [ -n "$SIG" ] || fail "no cesrSignature provided on re-sign" + ok "re-signed over the fresh signingInput: $SIG" +fi + +# ----- 4. verify-control: RA verifies signature + authorized LEI, pins the AID ----- +header "4. verify-control — POST .../verify-control { cesrSignature }" +note "no aid in the body — the RA pins the signer AID to the recorded identity" +VERIFY_BODY="$(jq -n --arg sig "$SIG" '{cesrSignature:$sig}')" +VERIFY_RESP="$(curl_json POST "/v2/ans/identities/$IDENTITY_ID/verify-control" "$VERIFY_BODY")" +STATUS="$(printf '%s' "$VERIFY_RESP" | jq -r '.status // empty')" +if [ "$STATUS" = "VERIFIED" ]; then + ok "status:VERIFIED — the AID controls a vLEI authorizing $LEI, and signed our challenge" +else + CODE="$(printf '%s' "$VERIFY_RESP" | jq -r '.code // "unknown"')" + DETAIL="$(printf '%s' "$VERIFY_RESP" | jq -r '.detail // empty')" + case "$CODE" in + PRICC_SIGNATURE_INVALID) + fail "verify-control failed (code=$CODE) — the cesrSignature was not signed by the role AID over THIS signingInput. Make sure sign-proof.ts signed the served signingInput with the 'role' alias, not a kli/other key." ;; + LEI_NOT_AUTHORIZED) + fail "verify-control failed (code=$CODE) — the verifier reports no authorized LEI for the AID right now. Confirm the root of trust is registered (build-chain.sh) and the chain authorizes this LEI; if signing took >10 min, just re-run the demo." ;; + LEI_MISMATCH) + fail "verify-control failed (code=$CODE) — the verifier authorized a different LEI than $LEI. Check the credential's LEI matches the claim." ;; + *) + fail "verify-control failed (code=$CODE): ${DETAIL:-no detail} — response: $VERIFY_RESP" ;; + esac +fi + +# The sealed IDENTITY_VERIFIED reaches the TL through the outbox worker. +header "verify the seal landed on the TL identity stream" +poll_tl_identity_audit "$IDENTITY_ID" 1 +ok "IDENTITY_VERIFIED sealed with a Merkle proof on the TL" + +# ----- 5. link: bind the verified identity to the agent (one event) ----- +header "5. link — POST .../links { agentIds: [ $AGENT_ID ] }" +LINK_BODY="$(jq -n --arg a "$AGENT_ID" '{agentIds:[$a]}')" +LINK_RESP="$(curl_json POST "/v2/ans/identities/$IDENTITY_ID/links" "$LINK_BODY")" +LINKED="$(printf '%s' "$LINK_RESP" | jq -r '.linked // empty')" +[ "$LINKED" = "1" ] || fail "link did not report linked:1 — response: $LINK_RESP" +ok "linked: 1" + +# ----- 6. show: the computed identities[] badge on the agent ----- +header "6. show — GET /v2/ans/agents/$AGENT_ID (computed identities[] badge)" +AGENT_RESP="$(curl_json GET "/v2/ans/agents/$AGENT_ID")" +BADGE_KIND="$(printf '%s' "$AGENT_RESP" | jq -r --arg id "$IDENTITY_ID" \ + '.identities[]? | select(.identityId==$id) | .kind // empty')" +BADGE_STATUS="$(printf '%s' "$AGENT_RESP" | jq -r --arg id "$IDENTITY_ID" \ + '.identities[]? | select(.identityId==$id) | .identityStatus // empty')" +[ "$BADGE_KIND" = "lei" ] || fail "agent identities[] does not carry the lei badge for $IDENTITY_ID — response: $AGENT_RESP" +[ "$BADGE_STATUS" = "VERIFIED" ] || fail "lei badge status is '$BADGE_STATUS', expected VERIFIED — response: $AGENT_RESP" +ok "agent carries the lei identity badge: $IDENTITY_ID (VERIFIED)" + +header "Done" +note "register-with-presentation pins the verifier-reported subject AID; verify-control" +note "is a single CESR-signature proof over the served signingInput (uniform with the" +note "JWS kinds), and the RA pins the signer AID to the identity — never a body value." diff --git a/scripts/demo/vlei/witness-config/main/wan.json b/scripts/demo/vlei/witness-config/main/wan.json new file mode 100755 index 0000000..ffb1dab --- /dev/null +++ b/scripts/demo/vlei/witness-config/main/wan.json @@ -0,0 +1,8 @@ +{ + "wan": { + "dt": "2024-12-31T14:06:30.123456+00:00", + "curls": ["tcp://witness-demo:5632/", "http://witness-demo:5642/"] + }, + "dt": "2024-12-31T14:06:30.123456+00:00", + "iurls": [] +} diff --git a/scripts/demo/vlei/witness-config/main/wes.json b/scripts/demo/vlei/witness-config/main/wes.json new file mode 100755 index 0000000..d84b0db --- /dev/null +++ b/scripts/demo/vlei/witness-config/main/wes.json @@ -0,0 +1,8 @@ +{ + "wes": { + "dt": "2024-12-31T14:06:30.123456+00:00", + "curls": ["tcp://witness-demo:5634/", "http://witness-demo:5644/"] + }, + "dt": "2024-12-31T14:06:30.123456+00:00", + "iurls": [] +} diff --git a/scripts/demo/vlei/witness-config/main/wil.json b/scripts/demo/vlei/witness-config/main/wil.json new file mode 100755 index 0000000..22a5fb0 --- /dev/null +++ b/scripts/demo/vlei/witness-config/main/wil.json @@ -0,0 +1,8 @@ +{ + "wil": { + "dt": "2024-12-31T14:06:30.123456+00:00", + "curls": ["tcp://witness-demo:5633/", "http://witness-demo:5643/"] + }, + "dt": "2024-12-31T14:06:30.123456+00:00", + "iurls": [] +} diff --git a/scripts/demo/vlei/witness-config/main/wit.json b/scripts/demo/vlei/witness-config/main/wit.json new file mode 100755 index 0000000..ddef257 --- /dev/null +++ b/scripts/demo/vlei/witness-config/main/wit.json @@ -0,0 +1,8 @@ +{ + "wit": { + "dt": "2024-12-31T14:06:30.123456+00:00", + "curls": ["tcp://witness-demo:5635/", "http://witness-demo:5645/"] + }, + "dt": "2024-12-31T14:06:30.123456+00:00", + "iurls": [] +} diff --git a/scripts/demo/vlei/witness-config/main/wub.json b/scripts/demo/vlei/witness-config/main/wub.json new file mode 100755 index 0000000..10970b2 --- /dev/null +++ b/scripts/demo/vlei/witness-config/main/wub.json @@ -0,0 +1,8 @@ +{ + "wub": { + "dt": "2024-12-31T14:06:30.123456+00:00", + "curls": ["tcp://witness-demo:5636/", "http://witness-demo:5646/"] + }, + "dt": "2024-12-31T14:06:30.123456+00:00", + "iurls": [] +} diff --git a/scripts/demo/vlei/witness-config/main/wyz.json b/scripts/demo/vlei/witness-config/main/wyz.json new file mode 100755 index 0000000..19b228a --- /dev/null +++ b/scripts/demo/vlei/witness-config/main/wyz.json @@ -0,0 +1,8 @@ +{ + "wyz": { + "dt": "2024-12-31T14:06:30.123456+00:00", + "curls": ["tcp://witness-demo:5637/", "http://witness-demo:5647/"] + }, + "dt": "2024-12-31T14:06:30.123456+00:00", + "iurls": [] +} diff --git a/spec/api-spec-tl-v2.yaml b/spec/api-spec-tl-v2.yaml index 4664a78..78cdcf7 100644 --- a/spec/api-spec-tl-v2.yaml +++ b/spec/api-spec-tl-v2.yaml @@ -1203,17 +1203,25 @@ components: conveniences (anyone can derive RFC 7638 from the sealed source) and are never part of the sealed contract. - The postponed `lei` kind is the one deliberate exception: - it will seal the subject AID + a key thumbprint only — there - is no document to quote, the ACDC is PII, and KERI's KEL is - already the authoritative key history. Seal verbatim what - has no other tamper-evident home; commit minimally where one - exists. + The `lei` kind is the one deliberate exception: it seals the + subject AID + a key thumbprint only (`{id: , type: + "vLEI-KERI-AID", thumbprint: base64url(SHA-256(AID))}`) — + there is no document to quote, the ACDC is PII, and KERI's + KEL is already the authoritative key history. Seal verbatim + what has no other tamper-evident home; commit minimally where + one exists. A `lei` seal is therefore NOT offline + re-verifiable from the seal alone: the KEL-backed key state + lives at the vlei-verifier (the documented lei trust + boundary), whereas a JWS seal carries the key material and so + the sealed proof re-verifies offline. required: [verificationMethod, signedProof] properties: verificationMethod: type: object - description: The DID document's verification-method object, verbatim + description: | + For JWS kinds, the DID document's verification-method + object, verbatim. For `lei`, the synthesized subject-AID + object (`id`, `type: vLEI-KERI-AID`, `thumbprint`). example: id: did:web:identity.acme-corp.com#key-1 type: JsonWebKey2020 @@ -1221,7 +1229,10 @@ components: publicKeyJwk: { kty: OKP, crv: Ed25519, x: "0-e2i2_..." } signedProof: type: string - description: The compact JWS over the served IdentityProofInput + description: | + The proof over the served IdentityProofInput — a compact + JWS for the JWS kinds, or the CESR signature by the + subject AID's current key for `lei`. LinkedIdentityView: type: object diff --git a/spec/api-spec-v2.yaml b/spec/api-spec-v2.yaml index 5b17e4e..90d48a2 100644 --- a/spec/api-spec-v2.yaml +++ b/spec/api-spec-v2.yaml @@ -927,9 +927,12 @@ paths: is the idempotent re-add: the same `identityId` returns with a fresh nonce (the prior nonce is superseded). A value already verified — by this owner or any other — returns 409 - `IDENTIFIER_DUPLICATE`. Kinds without an enabled control - verifier (`lei`, postponed) return 422 - `IDENTIFIER_KIND_UNSUPPORTED`. + `IDENTIFIER_DUPLICATE`. A recognized value whose kind has no + enabled control verifier (e.g. `did:plc`, `did:ion`, until + 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`. operationId: registerIdentity requestBody: required: true @@ -2056,16 +2059,38 @@ components: description: | Registers (POST) or rotates (PUT) an identifier. The kind is inferred from the value's lexical form — `did:web:` prefix, - `did:key:` prefix, or a 20-character LEI (recognized but - postponed) — never caller-asserted. + `did:key:` prefix, or a 20-character LEI — never + caller-asserted. properties: value: type: string description: The identifier to prove control of example: did:web:identity.acme-corp.com + vleiPresentation: + $ref: '#/components/schemas/VLEIPresentation' required: - value + VLEIPresentation: + type: object + description: | + The lei (vLEI) register-time credential presentation. REQUIRED + for the `lei` kind and omitted for the JWS kinds (`did:web`, + `did:key`). The RA submits the CESR to its configured + vlei-verifier, which derives and pins the subject AID; the + 202's `presentationStatus` reports the verifier's advisory + authorization decision. + properties: + cesr: + type: string + description: | + The full-chain CESR export of the vLEI credential and its + supporting KELs/ACDCs (the `credentials().get(said, true)` + shape). The RA never parses KERI key state itself — the + verifier is the authoritative key-state oracle. + required: + - cesr + IdentityChallengeResponse: type: object description: | @@ -2086,6 +2111,15 @@ components: description: The canonical identifier this round proves status: $ref: '#/components/schemas/IdentityLifecycleStatus' + presentationStatus: + type: string + description: | + The lei register-time advisory authorization status from + the vlei-verifier (`AUTHORIZED` | `PENDING`). Omitted for + kinds with no register-time presentation (`did:web`, + `did:key`). Advisory only — control is finally established + by a LIVE re-authorization at verify-control. + enum: ['AUTHORIZED', 'PENDING'] nonce: type: string description: Base64url 32-byte single-use anti-replay nonce @@ -2128,11 +2162,20 @@ components: VerifyControlRequest: type: object description: | - One compact JWS per proven key. Supported algorithms match - what the verifier implements: EdDSA (Ed25519), ES256 - (ECDSA P-256), and RS256 (RSA >= 2048). Key-agreement keys - (X25519) and curves without a verifier (secp256k1, - P-384/521) are rejected with a precise error. + The control proof. Its members are additive per identifier + kind, and EXACTLY ONE family is set per request: + + - JWS kinds (`did:web`, `did:key`) submit `signedProofs` — + one compact JWS per proven key. + - The `lei` kind submits `cesrSignature` — a single CESR + signature over the served signingInput by the subject + AID's current key. + + Supported JWS algorithms match what the verifier implements: + EdDSA (Ed25519), ES256 (ECDSA P-256), and RS256 (RSA >= + 2048). Key-agreement keys (X25519) and curves without a + verifier (secp256k1, P-384/521) are rejected with a precise + error. properties: signedProofs: type: array @@ -2146,8 +2189,18 @@ components: and MAY carry `jwk` (the signer's public key — required by the quickstart noop resolver, ignored by the web resolver, which always uses the resolved document). - required: - - signedProofs + cesrSignature: + type: string + description: | + The lei proof: a single CESR signature over the served + signingInput by the subject AID's current key. Set only + for the `lei` kind. The RA forwards it to the + vlei-verifier, which resolves the AID's key state from its + KEL and checks the signature over the exact signingInput + bytes (the same payload the JWS kinds sign). + oneOf: + - required: [signedProofs] + - required: [cesrSignature] IdentityLifecycleStatus: type: string From a28030e08fbcf6edc24bdf26d425c3666f903c1b Mon Sep 17 00:00:00 2001 From: James Hateley Date: Fri, 12 Jun 2026 15:52:25 +1000 Subject: [PATCH 02/21] feat: fix after rebase Signed-off-by: James Hateley --- internal/adapter/store/sqlite/identity.go | 7 ++++++- ...entity_subject_aid.sql => 009_identity_subject_aid.sql} | 0 internal/ra/handler/identity_handler_test.go | 1 - internal/ra/service/identity.go | 2 +- internal/ra/service/identity_lei_test.go | 4 ++-- 5 files changed, 9 insertions(+), 5 deletions(-) rename internal/adapter/store/sqlite/migrations/{008_identity_subject_aid.sql => 009_identity_subject_aid.sql} (100%) diff --git a/internal/adapter/store/sqlite/identity.go b/internal/adapter/store/sqlite/identity.go index 35a10a6..3406c77 100644 --- a/internal/adapter/store/sqlite/identity.go +++ b/internal/adapter/store/sqlite/identity.go @@ -316,6 +316,10 @@ func (s *IdentityStore) StageChallenge( if !v.Challenge.ExpiresAt.IsZero() { expires = sql.NullInt64{Int64: v.Challenge.ExpiresAt.UnixMilli(), Valid: true} } + var subjectAID sql.NullString + if v.SubjectAID != "" { + subjectAID = sql.NullString{String: v.SubjectAID, Valid: true} + } res, err := s.db.extx(ctx).ExecContext(ctx, ` UPDATE identities SET challenge_nonce = ?, @@ -323,12 +327,13 @@ func (s *IdentityStore) StageChallenge( challenge_consumed_at_ms = NULL, challenge_claimed_at_ms = NULL, pending_value = ?, + subject_aid = ?, updated_at_ms = ? WHERE identity_id = ? AND status = ? AND (challenge_nonce = ? OR (challenge_nonce IS NULL AND ? = '')) AND (challenge_claimed_at_ms IS NULL OR challenge_claimed_at_ms < ?)`, - v.Challenge.Nonce, expires, v.PendingValue, v.UpdatedAt.UnixMilli(), + v.Challenge.Nonce, expires, v.PendingValue, subjectAID, v.UpdatedAt.UnixMilli(), v.IdentityID, string(expectedStatus), expectedNonce, expectedNonce, staleBefore.UnixMilli()) if err != nil { diff --git a/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql b/internal/adapter/store/sqlite/migrations/009_identity_subject_aid.sql similarity index 100% rename from internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql rename to internal/adapter/store/sqlite/migrations/009_identity_subject_aid.sql diff --git a/internal/ra/handler/identity_handler_test.go b/internal/ra/handler/identity_handler_test.go index 1d1c134..796c8a2 100644 --- a/internal/ra/handler/identity_handler_test.go +++ b/internal/ra/handler/identity_handler_test.go @@ -89,7 +89,6 @@ func newIdentityHTTPFixture(t *testing.T) *identityHTTPFixture { didresolver.NewNoopResolver(), okSealer{}, leiverifier.NewNoop(), - outbox, db, ).WithChallengeTTL(30 * time.Minute) diff --git a/internal/ra/service/identity.go b/internal/ra/service/identity.go index 2b16ec6..d0e4756 100644 --- a/internal/ra/service/identity.go +++ b/internal/ra/service/identity.go @@ -326,7 +326,7 @@ func (s *IdentityService) Rotate(ctx context.Context, providerID, identityID, ra if err := identity.StageRotation(rawValue, now); err != nil { return nil, err } - return s.challenge(ctx, identity, now, true, opt) + return s.challenge(ctx, identity, now, false, opt) } // challenge mints a fresh nonce on the identity, runs the kind's diff --git a/internal/ra/service/identity_lei_test.go b/internal/ra/service/identity_lei_test.go index 7cd03af..4ae8e6e 100644 --- a/internal/ra/service/identity_lei_test.go +++ b/internal/ra/service/identity_lei_test.go @@ -96,11 +96,11 @@ func TestIdentityLifecycle_LEIHappy(t *testing.T) { t.Fatalf("verified state: %+v", identity) } - rows := fx.drainOutbox(t) + rows := fx.drainSealed(t) if len(rows) != 1 { t.Fatalf("outbox rows: %d", len(rows)) } - inner := fx.decodeOutboxEvent(t, rows[0]) + inner := fx.decodeSealed(t, rows[0]) if inner.EventType != identityevent.TypeIdentityVerified || len(inner.Keys) != 1 { t.Fatalf("sealed event: %+v", inner) } From e283ddcc38f5b81603f89ca5995617afec8c7fbd Mon Sep 17 00:00:00 2001 From: James Hateley Date: Sat, 13 Jun 2026 11:28:29 +1000 Subject: [PATCH 03/21] feat(vlei): whitespace-tolerant ACDC frame scan + demo cleanup 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 --- .gitignore | 3 + .../adapter/leiverifier/leiverifier_test.go | 3 + internal/adapter/leiverifier/verifier.go | 25 +- scripts/demo/start.sh | 5 +- scripts/demo/vlei/README.md | 336 ++++------- scripts/demo/vlei/build-chain.sh | 6 +- scripts/demo/vlei/docker-compose.yml | 2 +- scripts/demo/vlei/down.sh | 2 +- scripts/demo/vlei/run-vlei.sh | 101 +++- .../vlei/signify/scripts_ts/build-chain.ts | 16 +- scripts/demo/vlei/signify/scripts_ts/utils.ts | 528 ------------------ scripts/demo/vlei/verify-control-demo.sh | 6 +- 12 files changed, 237 insertions(+), 796 deletions(-) diff --git a/.gitignore b/.gitignore index ba9a85e..948de1a 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,6 @@ Thumbs.db # Dependency directories vendor/ AGENTS.md + +# Demo outputs +scripts/demo/vlei/signify/out/ \ No newline at end of file diff --git a/internal/adapter/leiverifier/leiverifier_test.go b/internal/adapter/leiverifier/leiverifier_test.go index 23b4a9d..91d139d 100644 --- a/internal/adapter/leiverifier/leiverifier_test.go +++ b/internal/adapter/leiverifier/leiverifier_test.go @@ -323,6 +323,9 @@ func TestPresentedCredentialSAID(t *testing.T) { {"escaped strings before d", `{"v":"ACDC10JSON_","note":"a \"quoted\" }brace","d":"EReal"}`, "EReal"}, {"unterminated object", `{"v":"ACDC10JSON_","d":"x"`, ""}, {"marker but no d, then a real one", `{"v":"ACDC10JSON_","x":1}{"v":"ACDC10JSON_","d":"ESecond"}`, "ESecond"}, + // Insignificant JSON whitespace around `{`, the `v` key, and the + // colon must not defeat the frame scan (pretty-printed export). + {"whitespace around version member", "{ \"v\" :\t\"ACDC10JSON_\", \"d\": \"EWS\" }", "EWS"}, // Full-chain exports: the leaf is the credential no other // credential's edge `n` references — independent of frame order. // KERIA emits issuer-first (leaf last); we must not pick the first. diff --git a/internal/adapter/leiverifier/verifier.go b/internal/adapter/leiverifier/verifier.go index 9f35421..afc39c7 100644 --- a/internal/adapter/leiverifier/verifier.go +++ b/internal/adapter/leiverifier/verifier.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "net/http" + "regexp" "strings" "time" @@ -321,15 +322,24 @@ func isQB64(s string) bool { return true } +// acdcFrameMarker matches the start of an ACDC credential frame: a JSON +// object whose first member is the version string `"v":"ACDC…"`. The +// pattern tolerates insignificant JSON whitespace around the `{`, key, +// and colon so a serializer that pretty-prints (or inserts SP/HT) does +// not cause the scan to miss frames. It is deliberately anchored on the +// version member being first, which the KERI/ACDC serialization rules +// guarantee. +var acdcFrameMarker = regexp.MustCompile(`\{\s*"v"\s*:\s*"ACDC`) + // presentedCredentialSAID extracts the SAID of the *presented* (leaf) // credential from a full-chain CESR export — the minimal, targeted read // the real verifier path needs to route PUT /presentations/{said}. It is // NOT a CESR codec: KERI/ACDC serializations are version-string-first, so // an ACDC credential message is always a JSON object whose first member -// is `"v":"ACDC…"`; we locate those frames by brace-balancing (respecting -// JSON string escaping), read each frame's self-addressing `d`, and -// collect the edge node SAIDs (the `n` of each edge) from each frame's -// `e` block. +// is `"v":"ACDC…"`; we locate those frames with acdcFrameMarker and read +// each one by brace-balancing (respecting JSON string escaping), take its +// self-addressing `d`, and collect the edge node SAIDs (the `n` of each +// edge) from each frame's `e` block. // // The presented credential is the most-derived one — the ECR/role // credential at the bottom of the ECR→LE→QVI chain — identified @@ -341,7 +351,6 @@ func isQB64(s string) bool { // so its one frame is the leaf. The end-to-end demo (scripts/demo/vlei) // exercises this against the live verifier. func presentedCredentialSAID(cesr string) string { - const marker = `{"v":"ACDC` type acdcFrame struct { D string `json:"d"` E json.RawMessage `json:"e"` @@ -350,11 +359,11 @@ func presentedCredentialSAID(cesr string) string { referenced := make(map[string]struct{}) offset := 0 for { - rel := strings.Index(cesr[offset:], marker) - if rel < 0 { + loc := acdcFrameMarker.FindStringIndex(cesr[offset:]) + if loc == nil { break } - start := offset + rel + start := offset + loc[0] obj, end := balancedJSONObject(cesr, start) if obj == "" { offset = start + 1 diff --git a/scripts/demo/start.sh b/scripts/demo/start.sh index 1f14d78..6971eda 100755 --- a/scripts/demo/start.sh +++ b/scripts/demo/start.sh @@ -210,10 +210,7 @@ vlei: # The lei (vLEI) control verifier behind the "lei" identifier kind. # "noop" runs real Ed25519 crypto but waives the GLEIF authorization # binding; "verifier" routes CESR/KERI questions to a real - # vlei-verifier (scripts/demo/vlei brings one up on :7676). The - # base-url can't be set via ANS_RA_VLEI__BASE_URL — koanf maps a - # single underscore literally, so it would target vlei.base_url, not - # vlei.base-url — hence it is composed into the file here: + # vlei-verifier (scripts/demo/vlei brings one up on :7676). # ANS_VLEI_TYPE=verifier ANS_VLEI_BASE_URL=http://localhost:7676 \ # scripts/demo/start.sh type: ${ANS_VLEI_TYPE:-noop} diff --git a/scripts/demo/vlei/README.md b/scripts/demo/vlei/README.md index 7f2a5c5..06209d2 100644 --- a/scripts/demo/vlei/README.md +++ b/scripts/demo/vlei/README.md @@ -1,48 +1,32 @@ -# vLEI ecosystem + identifier / `verify-control` demo +# vLEI ecosystem + `verify-control` demo -This directory stands up a **local, self-contained** GLEIF/KERI stack so -a genuine AID holding a (self-issued) vLEI can be registered with the RA -on the identity-scoped routes — `POST /v2/ans/identities` (carrying the -full-chain CESR) + `.../verify-control` — and the RA can present it to, -and verify the AID-signed `signingInput` against, a **real -`vlei-verifier`**, seal the `IDENTITY_VERIFIED` event on the TL, and link -the verified `lei` identity to an agent. - -Proves the *RA integration* against the stock -GLEIF verifier, including the credential-chain / authorized-LEI check. +A **local, self-contained** GLEIF/KERI stack that proves the RA's `lei` +identity flow against a **real `vlei-verifier`**: a genuine AID holding a +self-issued vLEI is registered on `POST /v2/ans/identities` (carrying the +full-chain CESR), the RA presents the chain to the verifier and verifies the +AID-signed `signingInput` via `.../verify-control`, seals `IDENTITY_VERIFIED` +on the TL, and links the verified `lei` identity to an agent — including the +credential-chain / authorized-LEI check. ## No genuine LEI/vLEI required -The entire ecosystem is self-issued against a **synthetic local GLEIF -root** registered via `POST /root_of_trust/{aid}` (the verifier runs -with `VERIFIER_ENV=development`, `VERIFY_ROOT_OF_TRUST=True`). The LEI is -any well-formed 20-char string you choose — the verifier checks the -chain to *your* local root, not `api.gleif.org`. The RA's `ValidateLEI` +The whole chain is self-issued against a **synthetic local GLEIF root** +registered via `POST /root_of_trust/{aid}` (verifier runs with +`VERIFIER_ENV=development`, `VERIFY_ROOT_OF_TRUST=True`). The verifier checks +the chain to *your* local root, not `api.gleif.org`. The RA's `ValidateLEI` checks ISO-17442 **format only** (20-char `[A-Z0-9]`), so any well-formed -string works; `build-chain.ts` uses LEI `875500ELOZEL05BVXV37`. +string works; `build-chain.ts` uses `875500ELOZEL05BVXV37`. A genuine vLEI is +needed *only* against the real GLEIF production root — out of scope here. -A genuine vLEI is needed *only* if you point the verifier at the real -GLEIF production root — out of scope here. +## The RA is the single touchpoint for the verifier -## Notes -- **Everything is version-pinned for reproducibility.** GLEIF's - KERI/KERIA/vLEI images and the `vlei-verifier` config schema move - between releases, so the compose file pins every image to a known-good - tag (`weboftrust/keri:1.2.0-rc4`, `gleif/vlei:1.0.0`, - `gleif/keria:0.3.0`) and builds the verifier from the `0.1.5` source. - The verifier uses its own bundled `verifier-config-docker-local.json` - (keri-style `iurls`/`durls` pointing at `witness-demo` + `vlei-server`), - so there is no local config file to keep in sync. Bumping any pin means - re-confirming flags/endpoints and the config shape against that release. -- **The RA is the single touchpoint for the verifier.** The holder hands - the RA their full-chain credential CESR via the `vleiPresentation` of - `POST /v2/ans/identities`; the RA reads the leaf credential SAID out of - it (the only thing it parses — never KERI key state), presents the chain - to the verifier (`PUT /presentations/{said}`), reads the verifier-reported - subject AID, and pins it on the identity. The holder never calls the - verifier directly. The one bootstrap the RA can't do is registering the - *synthetic local* GLEIF root of trust — that is a one-time admin step - against the verifier (`build-chain.ts` does it). +The holder hands the RA the full-chain CESR in the `vleiPresentation` of `POST +/v2/ans/identities`. The RA reads the leaf credential SAID out of it (the only +thing it parses — never KERI key state), presents the chain to the verifier +(`PUT /presentations/{said}`), reads back the subject AID, and pins it on the +identity. The holder never calls the verifier directly. The one thing the RA +can't bootstrap is registering the synthetic local GLEIF root of trust — a +one-time admin step `build-chain.ts` does. ## Components (`docker-compose.yml`) @@ -52,105 +36,90 @@ GLEIF production root — out of scope here. | `vlei-server` | `gleif/vlei:1.0.0` | 7723 | ACDC schema + OOBI server (LE/OOR/ECR/QVI) | | `keria` | `gleif/keria:0.3.0` | 3901-3903 | KERIA edge agent for the holder (signify-ts) | | `vlei-verifier` | built from source @ `0.1.5` | **7676** | the service `ans-ra` calls | -| `signify` | `denoland/deno:alpine-2.8.2` | — | runs `build-chain.ts` (build chain, present, export) and `sign-proof.ts` | - -> `vlei-verifier` is not published to any registry, so the compose file -> builds it from the pinned [`GLEIF-IT/vlei-verifier`](https://github.com/GLEIF-IT/vlei-verifier) -> `0.1.5` tag via a git build context. The first `up.sh` therefore runs a -> `docker build` (git clone + `pip install`) that takes a few minutes; later -> runs reuse the cached `ans-vlei-verifier:0.1.5` image. The verifier loads -> its **bundled** `verifier-config-docker-local.json` (selected via -> `VERIFIER_CONFIG_FILE`), which already points at this stack's `witness-demo` -> and `vlei-server` hostnames — there is no local config file to edit. - -> **The SignifyTS runner is self-contained.** The `signify` service is the -> stock `denoland/deno` image — no custom build. It bind-mounts -> [`signify/`](signify/) in this directory, which holds the demo's -> [`scripts_ts/`](signify/scripts_ts/): `build-chain.ts` (the trust-chain build, -> converted from the old `ans-vlei-verifier.ipynb`), `sign-proof.ts` (the -> standalone proof signer), and `utils.ts` (the SignifyTS helpers, vendored from -> [GLEIF-IT/vlei-trainings](https://github.com/GLEIF-IT/vlei-trainings)). The -> container is on the same Docker network as the rest of the stack and reaches -> `keria`, `vlei-server`, `witness-demo`, and `vlei-verifier` by service name — -> no external network / `docker network connect` required. On start it pre-caches -> the npm deps (`signify-ts`, `libsodium`) so the first `deno run` is fast. The -> exported artifacts land in [`signify/out/`](signify/out/) via the bind mount. -> When re-vendoring, re-pull `utils.ts` from the upstream repo. - -## End-to-end sequence +| `signify` | `denoland/deno:alpine-2.8.2` | — | Deno runner for `build-chain.ts` + `sign-proof.ts` | + +Everything is version-pinned: GLEIF's KERI/KERIA/vLEI images and the verifier +config schema move between releases, so bumping any pin means re-confirming +flags, endpoints, and config shape against that release. + +- **`vlei-verifier` is built, not pulled** — it ships to no registry, so the + compose file builds it from the pinned + [`GLEIF-IT/vlei-verifier`](https://github.com/GLEIF-IT/vlei-verifier) `0.1.5` + tag via a git build context. The first `up.sh` runs a `docker build` (git + clone + `pip install`) taking a few minutes; later runs reuse the cached + `ans-vlei-verifier:0.1.5` image. It loads its **bundled** + `verifier-config-docker-local.json` (`VERIFIER_CONFIG_FILE`), already pointed + at this stack's `witness-demo` + `vlei-server` hostnames — no local config to + edit. +- **`signify` is the stock Deno image** — no custom build. It bind-mounts + [`signify/`](signify/), holding [`scripts_ts/`](signify/scripts_ts/): + `build-chain.ts` (trust-chain build), `sign-proof.ts` (proof signer), and + `utils.ts` (SignifyTS helpers vendored from + [GLEIF-IT/vlei-trainings](https://github.com/GLEIF-IT/vlei-trainings) — + re-pull on re-vendor). It reaches the other services by name on the shared + network and pre-caches its npm deps at start. Exports land in + [`signify/out/`](signify/out/) via the bind mount. + +## Run it + +No prerequisites — `run-vlei.sh` bootstraps everything with **no manual paste**: -### Prerequisites (the RA — once) - -The vLEI stack is self-contained, but the RA owns its own lifecycle, so two -RA-side steps happen first: - -1. **Enable the verifier wiring.** Set the `vlei:` block in - `config/ra-local.yaml` to the real verifier (it ships as `type: noop`): - ```yaml - vlei: - type: verifier - base-url: "http://localhost:7676" - ``` - The identity routes (`POST /v2/ans/identities`, `.../verify-control`, - `.../links`) are always registered — `did:web`/`did:key` use them too. - `vlei.type` only selects which control verifier backs the `lei` kind: - `noop` runs real Ed25519 crypto but waives the GLEIF authorization - binding (zero-infra quickstart), while `verifier` routes every - CESR/KERI question to this stack's `vlei-verifier`. The real end-to-end - flow below requires `type: verifier`. -2. **Start the RA and register an agent.** `scripts/demo/start.sh` starts - `ans-ra`; `scripts/demo/run-lifecycle.sh` registers an agent and writes its - id to `data/demo/vlei/last-agent-id`. That id is the `AGENT_ID` below. +```bash +scripts/demo/vlei/run-vlei.sh # add --down to tear everything down after +``` -### Commands +It starts `ans-ra` (+ `ans-tl`) in verifier mode, registers an agent, brings up +the stack, builds the chain, and runs the register + verify-control flow. +Re-running is safe: a running RA and a previously-registered agent are reused. + +**Why "mode" matters.** `vlei.type` selects the `lei` control verifier: `noop` +runs real Ed25519 crypto but waives the GLEIF authorization binding (zero-infra +quickstart); `verifier` routes every CESR/KERI question to this stack's +`vlei-verifier`. This demo presents **real CESR**, which only `verifier` +accepts. So `run-vlei.sh` guarantees verifier mode — starting the RA in it if +down, or restarting via `stop.sh` + `start.sh --keep` (preserves the registered +agent, SQLite store, and signer keys) if it's running in the `noop` default. +The identity routes are always registered regardless (`did:web`/`did:key` use +them too). Editing `config/ra-local.yaml` has no effect here: `start.sh` +composes its config from `ANS_VLEI_*` env vars. To start in verifier mode up +front and skip the mid-run restart: ```bash -ANS_VLEI_TYPE=verifier ANS_VLEI_BASE_URL=http://localhost:7676 ./scripts/demo/start.sh -AGENT_ID=$(scripts/demo/register.sh --v2) -scripts/demo/vlei/run-vlei.sh +ANS_VLEI_TYPE=verifier ANS_VLEI_BASE_URL=http://localhost:7676 scripts/demo/start.sh ``` -`run-vlei.sh` checks the RA is reachable, then chains the three steps below -with **no manual paste**: - -1. **`up.sh`** — build + start the whole stack (witnesses, vlei-server, KERIA, - vlei-verifier, signify Deno runner) on one Docker network; wait for the - verifier's `/health` (`:7676`) and for the `signify` container to finish - pre-caching its deps. The first run includes a `docker build` of the - verifier image and the signify container's npm-dep download, which together - take a few minutes; later runs reuse the cached image and deps. -2. **`build-chain.sh`** — run [`build-chain.ts`](signify/scripts_ts/build-chain.ts) - via `deno run` in the `signify` container. It builds the synthetic - `GLEIF → QVI(delegated) → LE → ECR` chain, issues the ECR to the `role` - holder AID (LEI `875500ELOZEL05BVXV37`), presents it via IPEX, **registers - the local `gleif` root of trust** at the verifier, and exports two files into - the bind-mounted [`signify/out/`](signify/out/) dir: - - `ecr-presentation.json` — `{cesr, lei, aid}` the shell hands to the RA; - - `tier1-outputs.json` — carries the holder's `roleBran` for the signer. -3. **`verify-control-demo.sh`** (invoked with `AUTO_SIGN=1` and `DATA` pointed - at `build-chain.ts`'s exports) — the RA-mediated register + verify-control flow: - - `POST /v2/ans/identities { value: , vleiPresentation:{ cesr } }` — the - RA reads the leaf SAID, presents the chain to the verifier, pins the - verifier-reported subject AID, and returns the challenge round (nonce + - `signingInput`) plus the advisory `presentationStatus`; - - **auto-sign** — runs [`sign-proof.ts`](signify/scripts_ts/sign-proof.ts) - inside the `signify` container, reconstructing `roleClient` from the - exported `roleBran` and signing the served `signingInput` with the `role` - AID's KERIA-held keys; +### What `run-vlei.sh` chains + +0. **ensure ans-ra + agent** — RA up in verifier mode (per above), then + `register.sh --v2` if `AGENT_ID` / `data/demo/last-agent-id` names none. +1. **`up.sh`** — build + start the stack on one Docker network; wait for the + verifier's `/health` (`:7676`) and for `signify` to finish pre-caching deps. +2. **`build-chain.sh`** — runs + [`build-chain.ts`](signify/scripts_ts/build-chain.ts) via `deno run` in the + `signify` container: builds the synthetic `GLEIF → QVI(delegated) → LE → ECR` + chain, issues the ECR to the `role` holder AID, presents it via IPEX, + **registers the local `gleif` root of trust**, and exports into + [`signify/out/`](signify/out/): + - `ecr-presentation.json` — `{cesr, lei, aid}` the shell hands the RA; + - `holder-state.json` — the holder's `roleBran` for the signer. +3. **`verify-control-demo.sh`** (`AUTO_SIGN=1`, `DATA` → the exports) — the + register + verify-control flow: + - `POST /v2/ans/identities { value:, vleiPresentation:{cesr} }` — RA + reads the leaf SAID, presents the chain, pins the subject AID, returns the + challenge (nonce + `signingInput`) + advisory `presentationStatus`; + - **auto-sign** — [`sign-proof.ts`](signify/scripts_ts/sign-proof.ts) + reconstructs `roleClient` from `roleBran` and signs the `signingInput` with + the `role` AID's KERIA-held keys; - **re-present** — re-POST the same body while `PENDING_CONTROL` to refresh the verifier's authorization window (same `identityId`, fresh nonce); - `POST .../verify-control { cesrSignature }` — **no aid in the body**; the - RA pins the signer AID to the identity → expects `status: VERIFIED`, - then polls the TL for the sealed `IDENTITY_VERIFIED`; - - `POST .../links { agentIds: [ ] }` then - `GET /v2/ans/agents/` → the computed `identities[]` badge - carries the verified `lei` identity. - -Add `--down` to tear the stack down after a successful run. + RA pins the signer AID → expects `status: VERIFIED`, then polls the TL for + the sealed `IDENTITY_VERIFIED`; + - `POST .../links { agentIds:[] }`, then + `GET /v2/ans/agents/` → the computed `identities[]` badge carries + the verified `lei` identity. -### Step by step / fallback - -Each stage is runnable on its own: +### Run stages individually ```bash scripts/demo/vlei/up.sh # stack @@ -160,103 +129,46 @@ AGENT_ID= DATA=scripts/demo/vlei/signify/out \ scripts/demo/vlei/down.sh # tear down ``` -**Manual signing fallback.** To sign by hand, run `verify-control-demo.sh` -**without** `AUTO_SIGN`: it prints the served `signingInput`, then prints the -exact `deno run … sign-proof.ts ` command to sign it -in the `signify` container. Run that, copy the printed signature (indexed Siger -qb64, e.g. `AAB…`), and paste it back at the prompt. You can also pass a -signature non-interactively with `SIGNED_PROOF=`. +**Manual signing fallback.** Run `verify-control-demo.sh` **without** +`AUTO_SIGN`: it prints the served `signingInput` and the exact `deno run … +sign-proof.ts ` command. Run it, copy the printed +signature (indexed Siger qb64, e.g. `AAB…`), paste it at the prompt. Or pass it +non-interactively with `SIGNED_PROOF=`. The `lei` control proof is uniform with the JWS kinds: every kind signs the -served `signingInput` (the base64url of the JCS-canonical `IdentityProofInput`, -which binds the nonce, the identity id, the identifier, and the proof purpose). -The RA forwards the signature to the verifier as `non_prefixed_digest = signingInput`. +served `signingInput` (base64url of the JCS-canonical `IdentityProofInput`, +binding the nonce, identity id, identifier, and proof purpose). The RA forwards +the signature to the verifier as `non_prefixed_digest = signingInput`. + +**The 10-minute authorization window.** The verifier ages authorizations off +after `TimeoutAuth = 600s`, and `verify-control` re-checks authorization +**live** on every call — so a slow manual signing step can lapse the window and +surface as `LEI_NOT_AUTHORIZED` even with a valid signature. The script +re-presents the chain immediately before the verify to reset the window; if you +still hit it, just re-run. -**The 10-minute authorization window.** The `vlei-verifier` ages credential -authorizations off after `TimeoutAuth = 600s`. `verify-control` re-checks -authorization **live** on every call, so a slow manual signing step can lapse -the window and surface as `LEI_NOT_AUTHORIZED` even with a valid signature. The -script re-presents the chain (the idempotent re-add) immediately before the -verify to reset the window; if you still hit it, just re-run. +**Re-registering the root of trust by hand.** `build-chain.sh` does it for you. +If the verifier was restarted (its DB is in-container and ephemeral) and you +need to re-register without re-running the chain build: -**Registering the root of trust by hand.** `build-chain.sh` registers it for -you; if the verifier was restarted (its DB is in-container and ephemeral) and -you need to re-register without re-running the chain build, the raw call is: ```bash curl -X POST http://localhost:7676/root_of_trust/{gleifRootAID} \ -H 'Content-Type: application/json' \ -d '{"vlei":"","oobi":""}' ``` -## Troubleshooting - -### Step 1 (QVI Credential) fails with `unknown AID` - -Symptom — the IPEX grant in *Step 1* dies with: - -``` -HTTP POST /identifiers/gleif/ipex/grant - 400 Bad Request -{"description": "attempt to send to unknown AID="} -``` - -and the keria container loops forever on: - -``` -ERROR eventing .processEscrowDelegables Kevery unescrow failed: No delegation seal found for event. -keri.kering.MissingDelegableApprovalError: No delegation seal found for event. -INFO routing .acceptReply Revery: escrowing without key state for signer on reply ... -``` - -**Cause.** A *previous* run approved the QVI delegation incorrectly — e.g. -older setup code using `identifiers().interact()` (which only anchors -the seal) instead of `delegations().approve()` (which also ingests the -QVI's `dip`). That leaves a QVI `dip` that can never be promoted, churning -in gleif's `delegables` escrow. Because `gleif` uses a **fixed bran** (so -the same gleif agent is reused on every run) and the compose file mounts -**no data volume** for keria (agent DBs live in the container's ephemeral -writable layer), this poison survives across runs — and a plain -`docker compose restart keria` does **not** clear it (same container, same -writable layer). - -**Fix.** Recreate the keria container to wipe all agent state, then re-run -the chain build: - -```bash -docker compose -f scripts/demo/vlei/docker-compose.yml \ - up -d --force-recreate keria -``` - -gleif comes back with the **same prefix** (it is deterministic from the -fixed bran), so any root-of-trust registration still matches. Then just -re-run `scripts/demo/vlei/build-chain.sh`. `build-chain.ts` already uses -`delegations().approve()` in a retry loop, so on a clean keria the -delegation completes and the QVI credential grants/admits cleanly. - -### Benign noise - -`Unverified loc scheme reply URL=… SAID=…` (a `/loc/scheme` reply, often -with a `dt` of `2024-12-31`) is **not** an error you need to chase — it is -transient witness-resolution churn that self-resolves once the witness KEL -loads. Only delegation/escrow errors (`MissingDelegableApprovalError`, -`escrowing without key state`) indicate the poisoned-agent state above. - ## Scope -This implements the **RA-mediated register-with-presentation + -verify-control** flow for the `lei` identifier kind on the identity-scoped -`/v2/ans/identities` routes: +The `lei` kind on the identity-scoped `/v2/ans/identities` routes: -- The RA is the single touchpoint for the verifier: `POST /v2/ans/identities` - carries the holder's full-chain CESR in `vleiPresentation`, the RA presents - it and pins the verifier-reported subject AID on the identity; - `.../verify-control` is a CESR-signature proof over the served `signingInput` - that **pins the signer AID to the identity** — never a request-body value. -- On a clean verify the RA seals an `IDENTITY_VERIFIED` event on the identity's - TL stream (the demo polls the TL identity audit for it), and `.../links` - binds the verified `lei` identity to an agent so it surfaces in the agent's - computed `identities[]` badge. +- `POST /v2/ans/identities` carries the full-chain CESR; the RA presents it and + pins the verifier-reported subject AID. `.../verify-control` is a + CESR-signature proof over the served `signingInput` that **pins the signer + AID to the identity** — never a request-body value. +- On a clean verify the RA seals `IDENTITY_VERIFIED` on the identity's TL + stream, and `.../links` binds the verified `lei` identity to an agent so it + surfaces in the agent's computed `identities[]` badge. - The seal commits the subject AID + a thumbprint only (no JWK, no document): the KEL-backed key state lives at the verifier, so a `lei` seal is **not** - offline-re-verifiable from the seal alone — the documented `lei` trust - boundary (`ans-verify` enforces the AID+thumbprint shape, not an offline - signature re-check). + offline-re-verifiable from the seal alone. `ans-verify` enforces the + AID+thumbprint shape, not an offline signature re-check. diff --git a/scripts/demo/vlei/build-chain.sh b/scripts/demo/vlei/build-chain.sh index 14443f3..96e9bfb 100755 --- a/scripts/demo/vlei/build-chain.sh +++ b/scripts/demo/vlei/build-chain.sh @@ -9,7 +9,7 @@ # On success build-chain.ts has written, into the bind-mounted out dir # (host: scripts/demo/vlei/signify/out/): # - ecr-presentation.json {cesr, lei, aid} consumed by verify-control-demo.sh -# - tier1-outputs.json {roleBran, ...} consumed by the nonce signer +# - holder-state.json {roleBran, ...} consumed by the nonce signer # # Usage: # scripts/demo/vlei/build-chain.sh @@ -42,7 +42,7 @@ $COMPOSE -f "$COMPOSE_FILE" exec -T signify deno run -A "$SCRIPT" ok "build script executed" # Assert the exported artifacts landed on the host via the bind mount. -for f in ecr-presentation.json tier1-outputs.json; do +for f in ecr-presentation.json holder-state.json; do if [ ! -s "$OUT_DIR/$f" ]; then fail "expected $OUT_DIR/$f to exist and be non-empty after the run — check the output above" fi @@ -50,5 +50,5 @@ for f in ecr-presentation.json tier1-outputs.json; do done header "Chain build complete" -note "ecr-presentation.json + tier1-outputs.json are in $OUT_DIR" +note "ecr-presentation.json + holder-state.json are in $OUT_DIR" note "next: $SCRIPT_DIR/verify-control-demo.sh (or run-vlei.sh for the full flow)" diff --git a/scripts/demo/vlei/docker-compose.yml b/scripts/demo/vlei/docker-compose.yml index dc842bc..019456d 100644 --- a/scripts/demo/vlei/docker-compose.yml +++ b/scripts/demo/vlei/docker-compose.yml @@ -181,7 +181,7 @@ services: # second exec (sign-proof.ts) reuses build-chain.ts's downloads. - DENO_DIR=/deno-dir # Bind the signify dir so edits are live AND the exported artifacts - # (out/ecr-presentation.json, out/tier1-outputs.json) land on the host for + # (out/ecr-presentation.json, out/holder-state.json) land on the host for # the shell demo to consume. volumes: - ./signify:/app diff --git a/scripts/demo/vlei/down.sh b/scripts/demo/vlei/down.sh index 001f156..7710a75 100755 --- a/scripts/demo/vlei/down.sh +++ b/scripts/demo/vlei/down.sh @@ -13,7 +13,7 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" export DATA="${DATA:-$(cd "$SCRIPT_DIR/../../.." && pwd)/data/demo/vlei}" -# shellcheck source=../../common.sh +# shellcheck source=../common.sh . "$SCRIPT_DIR/../common.sh" COMPOSE="${COMPOSE:-docker compose}" diff --git a/scripts/demo/vlei/run-vlei.sh b/scripts/demo/vlei/run-vlei.sh index 4caffbb..333716d 100755 --- a/scripts/demo/vlei/run-vlei.sh +++ b/scripts/demo/vlei/run-vlei.sh @@ -1,37 +1,44 @@ #!/usr/bin/env bash # -# One-command vLEI verify-control demo. +# One-command vLEI verify-control demo — fully standalone. # -# Chains the whole self-contained flow: -# 1. up.sh — bring up the stack (witnesses, vlei-server, KERIA, -# vlei-verifier, signify Deno runner) on one network. -# 2. build-chain.sh — run build-chain.ts headless: build the synthetic -# vLEI trust chain, issue the ECR to the holder AID, -# present it, register the local GLEIF root of trust, -# and export ecr-presentation.json + tier1-outputs.json. +# Bootstraps everything the flow needs and chains it end-to-end with no manual steps: +# 0. ensure ans-ra — start ans-ra (+ ans-tl) in the real vlei +# "verifier" mode if it isn't already running that +# way. The demo presents real CESR, which only the +# verifier backend accepts; the plain start.sh +# default is "noop" (base64url JSON), so a noop RA is +# restarted into verifier mode here. +# 0b. ensure an agent — register one (register.sh --v2) if none exists, to +# link the verified lei identity to. +# 1. up.sh — bring up the stack (witnesses, vlei-server, KERIA, +# vlei-verifier, signify Deno runner) on one network. +# 2. build-chain.sh — run build-chain.ts headless: build the synthetic +# vLEI trust chain, issue the ECR to the holder AID, +# present it, register the local GLEIF root of trust, +# and export ecr-presentation.json + holder-state.json. # 3. verify-control-demo.sh (AUTO_SIGN=1) — RA-mediated register + -# verify-control on /v2/ans/identities, signing the -# served signingInput in-container with the holder -# (role) AID, then linking the verified lei identity -# to the agent. No manual paste. -# -# The RA is NOT started here — it owns its own lifecycle (config + agent -# registration). This script requires it already running with an agent -# registered; it checks both up front and points you at the right script if not. +# verify-control on /v2/ans/identities, signing the +# served signingInput in-container with the holder +# (role) AID, then linking the verified lei identity +# to the agent. No manual paste. # # Usage: -# AGENT_ID=$(scripts/demo/register.sh --v2) # scripts/demo/vlei/run-vlei.sh [--down] # -# Required env: -# AGENT_ID a registered ans agent id (e.g. from scripts/demo/register.sh -# # Flags: -# --down tear the stack down (down.sh) after a successful run. +# --down tear the stack down after a successful run — both the docker +# ecosystem (down.sh) and the ans-ra/ans-tl/ans-dns daemons +# (stop.sh) this run may have started. # # Env overrides: -# COMPOSE docker compose command (default: "docker compose") -# RA_URL ans-ra base URL (default: http://localhost:18080) +# AGENT_ID reuse this already-registered agent instead of +# registering a fresh one (default: the id saved by a +# prior register.sh --v2, else a freshly registered one). +# COMPOSE docker compose command (default: "docker compose") +# RA_URL ans-ra base URL (default: http://localhost:18080) +# VLEI_VERIFIER_URL the vlei-verifier the RA points at in verifier mode +# (default: http://localhost:7676 — the port up.sh exposes) set -euo pipefail @@ -48,18 +55,47 @@ for arg in "$@"; do done OUT_DIR="$SCRIPT_DIR/signify/out" - -# AGENT_ID: from env -[ -n "${AGENT_ID:-}" ] || fail "set AGENT_ID — register an agent first (scripts/demo/register.sh)" +VLEI_VERIFIER_URL="${VLEI_VERIFIER_URL:-http://localhost:7676}" header "vLEI verify-control demo — full run" -note "agent: $AGENT_ID RA: $RA_URL" -# Fail fast if the RA isn't reachable, before standing the stack up. +# 0. Ensure ans-ra is up AND wired to the real vlei-verifier. This demo +# presents real CESR, which only the "verifier" backend accepts; the plain +# start.sh default is "noop" (base64url JSON). Three cases: +# * RA not running → fresh start in verifier mode. +# * RA running, noop mode → restart in verifier mode, preserving data +# (start.sh --keep keeps data/demo: agent id, SQLite store, signer keys; +# the TL still trusts the unchanged RA pubkey). +# * RA running, verifier → leave it. +# The running RA's mode is read from its startup log; start.sh truncates +# ra.log per launch, so the grep reflects the live process. if ! curl -sSf "$RA_URL/v2/admin/ready" >/dev/null 2>&1; then - fail "ans-ra isn't reachable at $RA_URL — run scripts/demo/start.sh first (and ensure the vlei: block in config/ra-local.yaml is enabled)" + note "ans-ra not running — starting ans-ra + ans-tl in vlei verifier mode" + ANS_VLEI_TYPE=verifier ANS_VLEI_BASE_URL="$VLEI_VERIFIER_URL" \ + "$SCRIPT_DIR/../start.sh" +elif grep -Eq 'vleiVerifier=("?)verifier' "$DATA/ra.log" 2>/dev/null; then + ok "ans-ra already in vlei verifier mode" +else + note "ans-ra is in noop vlei mode — restarting in verifier mode (data preserved via --keep)" + "$SCRIPT_DIR/../stop.sh" + ANS_VLEI_TYPE=verifier ANS_VLEI_BASE_URL="$VLEI_VERIFIER_URL" \ + "$SCRIPT_DIR/../start.sh" --keep fi -ok "ans-ra ready at $RA_URL" +ok "ans-ra ready at $RA_URL in vlei verifier mode" + +# 0b. Ensure an agent is registered to link the verified lei identity to. +# Reuse AGENT_ID (env) or the id a prior register.sh --v2 saved; otherwise +# register a fresh one now (the RA is up, so registration can run). +if [ -z "${AGENT_ID:-}" ] && [ -f "$DATA/last-agent-id" ]; then + AGENT_ID=$(cat "$DATA/last-agent-id") +fi +if [ -z "${AGENT_ID:-}" ]; then + note "no agent registered — registering one (register.sh --v2)" + "$SCRIPT_DIR/../register.sh" --v2 >&2 + AGENT_ID=$(cat "$DATA/last-agent-id") +fi +[ -n "${AGENT_ID:-}" ] || fail "agent registration did not produce an id" +note "agent: $AGENT_ID RA: $RA_URL" # 1. stack up "$SCRIPT_DIR/up.sh" @@ -69,11 +105,14 @@ ok "ans-ra ready at $RA_URL" # 3. RA-mediated register + verify-control, auto-signing the signingInput # in-container. DATA points the verify script at build-chain.ts's exported -# artifacts so it finds both ecr-presentation.json and tier1-outputs.json there. +# artifacts so it finds both ecr-presentation.json and holder-state.json there. AGENT_ID="$AGENT_ID" DATA="$OUT_DIR" AUTO_SIGN=1 "$SCRIPT_DIR/verify-control-demo.sh" if [ "$TEARDOWN" = "1" ]; then "$SCRIPT_DIR/down.sh" + # Also stop the ans-ra/ans-tl/ans-dns daemons this run may have started in + # step 0 — down.sh only tears down the docker stack, not the local daemons. + "$SCRIPT_DIR/../stop.sh" fi header "All done" diff --git a/scripts/demo/vlei/signify/scripts_ts/build-chain.ts b/scripts/demo/vlei/signify/scripts_ts/build-chain.ts index 56631bf..803cf27 100644 --- a/scripts/demo/vlei/signify/scripts_ts/build-chain.ts +++ b/scripts/demo/vlei/signify/scripts_ts/build-chain.ts @@ -6,7 +6,7 @@ // LOCAL synthetic GLEIF root of trust at the vlei-verifier, and exports the two // artifacts the shell demo consumes: // - out/ecr-presentation.json {cesr, lei, aid} → verify-control-demo.sh -// - out/tier1-outputs.json {roleBran, ...} → the nonce signer +// - out/holder-state.json {roleBran, ...} → the nonce signer // // This is the headless equivalent of the old Jupyter notebook — same SignifyTS // logic, no notebook/kernel layer. The interactive sign cell is gone entirely; @@ -337,7 +337,7 @@ prContinue(); } // --------------------------------------------------------------------------- -// Step 6 (Path 1): ECR Credential — LE directly issues an Engagement Context +// Step 3: ECR Credential — LE directly issues an Engagement Context // Role credential to the Role holder, chained to the LE's own vLEI credential. // --------------------------------------------------------------------------- { @@ -426,7 +426,13 @@ prContinue(); headers: { "Content-Type": "application/json" }, body: JSON.stringify({ vlei: ecrCesr, oobi: gleifOOBI }), }); - console.log("root_of_trust:", rotResp.status, await rotResp.text()); + const rotBody = await rotResp.text(); + if (!rotResp.ok) { + throw new Error( + `root_of_trust registration failed: ${rotResp.status} ${rotResp.statusText} — ${rotBody}`, + ); + } + console.log("root_of_trust:", rotResp.status, rotBody); // Export {cesr, lei, aid} for the shell demo. The RA parses said+aid out of // the CESR itself and presents it to the verifier on the holder's behalf. @@ -454,6 +460,6 @@ prContinue(); ecrCredentialSaid: ecrCredential.sad.d, gleifOOBI, }; - await Deno.writeTextFile(`${OUT_DIR}/tier1-outputs.json`, JSON.stringify(outputs, null, 2)); - console.log(` wrote ${OUT_DIR}/tier1-outputs.json`); + await Deno.writeTextFile(`${OUT_DIR}/holder-state.json`, JSON.stringify(outputs, null, 2)); + console.log(` wrote ${OUT_DIR}/holder-state.json`); } diff --git a/scripts/demo/vlei/signify/scripts_ts/utils.ts b/scripts/demo/vlei/signify/scripts_ts/utils.ts index c0ca782..51dd866 100644 --- a/scripts/demo/vlei/signify/scripts_ts/utils.ts +++ b/scripts/demo/vlei/signify/scripts_ts/utils.ts @@ -1,5 +1,4 @@ import { - randomPasscode, ready, SignifyClient, Tier, @@ -24,33 +23,12 @@ class Ansi { // Bright/Light versions static readonly BRIGHT_BLACK = '\x1b[90m'; - static readonly BRIGHT_RED = '\x1b[91m'; - static readonly BRIGHT_GREEN = '\x1b[92m'; - static readonly BRIGHT_YELLOW = '\x1b[93m'; static readonly BRIGHT_BLUE = '\x1b[94m'; - static readonly BRIGHT_MAGENTA = '\x1b[95m'; - static readonly BRIGHT_CYAN = '\x1b[96m'; - static readonly BRIGHT_WHITE = '\x1b[97m'; // Background colors - static readonly BG_BLACK = '\x1b[40m'; - static readonly BG_RED = '\x1b[41m'; static readonly BG_GREEN = '\x1b[42m'; static readonly BG_YELLOW = '\x1b[43m'; static readonly BG_BLUE = '\x1b[44m'; - static readonly BG_MAGENTA = '\x1b[45m'; - static readonly BG_CYAN = '\x1b[46m'; - static readonly BG_WHITE = '\x1b[47m'; - - // Bright Background colors - static readonly BG_BRIGHT_BLACK = '\x1b[100m'; - static readonly BG_BRIGHT_RED = '\x1b[101m'; - static readonly BG_BRIGHT_GREEN = '\x1b[102m'; - static readonly BG_BRIGHT_YELLOW = '\x1b[103m'; - static readonly BG_BRIGHT_BLUE = '\x1b[104m'; - static readonly BG_BRIGHT_MAGENTA = '\x1b[105m'; - static readonly BG_BRIGHT_CYAN = '\x1b[106m'; - static readonly BG_BRIGHT_WHITE = '\x1b[107m'; // Styles static readonly BOLD = '\x1b[1m'; @@ -66,10 +44,6 @@ export function prMessage(message: string): void { console.log(`\n${Ansi.BOLD}${Ansi.BRIGHT_BLUE}${message}${Ansi.RESET}\n`); } -export function prAlert(message: string): void { - console.log(`\n${Ansi.BOLD}${Ansi.BG_YELLOW}${Ansi.BRIGHT_BLUE}${message}${Ansi.RESET}\n`); -} - export function prContinue(): void { const message = " You can continue ✅ "; console.log(`\n${Ansi.BOLD}${Ansi.BG_GREEN}${Ansi.BRIGHT_BLACK}${message}${Ansi.RESET}\n\n`); @@ -80,27 +54,6 @@ export function sleep(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } -// Function to check the health of a container -export async function isServiceHealthy(healthCheckUrl: string): Promise { - - console.log(`Checking health at: ${healthCheckUrl}`); - - try { - const response = await fetch(healthCheckUrl); - - if (response.ok) { - console.log(`Received status: ${response.status}. Service is healthy.`); - return true; - } else { - console.warn(`Received a non-ok status: ${response.status}. Service is running but may be unhealthy.`); - return false; - } - } catch (error) { - console.error(`Failed to connect to service. It may be down. Error:`, error.message); - return false; - } -} - // Default KERIA connection parameters (adjust as needed for your environment) export const DEFAULT_ADMIN_URL = 'http://keria:3901'; export const DEFAULT_BOOT_URL = 'http://keria:3903'; @@ -110,8 +63,6 @@ export const DEFAULT_RETRIES = 5; // For retries export const ROLE_AGENT = 'agent' export const IPEX_GRANT_ROUTE = '/exn/ipex/grant' export const IPEX_ADMIT_ROUTE = '/exn/ipex/admit' -export const IPEX_APPLY_ROUTE = '/exn/ipex/apply' -export const IPEX_OFFER_ROUTE = '/exn/ipex/offer' export const SCHEMA_SERVER_HOST = 'http://vlei-server:7723'; export const DEFAULT_IDENTIFIER_ARGS = { @@ -306,113 +257,6 @@ export async function resolveOOBI( } } -/** - * Generates challenge words for authentication. - * @param {SignifyClient} client - The SignifyClient instance. - * @param {number} [strength=128] - The bit strength for the challenge (e.g., 128, 256). - * @returns {Promise} A promise that resolves to an array of challenge words. - */ -export async function generateChallengeWords( - client: SignifyClient, - strength: number = 128 -): Promise { - console.log(`Generating ${strength}-bit challenge words...`); - try { - const challenge = await client.challenges().generate(strength); - console.log('Generated challenge words:', challenge.words); - return challenge.words; - } catch (error) { - console.error('Failed to generate challenge words:', error); - throw error; - } -} - -/** - * Responds to a challenge by signing the words and sending them to the challenger. - * @param {SignifyClient} client - The SignifyClient instance of the responder. - * @param {string} sourceAidAlias - The alias of the AID that is responding (signing). - * @param {string} recipientAidPrefix - The AID prefix of the challenger (to whom the response is sent). - * @param {string[]} challengeWords - The array of challenge words to sign. - * @returns {Promise} A promise that resolves when the response is sent. - */ -export async function respondToChallenge( - client: SignifyClient, - sourceAidAlias: string, - recipientAidPrefix: string, - challengeWords: string[] -): Promise { - console.log(`AID alias '${sourceAidAlias}' responding to challenge from AID '${recipientAidPrefix}'...`); - try { - await client.challenges().respond(sourceAidAlias, recipientAidPrefix, challengeWords); - console.log('Challenge response sent.'); - } catch (error) { - console.error('Failed to respond to challenge:', error); - throw error; - } -} - -/** - * Verifies a challenge response received from another AID. - * @param {SignifyClient} client - The SignifyClient instance of the verifier. - * @param {string} allegedSenderAidPrefix - The AID prefix of the AID that allegedly sent the response. - * @param {string[]} originalChallengeWords - The original challenge words that were sent. - * @returns {Promise<{ verified: boolean; said?: string; operation?: Operation }>} - * A promise that resolves to an object indicating if verification was successful, - * the SAID of the signed exchange message, and the operation details. - */ -export async function verifyChallengeResponse( - client: SignifyClient, - allegedSenderAidPrefix: string, - originalChallengeWords: string[] -): Promise<{ verified: boolean; said?: string; operation?: Operation }> { - console.log(`Verifying challenge response from AID '${allegedSenderAidPrefix}'...`); - try { - const verifyOperation = await client.challenges().verify(allegedSenderAidPrefix, originalChallengeWords); - const completedOperation = await client - .operations() - .wait(verifyOperation, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); - - if (completedOperation.error) { - console.error('Challenge verification failed:', completedOperation.error); - await client.operations().delete(completedOperation.name); - return { verified: false, operation: completedOperation }; - } - - const said = completedOperation.response?.exn?.d; - console.log(`Challenge response verified successfully. SAID of exn: ${said}`); - - await client.operations().delete(completedOperation.name); - - return { verified: true, said: said, operation: completedOperation }; - } catch (error) { - console.error('Failed to verify challenge response:', error); - throw error; - } -} - -/** - * Marks a challenge for a contact as authenticated. - * This is done after successful verification of a challenge response. - * @param {SignifyClient} client - The SignifyClient instance. - * @param {string} contactAidPrefix - The AID prefix of the contact to mark as authenticated. - * @param {string} signedChallengeSaid - The SAID of the signed challenge exchange message (exn). - * @returns {Promise} A promise that resolves when the contact is marked. - */ -export async function markChallengeAuthenticated( - client: SignifyClient, - contactAidPrefix: string, - signedChallengeSaid: string -): Promise { - console.log(`Marking challenge for contact AID '${contactAidPrefix}' as authenticated with SAID '${signedChallengeSaid}'...`); - try { - await client.challenges().responded(contactAidPrefix, signedChallengeSaid); - console.log(`Contact AID '${contactAidPrefix}' marked as authenticated.`); - } catch (error) { - console.error(`Failed to mark challenge as authenticated for contact AID '${contactAidPrefix}':`, error); - throw error; - } -} - export function createTimestamp() { return new Date().toISOString().replace('Z', '000+00:00'); } @@ -455,27 +299,6 @@ export async function createCredentialRegistry( } } -/** - * Retrieves a schema by its SAID. - * @param {SignifyClient} client - The SignifyClient instance. - * @param {string} schemaSaid - The SAID of the schema to retrieve. - * @returns {Promise} The schema object. - */ -export async function getSchema( - client: SignifyClient, - schemaSaid: string -): Promise { - console.log(`Retrieving schema with SAID: ${schemaSaid}...`); - try { - const schema = await client.schemas().get(schemaSaid); - console.log(`Successfully retrieved schema: ${schemaSaid}`); - return schema; - } catch (error) { - console.error(`Failed to retrieve schema "${schemaSaid}":`, error); - throw error; - } -} - /** * Issues a new credential. * @param {SignifyClient} client - The SignifyClient instance. @@ -584,42 +407,6 @@ export async function ipexGrantCredential( } } -/** - * Retrieves the state of a credential. - * Includes retry logic as this might be called before the information has propagated. - * @param {SignifyClient} client - The SignifyClient instance. - * @param {string} registryIdentifier - The registry identifier (regk). - * @param {string} credentialSaid - The SAID of the credential. - * @param {number} [retries=DEFAULT_RETRIES] - Number of retry attempts. - * @param {number} [delayMs=DEFAULT_DELAY_MS] - Delay between retries in milliseconds. - * @returns {Promise} The credential state. - */ -export async function getCredentialState( - client: SignifyClient, - registryIdentifier: string, - credentialSaid: string, - retries: number = DEFAULT_RETRIES, - delayMs: number = DEFAULT_DELAY_MS -): Promise { - console.log(`Querying credential state for SAID "${credentialSaid}" in registry "${registryIdentifier}"...`); - for (let attempt = 1; attempt <= retries; attempt++) { - try { - const credentialState = await client.credentials().state(registryIdentifier, credentialSaid); - console.log('Successfully retrieved credential state.'); - return credentialState; - } catch (error: any) { - console.warn(`[Attempt ${attempt}/${retries}] Failed to get credential state: ${error.message}`); - if (attempt === retries) { - console.error(`Max retries (${retries}) reached for getting credential state.`); - throw error; - } - await new Promise(resolve => setTimeout(resolve, delayMs)); - } - } - // Should not be reached if retries > 0 - throw new Error('Failed to get credential state after all retries.'); -} - /** * Waits for and retrieves a specific notification. * @param {SignifyClient} client - The SignifyClient instance. @@ -728,318 +515,3 @@ export async function markNotificationRead( throw error; } } - -/** - * Deletes a notification. - * @param {SignifyClient} client - The SignifyClient instance. - * @param {string} notificationId - The ID of the notification to delete. - * @returns {Promise} - */ -export async function deleteNotification( - client: SignifyClient, - notificationId: string -): Promise { - console.log(`Deleting notification "${notificationId}"...`); - try { - await client.notifications().delete(notificationId); - console.log(`Notification "${notificationId}" deleted.`); - } catch (error) { - console.error(`Failed to delete notification "${notificationId}":`, error); - throw error; - } -} - - -//-------------------------------------------------------------------------------- - -// --- Credential Presentation Functions --- - -/** - * Submits an IPEX apply (presentation request). - * @param {SignifyClient} client - The SignifyClient instance of the verifier. - * @param {string} senderAidAlias - The alias of the AID applying for presentation. - * @param {string} recipientAidPrefix - The AID prefix of the holder. - * @param {string} schemaSaid - The SAID of the schema being requested. - * @param {any} attributes - The attributes being requested for the credential. - * @param {string} datetime - The timestamp for the apply. - * @returns {Promise<{ operation: Operation; applySaid: string }>} The operation details and SAID of the apply exn. - */ -export async function ipexApplyForCredential( - client: SignifyClient, - senderAidAlias: string, - recipientAidPrefix: string, - schemaSaid: string, - attributes: any, - datetime: string -): Promise<{ operation: Operation; applySaid: string }> { - console.log(`AID "${senderAidAlias}" applying for credential presentation from AID "${recipientAidPrefix}"...`); - try { - const [apply, sigs, _] = await client.ipex().apply({ - senderName: senderAidAlias, - schemaSaid: schemaSaid, - attributes: attributes, - recipient: recipientAidPrefix, - datetime: datetime, - }); - - const applySaid = new Serder(apply).said; // Get SAID of the apply message itself - - const applyOperationDetails = await client - .ipex() - .submitApply(senderAidAlias, apply, sigs, [recipientAidPrefix]); - - const completedOperation = await client - .operations() - .wait(applyOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); - - if (completedOperation.error) { - throw new Error(`IPEX apply submission failed: ${JSON.stringify(completedOperation.error)}`); - } - console.log(`Successfully submitted IPEX apply with SAID "${applySaid}".`); - await client.operations().delete(completedOperation.name); - return { operation: completedOperation, applySaid }; - } catch (error) { - console.error('Failed to submit IPEX apply:', error); - throw error; - } -} - -/** - * Finds matching credentials based on a filter. - * @param {SignifyClient} client - The SignifyClient instance of the holder. - * @param {any} filter - The filter object to apply (e.g., { '-s': schemaSaid, '-a-attributeName': value }). - * @returns {Promise} An array of matching credentials. - */ -export async function findMatchingCredentials( - client: SignifyClient, - filter: any -): Promise { - console.log('Finding matching credentials with filter:', filter); - try { - const matchingCredentials = await client.credentials().list({ filter }); - console.log(`Found ${matchingCredentials.length} matching credentials.`); - return matchingCredentials; - } catch (error) { - console.error('Failed to find matching credentials:', error); - throw error; - } -} - -/** - * Submits an IPEX offer (presents a credential). - * @param {SignifyClient} client - The SignifyClient instance of the holder. - * @param {string} senderAidAlias - The alias of the AID offering the credential. - * @param {string} recipientAidPrefix - The AID prefix of the verifier. - * @param {any} acdcSad - The Self-Addressing Data (SAD) of the ACDC being offered. - * @param {string} applySaid - The SAID of the IPEX apply message this offer is responding to. - * @param {string} datetime - The timestamp for the offer. - * @returns {Promise<{ operation: Operation }>} The operation details. - */ -export async function ipexOfferCredential( - client: SignifyClient, - senderAidAlias: string, - recipientAidPrefix: string, - acdcSad: any, // This is the SAD of the credential to be offered - applySaid: string, - datetime: string -): Promise<{ operation: Operation }> { - console.log(`AID "${senderAidAlias}" offering credential to AID "${recipientAidPrefix}" in response to apply "${applySaid}"...`); - try { - const [offer, sigs, end] = await client.ipex().offer({ - senderName: senderAidAlias, - recipient: recipientAidPrefix, - acdc: new Serder(acdcSad), // The credential SAD needs to be wrapped in Serder - applySaid: applySaid, - datetime: datetime, - }); - - const offerOperationDetails = await client - .ipex() - .submitOffer(senderAidAlias, offer, sigs, end, [recipientAidPrefix]); - - const completedOperation = await client - .operations() - .wait(offerOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); - - if (completedOperation.error) { - throw new Error(`IPEX offer submission failed: ${JSON.stringify(completedOperation.error)}`); - } - console.log(`Successfully submitted IPEX offer in response to apply "${applySaid}".`); - await client.operations().delete(completedOperation.name); - return { operation: completedOperation }; - } catch (error) { - console.error('Failed to submit IPEX offer:', error); - throw error; - } -} - -/** - * Submits an IPEX agree (verifier agrees to the offered credential). - * @param {SignifyClient} client - The SignifyClient instance of the verifier. - * @param {string} senderAidAlias - The alias of the AID agreeing to the offer. - * @param {string} recipientAidPrefix - The AID prefix of the holder who made the offer. - * @param {string} offerSaid - The SAID of the IPEX offer message being agreed to. - * @param {string} datetime - The timestamp for the agree. - * @returns {Promise<{ operation: Operation }>} The operation details. - */ -export async function ipexAgreeToOffer( - client: SignifyClient, - senderAidAlias: string, - recipientAidPrefix: string, - offerSaid: string, - datetime: string -): Promise<{ operation: Operation }> { - console.log(`AID "${senderAidAlias}" agreeing to IPEX offer "${offerSaid}" from AID "${recipientAidPrefix}"...`); - try { - const [agree, sigs, _] = await client.ipex().agree({ - senderName: senderAidAlias, - recipient: recipientAidPrefix, - offerSaid: offerSaid, - datetime: datetime, - }); - - const agreeOperationDetails = await client - .ipex() - .submitAgree(senderAidAlias, agree, sigs, [recipientAidPrefix]); - - const completedOperation = await client - .operations() - .wait(agreeOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); - - if (completedOperation.error) { - throw new Error(`IPEX agree submission failed: ${JSON.stringify(completedOperation.error)}`); - } - console.log(`Successfully submitted IPEX agree for offer "${offerSaid}".`); - await client.operations().delete(completedOperation.name); - return { operation: completedOperation }; - } catch (error) { - console.error('Failed to submit IPEX agree:', error); - throw error; - } -} - - - - - - - - - - - - - - - - - - - - - - -// --- Example Usage --- -export async function test() { - try { - await initializeSignify(); - - // --- Client A (Alfred) Setup --- - console.log('\n--- Initializing Client A (Alfred) ---'); - const { client: clientA, clientState: clientAState } = await initializeAndConnectClient(randomPasscode()); - const alfredClientAID = clientAState?.controller?.state?.i || 'Unknown Client AID A'; - const aidAAlias = 'alfredPrimaryAID'; - console.log('\n--- Creating AID for Alfred ---'); - const { aid: aidAObj} = await createNewAID(clientA, aidAAlias, DEFAULT_IDENTIFIER_ARGS); - const aidAPrefix = aidAObj?.i || 'Unknown AID A Prefix'; - console.log(`Alfred's primary AID: ${aidAPrefix}`); - console.log('\n--- Adding Agent End Role for Alfred ---'); - await addEndRoleForAID(clientA, aidAAlias, 'agent'); - console.log('\n--- Generating OOBI for Alfred ---'); - const alfredOOBI = await generateOOBI(clientA, aidAAlias, 'agent'); - - // --- Client B (Betty) Setup --- - console.log('\n\n--- Initializing Client B (Betty) ---'); - const { client: clientB, clientState: clientBState } = await initializeAndConnectClient(randomPasscode()); - const bettyClientAID = clientBState?.controller?.state?.i || 'Unknown Client AID B'; - const aidBAlias = 'bettyPrimaryAID'; - console.log('\n--- Creating AID for Betty ---'); - const { aid: aidBObj } = await createNewAID(clientB, aidBAlias, DEFAULT_IDENTIFIER_ARGS); - const aidBPrefix = aidBObj?.i || 'Unknown AID B Prefix'; - console.log(`Betty's primary AID: ${aidBPrefix}`); - console.log('\n--- Adding Agent End Role for Betty ---'); - await addEndRoleForAID(clientB, aidBAlias, 'agent'); - console.log('\n--- Generating OOBI for Betty ---'); - const bettyOOBI = await generateOOBI(clientB, aidBAlias, 'agent'); - - // --- OOBI Resolution --- - console.log('\n\n--- Betty resolving Alfred\'s OOBI ---'); - const contactAlfredAlias = 'AlfredsContactForBetty'; - await resolveOOBI(clientB, alfredOOBI, contactAlfredAlias); - - console.log('\n--- Alfred resolving Betty\'s OOBI ---'); - const contactBettyAlias = 'BettysContactForAlfred'; - await resolveOOBI(clientA, bettyOOBI, contactBettyAlias); - - // --- Challenge/Response: Alfred challenges Betty --- - console.log("\n\n--- MUTUAL AUTHENTICATION ---"); - console.log("\n--- Alfred challenges Betty ---"); - - // 1. Alfred generates challenge words for Betty - const alfredChallengeForBetty = await generateChallengeWords(clientA); - - // (Assume words are securely transmitted out-of-band to Betty) - - // 2. Betty responds to Alfred's challenge - console.log(`\nBetty (AID: ${aidBPrefix}) responding to Alfred's (AID: ${aidAPrefix}) challenge...`); - await respondToChallenge(clientB, aidBAlias, aidAPrefix, alfredChallengeForBetty); - - // 3. Alfred verifies Betty's response - console.log(`\nAlfred (AID: ${aidAPrefix}) verifying Betty's (AID: ${aidBPrefix}) response...`); - const verificationBetty = await verifyChallengeResponse(clientA, aidBPrefix, alfredChallengeForBetty); - - // 4. Alfred marks Betty as authenticated if verification succeeded - if (verificationBetty.verified && verificationBetty.said) { - await markChallengeAuthenticated(clientA, aidBPrefix, verificationBetty.said); - console.log(`Alfred has successfully authenticated Betty (AID: ${aidBPrefix}).`); - } else { - console.error(`Alfred failed to authenticate Betty (AID: ${aidBPrefix}).`); - } - - // --- Challenge/Response: Betty challenges Alfred --- - console.log("\n--- Betty challenges Alfred ---"); - - // 1. Betty generates challenge words for Alfred - const bettyChallengeForAlfred = await generateChallengeWords(clientB); - - // (Assume words are securely transmitted out-of-band to Alfred) - - // 2. Alfred responds to Betty's challenge - console.log(`\nAlfred (AID: ${aidAPrefix}) responding to Betty's (AID: ${aidBPrefix}) challenge...`); - await respondToChallenge(clientA, aidAAlias, aidBPrefix, bettyChallengeForAlfred); - - // 3. Betty verifies Alfred's response - console.log(`\nBetty (AID: ${aidBPrefix}) verifying Alfred's (AID: ${aidAPrefix}) response...`); - const verificationAlfred = await verifyChallengeResponse(clientB, aidAPrefix, bettyChallengeForAlfred); - - // 4. Betty marks Alfred as authenticated if verification succeeded - if (verificationAlfred.verified && verificationAlfred.said) { - await markChallengeAuthenticated(clientB, aidAPrefix, verificationAlfred.said); - console.log(`Betty has successfully authenticated Alfred (AID: ${aidAPrefix}).`); - } else { - console.error(`Betty failed to authenticate Alfred (AID: ${aidAPrefix}).`); - } - - console.log('\n\n--- Example scenario with mutual authentication completed! ---'); - console.log(`Alfred's Client AID: ${alfredClientAID}, Primary AID: ${aidAPrefix}`); - console.log(`Betty's Client AID: ${bettyClientAID}, Primary AID: ${aidBPrefix}`); - - // You can inspect contacts to see authentication status - const alfredsContacts = await clientA.contacts().list(); - console.log("\nAlfred's contacts:", JSON.stringify(alfredsContacts, null, 2)); - const bettysContacts = await clientB.contacts().list(); - console.log("\nBetty's contacts:", JSON.stringify(bettysContacts, null, 2)); - } catch (error) { - console.error('\n--- An error occurred in the main example: ---', error); - } -} diff --git a/scripts/demo/vlei/verify-control-demo.sh b/scripts/demo/vlei/verify-control-demo.sh index 82e9a15..7418bf6 100755 --- a/scripts/demo/vlei/verify-control-demo.sh +++ b/scripts/demo/vlei/verify-control-demo.sh @@ -66,7 +66,7 @@ # PRESENTATION_FILE exported {cesr,lei,aid} JSON # (default: $DATA/ecr-presentation.json) # OUTPUTS_FILE exported {roleBran,...} JSON, used by AUTO_SIGN -# (default: alongside PRESENTATION_FILE / tier1-outputs.json) +# (default: alongside PRESENTATION_FILE / holder-state.json) # LEI claimed LEI (default: read from PRESENTATION_FILE) # SIGNED_PROOF the signature over the signingInput (indexed Siger qb64). # When set, the script uses it directly — highest @@ -86,7 +86,7 @@ export DATA="${DATA:-$(cd "$SCRIPT_DIR/../../.." && pwd)/data/demo/vlei}" . "$SCRIPT_DIR/../common.sh" PRESENTATION_FILE="${PRESENTATION_FILE:-$DATA/ecr-presentation.json}" -OUTPUTS_FILE="${OUTPUTS_FILE:-$(dirname "$PRESENTATION_FILE")/tier1-outputs.json}" +OUTPUTS_FILE="${OUTPUTS_FILE:-$(dirname "$PRESENTATION_FILE")/holder-state.json}" COMPOSE="${COMPOSE:-docker compose}" require_cmd curl @@ -231,7 +231,7 @@ fi # The sealed IDENTITY_VERIFIED reaches the TL through the outbox worker. header "verify the seal landed on the TL identity stream" -poll_tl_identity_audit "$IDENTITY_ID" 1 +assert_tl_identity_audit "$IDENTITY_ID" 1 ok "IDENTITY_VERIFIED sealed with a Merkle proof on the TL" # ----- 5. link: bind the verified identity to the agent (one event) ----- From ffd265e3d5e6cda05c7bcbce136b49b269143aa4 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Sat, 13 Jun 2026 17:45:27 +1000 Subject: [PATCH 04/21] fix(vlei): noop lei verifier accepts the real CESR presentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../adapter/leiverifier/leiverifier_test.go | 128 ++++++++------- internal/adapter/leiverifier/noop.go | 148 +++++++----------- internal/adapter/leiverifier/verifier.go | 83 ++++++---- internal/config/config.go | 9 +- internal/port/leiverifier.go | 7 +- scripts/demo/start.sh | 8 +- scripts/demo/vlei/run-vlei.sh | 17 +- 7 files changed, 201 insertions(+), 199 deletions(-) diff --git a/internal/adapter/leiverifier/leiverifier_test.go b/internal/adapter/leiverifier/leiverifier_test.go index 91d139d..702cc67 100644 --- a/internal/adapter/leiverifier/leiverifier_test.go +++ b/internal/adapter/leiverifier/leiverifier_test.go @@ -2,10 +2,6 @@ package leiverifier import ( "context" - "crypto/ed25519" - "crypto/rand" - "encoding/base64" - "encoding/json" "errors" "net/http" "net/http/httptest" @@ -15,77 +11,70 @@ import ( "github.com/godaddy/ans/internal/domain" ) -// b64 is the unpadded base64url encoding the noop wire shape uses. -func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) } +// leafACDC is a minimal single-credential CESR export whose leaf carries +// the subject AID (a.i) and LEI (a.LEI) the noop pins and echoes — the +// same shape the real verifier receives. +const leafACDC = `{"v":"ACDC10JSON00011c_","d":"ECredSAID123","i":"EIssuerAID","s":"ESchema","a":{"i":"EHolderAID","LEI":"5493001KJTIIGC8Y1R17"}}` -// noopFixture mints an Ed25519 keypair and the matching noop -// presentation cesr + subject AID for the public key. -func noopFixture(t *testing.T, lei string) (ed25519.PrivateKey, string, string) { - t.Helper() - pub, priv, err := ed25519.GenerateKey(rand.Reader) +func TestNoopPresent(t *testing.T) { + ctx := context.Background() + n := NewNoop() + + // Present pins the leaf credential's subject AID, echoes its LEI, and + // always reports AUTHORIZED (the live binding is waived). + res, err := n.Present(ctx, leafACDC) if err != nil { - t.Fatal(err) + t.Fatalf("Present: %v", err) } - aid := b64(pub) - raw, err := json.Marshal(noopPresentation{PublicKey: aid, LEI: lei}) - if err != nil { - t.Fatal(err) + if res.SubjectAID != "EHolderAID" || res.LEI != "5493001KJTIIGC8Y1R17" || res.Status != "AUTHORIZED" { + t.Fatalf("present result: %+v", res) } - return priv, aid, b64(raw) } -func TestNoopPresentAndVerify(t *testing.T) { +func TestNoopPresentChainPinsLeafSubject(t *testing.T) { + // Full-chain export: the noop pins the LEAF credential's subject AID + // (the ECR), not an intermediate's — the same leaf selection the real + // verifier uses, independent of frame order. ctx := context.Background() n := NewNoop() - priv, aid, cesr := noopFixture(t, "5493001KJTIIGC8Y1R17") - - // Present recovers the AID + echoes the LEI + always AUTHORIZED. - res, err := n.Present(ctx, cesr) + chain := `{"v":"ACDC10JSON_","d":"EQVI","a":{"i":"EQviSub","LEI":"L"}}` + + `{"v":"ACDC10JSON_","d":"ELE","e":{"d":"Eedge1","qvi":{"n":"EQVI","s":"S"}},"a":{"i":"ELeSub","LEI":"L"}}` + + `{"v":"ACDC10JSON_","d":"EECR","e":{"d":"Eedge2","le":{"n":"ELE","s":"S"}},"a":{"i":"EEcrSub","LEI":"875500ELOZEL05BVXV37"}}` + res, err := n.Present(ctx, chain) if err != nil { t.Fatalf("Present: %v", err) } - if res.SubjectAID != aid || res.LEI != "5493001KJTIIGC8Y1R17" || res.Status != "AUTHORIZED" { + if res.SubjectAID != "EEcrSub" || res.LEI != "875500ELOZEL05BVXV37" { t.Fatalf("present result: %+v", res) } +} - // Authorization authorizes a well-formed AID, asserts no LEI binding. - auth, err := n.Authorization(ctx, aid) +func TestNoopPresentIgnoresKEL(t *testing.T) { + // A real export interleaves KERI KEL events (icp/ixn) with ACDC frames; + // the scan keys on the ACDC version marker, so KEL frames are ignored + // and the leaf credential's subject AID is still pinned. + ctx := context.Background() + n := NewNoop() + withKEL := `{"v":"KERI10JSON0001b7_","t":"icp","d":"EIncept","i":"EIncept","k":["DKey"]}` + leafACDC + res, err := n.Present(ctx, withKEL) if err != nil { - t.Fatalf("Authorization: %v", err) - } - if !auth.Authorized || auth.LEI != "" { - t.Fatalf("authorization: %+v", auth) - } - - // VerifySignature: a real Ed25519 signature over the signing input. - const signingInput = "the-served-signing-input" - sig := ed25519.Sign(priv, []byte(signingInput)) - ok, err := n.VerifySignature(ctx, aid, signingInput, b64(sig)) - if err != nil || !ok { - t.Fatalf("verify good sig: ok=%v err=%v", ok, err) + t.Fatalf("Present: %v", err) } - // Tampered payload does not verify. - if ok, _ := n.VerifySignature(ctx, aid, "other-input", b64(sig)); ok { - t.Fatal("tampered payload should not verify") + if res.SubjectAID != "EHolderAID" { + t.Fatalf("want subject AID EHolderAID, got %q", res.SubjectAID) } } func TestNoopPresentFailures(t *testing.T) { ctx := context.Background() n := NewNoop() - _, validAID, _ := noopFixture(t, "X") - - noLEI, _ := json.Marshal(noopPresentation{PublicKey: validAID}) - badPub, _ := json.Marshal(noopPresentation{PublicKey: "not-base64url-key", LEI: "X"}) - cases := []struct { name string cesr string }{ - {"not base64url", "!!!not-base64!!!"}, - {"not a json object", b64([]byte("not json"))}, - {"bad public key", b64(badPub)}, - {"missing lei", b64(noLEI)}, + {"no ACDC frame", "no acdc credential here"}, + {"leaf without subject AID", `{"v":"ACDC10JSON_","d":"ECred","a":{"LEI":"L"}}`}, + {"leaf with non-qb64 subject AID", `{"v":"ACDC10JSON_","d":"ECred","a":{"i":"../evil","LEI":"L"}}`}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -94,22 +83,41 @@ func TestNoopPresentFailures(t *testing.T) { } }) } +} - // A malformed AID to Authorization is an error (not a silent allow). - if _, err := n.Authorization(ctx, "bogus-aid"); err == nil { - t.Fatal("malformed AID should error") +func TestNoopAuthorization(t *testing.T) { + ctx := context.Background() + n := NewNoop() + // A well-formed AID is authorized with NO live LEI binding asserted. + auth, err := n.Authorization(ctx, "EHolderAID") + if err != nil || !auth.Authorized || auth.LEI != "" { + t.Fatalf("auth=%+v err=%v", auth, err) + } + // A non-qb64 AID is a validation error (mirrors the real verifier guard). + if _, err := n.Authorization(ctx, "../signature/verify"); !isCode(err, "LEI_SUBJECT_AID_INVALID") { + t.Fatalf("want LEI_SUBJECT_AID_INVALID, got %v", err) } +} - // VerifySignature treats malformed AID / signature as a non-verifying - // false, never an I/O error. - if ok, err := n.VerifySignature(ctx, "bogus-aid", "in", b64([]byte("sig"))); ok || err != nil { - t.Fatalf("bad aid: ok=%v err=%v", ok, err) +func TestNoopVerifySignature(t *testing.T) { + ctx := context.Background() + n := NewNoop() + // Structural accept: well-formed qb64 AID + signature → true. + if ok, err := n.VerifySignature(ctx, "EHolderAID", "signing-input", "0BsomeQb64Signature"); err != nil || !ok { + t.Fatalf("structural accept: ok=%v err=%v", ok, err) } - if ok, err := n.VerifySignature(ctx, validAID, "in", "!!!"); ok || err != nil { - t.Fatalf("bad sig encoding: ok=%v err=%v", ok, err) + // A malformed AID or signature is a non-verifying false, never an error. + cases := []struct{ name, aid, sig string }{ + {"bad aid", "../evil", "0Bsig"}, + {"bad sig", "EHolderAID", "!!!not-qb64!!!"}, + {"empty sig", "EHolderAID", ""}, } - if ok, err := n.VerifySignature(ctx, validAID, "in", b64([]byte("too-short"))); ok || err != nil { - t.Fatalf("wrong-length sig: ok=%v err=%v", ok, err) + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if ok, err := n.VerifySignature(ctx, tc.aid, "in", tc.sig); ok || err != nil { + t.Fatalf("ok=%v err=%v", ok, err) + } + }) } } diff --git a/internal/adapter/leiverifier/noop.go b/internal/adapter/leiverifier/noop.go index 18150c5..4040112 100644 --- a/internal/adapter/leiverifier/noop.go +++ b/internal/adapter/leiverifier/noop.go @@ -1,9 +1,10 @@ // Package leiverifier provides the two port.LEIControlVerifier // adapters behind the lei (vLEI) identifier kind: // -// - Noop — zero-infra quickstart verifier; runs REAL Ed25519 -// crypto over the signing input but waives the GLEIF/vlei-verifier -// authorization binding. +// - Noop — zero-infra quickstart verifier; accepts the SAME +// full-chain CESR presentation the real verifier does, pins the real +// subject AID, and waives the external-world bindings (GLEIF +// authorization + cryptographic signature check). // - Verifier — the real thing: a hardened HTTP client for an // internal vlei-verifier service (present / authorize / verify). // @@ -15,9 +16,6 @@ package leiverifier import ( "context" - "crypto/ed25519" - "encoding/base64" - "encoding/json" "github.com/godaddy/ans/internal/domain" "github.com/godaddy/ans/internal/port" @@ -25,113 +23,75 @@ import ( // Noop is the quickstart vLEI verifier. It never dials anywhere. // -// What this preserves and what it waives, stated precisely (the noop -// DNS / noop did:web precedent — real crypto, waived external-world -// binding): +// It consumes the SAME client payload as the real verifier — the +// full-chain CESR export (`vleiPresentation.cesr`) and a qb64 CESR +// signature (`cesrSignature`) — so a registration that works in +// verifier mode works unchanged in noop mode. This is the DNS / did:web +// noop precedent: the client sends identical bytes in either mode, and +// the noop derives its answer from material already in the request. // -// - PRESERVED: VerifySignature runs a genuine Ed25519 verification -// of the registrant's signature over the served signingInput, so -// the sealed proof is not a rubber stamp. The subject AID encodes -// the registrant's public key, so the verify key is recoverable -// from the AID alone — no KEL, no state. -// - WAIVED: "is this CESR really an authorized vLEI credential, and -// is the AID↔LEI binding real?" Anyone can mint a keypair and -// present any LEI. Authorization therefore returns Authorized -// with an empty LEI (no binding asserted), and the service skips -// the LEI-equality check accordingly. +// What this preserves and what it waives, stated precisely: // -// In noop mode the presentation `cesr` is a base64url (unpadded) -// encoding of a small JSON object {"publicKey": "", "lei": ""}, and a signature is the -// base64url (unpadded) Ed25519 signature over the exact signingInput -// bytes. Strictly for local development and tests. NOT for production. +// - PRESERVED: the presentation is a real full-chain CESR export and +// the pinned subject AID is the real holder AID read from the +// presented leaf credential (`a.i`) — so the sealed identity carries +// the genuine KERI AID, and the register-time LEI echoed from the +// credential (`a.LEI`) lets the service check it against the claimed +// value (a structural string compare, no external oracle). +// - WAIVED: "is this an authorized vLEI credential, is the AID↔LEI +// binding real, and does the signature verify against the AID's +// current key?" The quickstart has no KEL key-state oracle, so — +// like the noop DNS verifier, which accepts any well-formed record +// without proving the live zone — it accepts a well-formed qb64 +// signature without a cryptographic check, authorizes any +// well-formed AID, and asserts no live LEI binding (empty LEI). +// +// Strictly for local development and tests. NOT for production. type Noop struct{} // NewNoop returns the quickstart verifier. func NewNoop() *Noop { return &Noop{} } -// noopPresentation is the noop's stand-in for a full-chain CESR export. -type noopPresentation struct { - PublicKey string `json:"publicKey"` - LEI string `json:"lei"` -} - -// Present decodes the noop presentation, recovers the registrant's -// Ed25519 public key, and reports a subject AID that IS the base64url -// encoding of that key (so VerifySignature can recover it). The LEI is -// echoed verbatim and the status is always AUTHORIZED. +// Present reads the presented (leaf) credential from the full-chain +// CESR export, pins its subject AID (`a.i`) as the holder AID, echoes +// the credential's claimed LEI (`a.LEI`), and always reports AUTHORIZED. +// It reads credential attributes only — never KERI key state. func (n *Noop) Present(_ context.Context, cesr string) (port.PresentationResult, error) { - pres, pub, err := decodeNoopPresentation(cesr) - if err != nil { - return port.PresentationResult{}, err + leaf, ok := leafFrame(cesr) + if !ok { + return port.PresentationResult{}, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "vlei presentation carries no ACDC credential") + } + if !isQB64(leaf.A.I) { + return port.PresentationResult{}, domain.NewValidationError("LEI_PRESENTATION_INVALID", + "the presented credential carries no valid subject AID") } return port.PresentationResult{ - SubjectAID: base64.RawURLEncoding.EncodeToString(pub), - LEI: pres.LEI, + SubjectAID: leaf.A.I, + LEI: leaf.A.LEI, Status: "AUTHORIZED", }, nil } -// Authorization always authorizes a well-formed AID and asserts NO -// LEI binding (the waived check) — the service treats the empty LEI -// as "verifier does not constrain the LEI". +// Authorization authorizes any well-formed (qb64) AID and asserts NO +// live LEI binding (the waived check) — the service treats the empty LEI +// as "verifier does not constrain the LEI". A non-qb64 AID is a +// validation error, mirroring the real verifier's guard. func (n *Noop) Authorization(_ context.Context, subjectAID string) (port.AuthorizationResult, error) { - if _, err := decodeSubjectAID(subjectAID); err != nil { - return port.AuthorizationResult{}, err + if !isQB64(subjectAID) { + return port.AuthorizationResult{}, domain.NewValidationError("LEI_SUBJECT_AID_INVALID", + "subject AID is not a valid qb64 identifier") } return port.AuthorizationResult{Authorized: true, LEI: ""}, nil } -// VerifySignature recovers the public key from the subject AID and -// runs a real Ed25519 verification of the signature over the -// signingInput bytes. A malformed AID or signature is a false (not an -// error) — a non-verifying proof, not an I/O failure. -func (n *Noop) VerifySignature(_ context.Context, subjectAID, signingInput, signature string) (bool, error) { - pub, err := decodeSubjectAID(subjectAID) - if err != nil { - return false, nil //nolint:nilerr // malformed AID is a non-verifying proof (false), not an I/O failure - } - sig, err := base64.RawURLEncoding.DecodeString(signature) - if err != nil || len(sig) != ed25519.SignatureSize { - return false, nil //nolint:nilerr // malformed signature is a non-verifying proof (false), not an I/O failure - } - return ed25519.Verify(pub, []byte(signingInput), sig), nil -} - -// decodeNoopPresentation parses the base64url-wrapped JSON presentation -// and validates the embedded Ed25519 public key. -func decodeNoopPresentation(cesr string) (noopPresentation, ed25519.PublicKey, error) { - raw, err := base64.RawURLEncoding.DecodeString(cesr) - if err != nil { - return noopPresentation{}, nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", - "vlei presentation is not valid base64url") - } - var pres noopPresentation - if err := json.Unmarshal(raw, &pres); err != nil { - return noopPresentation{}, nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", - "vlei presentation is not a valid noop presentation object") - } - pub, err := decodeSubjectAID(pres.PublicKey) - if err != nil { - return noopPresentation{}, nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", - "vlei presentation publicKey is not a base64url Ed25519 public key") - } - if pres.LEI == "" { - return noopPresentation{}, nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", - "vlei presentation carries no lei") - } - return pres, pub, nil -} - -// decodeSubjectAID recovers the Ed25519 public key a noop subject AID -// encodes. -func decodeSubjectAID(aid string) (ed25519.PublicKey, error) { - b, err := base64.RawURLEncoding.DecodeString(aid) - if err != nil || len(b) != ed25519.PublicKeySize { - return nil, domain.NewValidationError("LEI_PRESENTATION_INVALID", - "subject AID is not a base64url Ed25519 public key") - } - return ed25519.PublicKey(b), nil +// VerifySignature is a structural check only: the quickstart has no KEL +// key-state oracle to resolve the AID's current key, so it accepts a +// well-formed qb64 signature over the well-formed AID and rejects a +// malformed one. A malformed AID or signature is a non-verifying false +// (not an I/O error) — the waived binding, the noop DNS precedent. +func (n *Noop) VerifySignature(_ context.Context, subjectAID, _, signature string) (bool, error) { + return isQB64(subjectAID) && isQB64(signature), nil } // compile-time conformance. diff --git a/internal/adapter/leiverifier/verifier.go b/internal/adapter/leiverifier/verifier.go index afc39c7..7376f1b 100644 --- a/internal/adapter/leiverifier/verifier.go +++ b/internal/adapter/leiverifier/verifier.go @@ -331,31 +331,32 @@ func isQB64(s string) bool { // guarantee. var acdcFrameMarker = regexp.MustCompile(`\{\s*"v"\s*:\s*"ACDC`) -// presentedCredentialSAID extracts the SAID of the *presented* (leaf) -// credential from a full-chain CESR export — the minimal, targeted read -// the real verifier path needs to route PUT /presentations/{said}. It is -// NOT a CESR codec: KERI/ACDC serializations are version-string-first, so -// an ACDC credential message is always a JSON object whose first member -// is `"v":"ACDC…"`; we locate those frames with acdcFrameMarker and read +// acdcFrame is the subset of an ACDC credential frame the presentation +// scan needs: the self-addressing SAID `d`, the attributes block `a` +// (the subject AID `i` and `LEI` the noop pins/echoes), and the edge +// block `e` (the SAIDs this credential chains to). It is shared by the +// real verifier (which needs the leaf `d` to route PUT /presentations) +// and the noop (which pins the leaf `a.i` and echoes `a.LEI`). +type acdcFrame struct { + D string `json:"d"` + A struct { + I string `json:"i"` + LEI string `json:"LEI"` + } `json:"a"` + E json.RawMessage `json:"e"` +} + +// scanACDCChain walks every ACDC credential frame in a full-chain CESR +// export and returns the parsed frames (in serialization order) plus the +// set of edge-referenced SAIDs (the `n` of each edge). It is NOT a CESR +// codec: KERI/ACDC serializations are version-string-first, so an ACDC +// credential message is always a JSON object whose first member is +// `"v":"ACDC…"`; we locate those frames with acdcFrameMarker and read // each one by brace-balancing (respecting JSON string escaping), take its // self-addressing `d`, and collect the edge node SAIDs (the `n` of each // edge) from each frame's `e` block. -// -// The presented credential is the most-derived one — the ECR/role -// credential at the bottom of the ECR→LE→QVI chain — identified -// structurally as the lone credential whose SAID is NOT referenced by any -// other credential's edge. This is position-independent: KERIA's -// `credentials().get(said, true)` exporter emits the chain in topological -// (issuer-first) order, so the leaf is serialized LAST, but we never rely -// on frame order. A single-credential export (no chain) has no references, -// so its one frame is the leaf. The end-to-end demo (scripts/demo/vlei) -// exercises this against the live verifier. -func presentedCredentialSAID(cesr string) string { - type acdcFrame struct { - D string `json:"d"` - E json.RawMessage `json:"e"` - } - var saids []string +func scanACDCChain(cesr string) ([]acdcFrame, map[string]struct{}) { + var frames []acdcFrame referenced := make(map[string]struct{}) offset := 0 for { @@ -374,19 +375,43 @@ func presentedCredentialSAID(cesr string) string { if err := json.Unmarshal([]byte(obj), &frame); err != nil || frame.D == "" { continue } - saids = append(saids, frame.D) + frames = append(frames, frame) if len(frame.E) > 0 { collectEdgeNodes(frame.E, referenced) } } - // The leaf is the credential no other credential chains to. A - // well-formed linear chain has exactly one such SAID. - for _, d := range saids { - if _, ok := referenced[d]; !ok { - return d + return frames, referenced +} + +// leafFrame returns the *presented* (leaf) credential frame — the +// most-derived one (the ECR/role credential at the bottom of the +// ECR→LE→QVI chain), identified structurally as the lone credential whose +// SAID is NOT referenced by any other credential's edge. This is +// position-independent: KERIA's `credentials().get(said, true)` exporter +// emits the chain in topological (issuer-first) order, so the leaf is +// serialized LAST, but we never rely on frame order. A single-credential +// export (no chain) has no references, so its one frame is the leaf. ok +// is false when the export carries no ACDC credential. The end-to-end +// demo (scripts/demo/vlei) exercises this against the live verifier. +func leafFrame(cesr string) (acdcFrame, bool) { + frames, referenced := scanACDCChain(cesr) + for _, f := range frames { + if _, ok := referenced[f.D]; !ok { + return f, true } } - return "" + return acdcFrame{}, false +} + +// presentedCredentialSAID extracts the SAID of the presented (leaf) +// credential — the minimal, targeted read the real verifier path needs to +// route PUT /presentations/{said}. Empty when the export carries no ACDC. +func presentedCredentialSAID(cesr string) string { + leaf, ok := leafFrame(cesr) + if !ok { + return "" + } + return leaf.D } // collectEdgeNodes walks an ACDC `e` (edge) block and records every edge diff --git a/internal/config/config.go b/internal/config/config.go index 109fa22..8381330 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -178,10 +178,11 @@ type IdentityResolver struct { // because it is a distinct outbound dependency with its own service // endpoint. // -// "noop" runs real Ed25519 crypto over the signing input but waives -// the GLEIF authorization binding (quickstart — NOT for production); -// "verifier" is a hardened HTTP client for an internal vlei-verifier -// service. +// "noop" accepts the same full-chain CESR presentation as "verifier" +// but waives the external bindings — the GLEIF authorization, the +// AID↔LEI binding, and the signature's cryptographic check (structural +// only, quickstart — NOT for production); "verifier" is a hardened HTTP +// client for an internal vlei-verifier service. type VLEI struct { Type string `koanf:"type"` // "noop" | "verifier" // BaseURL is the internal vlei-verifier service URL, required when diff --git a/internal/port/leiverifier.go b/internal/port/leiverifier.go index 73fe7b9..21729a8 100644 --- a/internal/port/leiverifier.go +++ b/internal/port/leiverifier.go @@ -42,10 +42,13 @@ type AuthorizationResult struct { // following the DNS/DID precedent — a noop adapter for the quickstart // and a real adapter selected by config (`vlei.type: noop | verifier`). // -// The RA never parses CESR/KERI: the verifier is the authoritative +// The real verifier owns all KERI key state: it is the authoritative // key-state oracle. Present reports the subject AID, Authorization // re-checks live authorization, and VerifySignature owns the KEL/key -// state used to check the registrant's signature. +// state used to check the registrant's signature. The noop quickstart +// adapter reads only the leaf credential's subject AID (a credential +// attribute, not key state) and waives the authorization + signature +// checks — the DNS/did:web noop precedent. type LEIControlVerifier interface { // Present submits the full-chain CESR export to the verifier and // returns the parsed subject AID + authorized LEI + presentation diff --git a/scripts/demo/start.sh b/scripts/demo/start.sh index 6971eda..f1f1c74 100755 --- a/scripts/demo/start.sh +++ b/scripts/demo/start.sh @@ -208,9 +208,11 @@ identity: vlei: # The lei (vLEI) control verifier behind the "lei" identifier kind. - # "noop" runs real Ed25519 crypto but waives the GLEIF authorization - # binding; "verifier" routes CESR/KERI questions to a real - # vlei-verifier (scripts/demo/vlei brings one up on :7676). + # "noop" accepts the same full-chain CESR presentation but waives the + # external bindings — GLEIF authorization, the AID↔LEI binding, and the + # signature check (structural only); "verifier" routes CESR/KERI + # questions to a real vlei-verifier (scripts/demo/vlei brings one up on + # :7676). # ANS_VLEI_TYPE=verifier ANS_VLEI_BASE_URL=http://localhost:7676 \ # scripts/demo/start.sh type: ${ANS_VLEI_TYPE:-noop} diff --git a/scripts/demo/vlei/run-vlei.sh b/scripts/demo/vlei/run-vlei.sh index 333716d..0073f57 100755 --- a/scripts/demo/vlei/run-vlei.sh +++ b/scripts/demo/vlei/run-vlei.sh @@ -5,10 +5,11 @@ # Bootstraps everything the flow needs and chains it end-to-end with no manual steps: # 0. ensure ans-ra — start ans-ra (+ ans-tl) in the real vlei # "verifier" mode if it isn't already running that -# way. The demo presents real CESR, which only the -# verifier backend accepts; the plain start.sh -# default is "noop" (base64url JSON), so a noop RA is -# restarted into verifier mode here. +# way. Both backends accept the same real CESR, but +# noop waives the GLEIF authorization + signature +# checks; a real end-to-end demo needs the verifier +# backend, so a noop RA is restarted into verifier +# mode here. The plain start.sh default is "noop". # 0b. ensure an agent — register one (register.sh --v2) if none exists, to # link the verified lei identity to. # 1. up.sh — bring up the stack (witnesses, vlei-server, KERIA, @@ -59,9 +60,11 @@ VLEI_VERIFIER_URL="${VLEI_VERIFIER_URL:-http://localhost:7676}" header "vLEI verify-control demo — full run" -# 0. Ensure ans-ra is up AND wired to the real vlei-verifier. This demo -# presents real CESR, which only the "verifier" backend accepts; the plain -# start.sh default is "noop" (base64url JSON). Three cases: +# 0. Ensure ans-ra is up AND wired to the real vlei-verifier. Both backends +# accept the same real CESR, but only "verifier" actually checks GLEIF +# authorization + the signature (noop waives them), so a real end-to-end +# demo needs verifier mode. The plain start.sh default is "noop". Three +# cases: # * RA not running → fresh start in verifier mode. # * RA running, noop mode → restart in verifier mode, preserving data # (start.sh --keep keeps data/demo: agent id, SQLite store, signer keys; From f5afc641d0e17806498c63b371dd1f96b2711190 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Mon, 15 Jun 2026 09:21:01 +1000 Subject: [PATCH 05/21] feat: lei verification - remove output files --- scripts/demo/vlei/signify/out/ecr-presentation.json | 5 ----- scripts/demo/vlei/signify/out/tier1-outputs.json | 8 -------- 2 files changed, 13 deletions(-) delete mode 100644 scripts/demo/vlei/signify/out/ecr-presentation.json delete mode 100644 scripts/demo/vlei/signify/out/tier1-outputs.json diff --git a/scripts/demo/vlei/signify/out/ecr-presentation.json b/scripts/demo/vlei/signify/out/ecr-presentation.json deleted file mode 100644 index 27b66f6..0000000 --- a/scripts/demo/vlei/signify/out/ecr-presentation.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "cesr": "{\"v\":\"KERI10JSON0001b7_\",\"t\":\"icp\",\"d\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DOt6-9xBMvmyS9PmGVz3useCtbqJpuB3Yn-kMuaVRgH8\"],\"nt\":\"1\",\"n\":[\"EObUbg8u1gHxkwI33ZFIQzD4XFZQYNZQaerBpnvjSrBk\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[]}-VBq-AABAACW9PoEPZf9gtkUKUVCjY-3eThjE5YjZDxsSiyoAks_cuXlBXLPNiiodpHfsSgrH3ipkCpnt1Y3CoujtfpQjNQE-BADAAAK0Ci5-Vmb-w6030xkAxaMp5xbGt2Bx8T_BGnApUs3sDOGd0DSlW2GX8oGuKxY3hzLvSJEdcLLBGA-PLJ79WIAABAtpfJUYldswt3-YFDzlVfiBJsX4NMPbzhdLRKABHnlIPJEHj4Fc4pllzQll2XE2OrxhjAlTVCU3fH2fB2isy4AACAA4a3VsrCUGNSAO4qsGI5pobaceOfDJ7-STIrnQHd93NolKoKvNoz0nlmeHnBUBsz6nbDOWWramc9kk8kZgLwK-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d775436p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EAlosSU9P_6SG9rV9UhCf-xZ0TA-Q1xrJc6eFn4PWoEB\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"1\",\"p\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"a\":[{\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"0\",\"d\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\"}]}-VBq-AABAADgWppEnWN4KKZG3uxj5yze6h56gLSw9B3q3PrU-oUs4KOybPGSMmwSrgNnW5irQKtcRbyDNryadvrsD0RuvkQN-BADAADogN3qPVG4Wr10tNbzapl7_6u6q30E7HYPR2D9jPMZnWN_0KyIBt3sC1HeicBk7hiUqR0r4_Co3WfhQtIC1yYDABCc3MfcaYrl8L68bJhZuCH86UKsL1Mq_MsradrFMds0bcGC-7Y2698ekZuDH8R_SovKpkI7SdimYq-ffuewKd0LACCnIie-9_bPrDGuo23NfGcpYoT-zyPv_urgvjL7kjDBSC9KqNlfMCRxov8vsWPjkz42WXTrCGlEU4XEtO-1sq0N-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c15d778006p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"ENeuCZc-nwXwgI6-Q8L6RTvwqi7i9yqy3nqin7jH7dpw\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"2\",\"p\":\"EAlosSU9P_6SG9rV9UhCf-xZ0TA-Q1xrJc6eFn4PWoEB\",\"a\":[{\"i\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"s\":\"0\",\"d\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\"}]}-VBq-AABAAB0yD2ShRLE9bVA_sGR-fPw-wtcKuJVDdD6kvGHm9tyWR6HgJbBv_nlogSNQqnNeH0NRQLl18fKWhgxtYCTxoAP-BADAAATdsAgl8nIYBs2MDZvkQczgGjht20YOKgjfItz6BoAgGedMrS8JrZiOwINJ27ClV_g5pm12lxh9cyFv-Lv42YIABA2fr7H6fhaGrT3fvMWCEjpgjXlPi2ueusgDxO5WHftHeDXQAJPu7oWh6arKnD5ssUtYjJzJgJEh9yIraW2ci0AACDbNruEWQwrLOu4hPit65IxOh3UTlZJnieb6_Jn5ASa5to0X2CofwWo6nqlpSRCdSGB5eU51kQkHRnteNtb7iUB-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d319587p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EPpu0lh5fmbgWxrvRsDDNf0FhWXRBq7ckOZ95yGndJWl\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"3\",\"p\":\"ENeuCZc-nwXwgI6-Q8L6RTvwqi7i9yqy3nqin7jH7dpw\",\"a\":[{\"i\":\"EFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o\",\"s\":\"0\",\"d\":\"ECTZS9gF3NefkoXtXvL2dpP8OUSMYKQ2ODJtgv1uSedF\"}]}-VBq-AABAAAXbFIZjN6jviJfvO9aSG1XBlN_JTbbQOC4AVL48WALG4sawm3KL7SnQ11cLV1syJ_VFE2j3DdA_ydc6GodKlkE-BADAABjvthGNIZQ9q1oWclwfO3iUDut-CGi-GcHpAcW1JvXmgurbycqdKmBALeHsbbwTj0bK5IAqelk35ydrkFHMZgLABCNEZJ5l_ng1C5O_4-u4asrILdPi2rHcn-a7unX_RCqWc8QAGtrrPMN9CJ72qrv75YFNAF1jiiGLsC3Z42W7dIFACCD7OP5FKI-uD9Z9Rs3I3iLH3hrDXAN49Gu8d58woevKtpnPTt-8qD1DhDTjCL4yrXVaQit-nYo7DlItYrXs18A-EAB0AAAAAAAAAAAAAAAAAAAAAAD1AAG2026-06-11T05c26c38d348177p00c00{\"v\":\"KERI10JSON0001eb_\",\"t\":\"dip\",\"d\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DAK3yw9yruQOKWaEhJnMhASzNhTigNnpO05bZS6bON94\"],\"nt\":\"1\",\"n\":[\"ED9axlzJGRSShmIi5aT8acvww12urlP9qvL24Us7A1OA\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[],\"di\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\"}-VB8-AABAAALRoR4Q2Hdzq2I_KqR7Wq_1gbIMXhGNov4uaqUUr-sfdssr2msqrTQB3PnT16uSPoVzYY0IxHYl3iMSuhGf24E-BADAAC2L3XNeFndkopThWUGQPLghSatuQsLv0625cUlzmol3z42SlyruPJwxlm2RCjWqP6YQXhBLz6y-bT3L7e9n7kGABDRaDmi96BFrH2M508U4V54DNUUFYRqpI8tAjpubZW1umbsy6pe1K3o8GN_8aCv3MislfDZin5bsmqQqrLSWGoFACAjUiD_HUbhv0kkKS1o6IvCGa-csVkr5HvCHdhauJnJstYgObPjYcDqR7ixggGHmiZwadDf0uexIjukSHcS_UIK-GAB0AAAAAAAAAAAAAAAAAAAAAABEAlosSU9P_6SG9rV9UhCf-xZ0TA-Q1xrJc6eFn4PWoEB-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d780613p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"1\",\"p\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"a\":[{\"i\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"s\":\"0\",\"d\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\"}]}-VBq-AABAAB-zwO_a7m8TPQt70fZ_k12dL26cgOvB0by7JnyLu9ySizIvSZnTZ2px2WH8ARCKdAvOMHQvbS8Dkym4VlXSG8E-BADAAAnklHaQ9uraB__CqEfoDNliVPGUq5S0Hc2d9Ov8ixxshNVLCfnFlMusDPP_jv-kHCYVnkFUUu9cjiBZZeKYXECABC0wtUMJZx-bHnP-MZ7Y3VEo8AGP6u1CGY5H0aFcgnLPFqtuApz2tYkFRhrVs73XMhe3-8OPKG4FS060cPHP-wJACCB4oF2sMyA0eYrzPj6ukIM-jWDZMIwBtAqQ6mY610OFVCMEEGI71UBxIWJu4oVKT-Wgt4PYy31HnBJJauusPYB-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c38d413917p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EEO5ecpf-eQIX5kHGkYamO96wWWblQlwVgZnVckBJLGn\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"2\",\"p\":\"EAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_\",\"a\":[{\"i\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"s\":\"0\",\"d\":\"EAaMenfuD8insWq_MqOqntu_L0acrmL4RwHHqTwsClZs\"}]}-VBq-AABAADr7pniHv6hYHPTHl9U5uoNKzrjFuv8mlDr-hC682oooA_vnLAzCiu8r017VY5Ef6BNaLB-_6jZKoErAEQj_d8I-BADAAByP1LwRjvVYm2IHjbo4wyOjZg30ZEca5afzuT8gLbF8czYzl5Skgji-kkpJef3r-8kRghEM_wR-wfN7Z76jgwJABCcRVg8b9GbE4RA4QWnt4P6k_gUzHY9YqNOHhOQfFQlSou2vywzhcP9qTEfg8wTrPtIFvaCZBeX4XuB7xNeyhkAACCw2j_DgzVOpTctykyLrcU5lMWha_gsLn_IUYIKwabdgNK-p3i1vpKUwInE1k1q8_XyvIw43Pks9n0UL_G4fMAK-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d443212p00c00{\"v\":\"KERI10JSON000113_\",\"t\":\"vcp\",\"d\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"i\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"ii\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"s\":\"0\",\"c\":[\"NB\"],\"bt\":\"0\",\"b\":[],\"n\":\"AJz_M1jOToVGPDIJBSjeDKA19kDFn9hSnXwwMzb38zFS\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAACENeuCZc-nwXwgI6-Q8L6RTvwqi7i9yqy3nqin7jH7dpw{\"v\":\"KERI10JSON0000ed_\",\"t\":\"iss\",\"d\":\"ECTZS9gF3NefkoXtXvL2dpP8OUSMYKQ2ODJtgv1uSedF\",\"i\":\"EFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o\",\"s\":\"0\",\"ri\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"dt\":\"2026-06-11T05:26:18.944000+00:00\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAADEPpu0lh5fmbgWxrvRsDDNf0FhWXRBq7ckOZ95yGndJWl{\"v\":\"ACDC10JSON000197_\",\"d\":\"EFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o\",\"i\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\",\"ri\":\"EH7hyKa78D8BzVzNgXPBon8IFtd6RHPQXp-dGbu-trxH\",\"s\":\"EBfdlu8R27Fbx-ehrqwImnK-8Cm79sqbAQ4MmvEAYqao\",\"a\":{\"d\":\"EGw2h5vW3OEcki0tOcAnxBRD_8bwZ8qwwawVLXzRuzzb\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"LEI\":\"254900OPPU84GM83MG36\",\"dt\":\"2026-06-11T05:26:18.944000+00:00\"}}-IABEFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o0AAAAAAAAAAAAAAAAAAAAAAAECTZS9gF3NefkoXtXvL2dpP8OUSMYKQ2ODJtgv1uSedF{\"v\":\"KERI10JSON0001eb_\",\"t\":\"dip\",\"d\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DAK3yw9yruQOKWaEhJnMhASzNhTigNnpO05bZS6bON94\"],\"nt\":\"1\",\"n\":[\"ED9axlzJGRSShmIi5aT8acvww12urlP9qvL24Us7A1OA\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[],\"di\":\"EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk\"}-VB8-AABAAALRoR4Q2Hdzq2I_KqR7Wq_1gbIMXhGNov4uaqUUr-sfdssr2msqrTQB3PnT16uSPoVzYY0IxHYl3iMSuhGf24E-BADAAC2L3XNeFndkopThWUGQPLghSatuQsLv0625cUlzmol3z42SlyruPJwxlm2RCjWqP6YQXhBLz6y-bT3L7e9n7kGABDRaDmi96BFrH2M508U4V54DNUUFYRqpI8tAjpubZW1umbsy6pe1K3o8GN_8aCv3MislfDZin5bsmqQqrLSWGoFACAjUiD_HUbhv0kkKS1o6IvCGa-csVkr5HvCHdhauJnJstYgObPjYcDqR7ixggGHmiZwadDf0uexIjukSHcS_UIK-GAB0AAAAAAAAAAAAAAAAAAAAAABEAlosSU9P_6SG9rV9UhCf-xZ0TA-Q1xrJc6eFn4PWoEB-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d780613p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"1\",\"p\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"a\":[{\"i\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"s\":\"0\",\"d\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\"}]}-VBq-AABAAB-zwO_a7m8TPQt70fZ_k12dL26cgOvB0by7JnyLu9ySizIvSZnTZ2px2WH8ARCKdAvOMHQvbS8Dkym4VlXSG8E-BADAAAnklHaQ9uraB__CqEfoDNliVPGUq5S0Hc2d9Ov8ixxshNVLCfnFlMusDPP_jv-kHCYVnkFUUu9cjiBZZeKYXECABC0wtUMJZx-bHnP-MZ7Y3VEo8AGP6u1CGY5H0aFcgnLPFqtuApz2tYkFRhrVs73XMhe3-8OPKG4FS060cPHP-wJACCB4oF2sMyA0eYrzPj6ukIM-jWDZMIwBtAqQ6mY610OFVCMEEGI71UBxIWJu4oVKT-Wgt4PYy31HnBJJauusPYB-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c38d413917p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EEO5ecpf-eQIX5kHGkYamO96wWWblQlwVgZnVckBJLGn\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"2\",\"p\":\"EAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_\",\"a\":[{\"i\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"s\":\"0\",\"d\":\"EAaMenfuD8insWq_MqOqntu_L0acrmL4RwHHqTwsClZs\"}]}-VBq-AABAADr7pniHv6hYHPTHl9U5uoNKzrjFuv8mlDr-hC682oooA_vnLAzCiu8r017VY5Ef6BNaLB-_6jZKoErAEQj_d8I-BADAAByP1LwRjvVYm2IHjbo4wyOjZg30ZEca5afzuT8gLbF8czYzl5Skgji-kkpJef3r-8kRghEM_wR-wfN7Z76jgwJABCcRVg8b9GbE4RA4QWnt4P6k_gUzHY9YqNOHhOQfFQlSou2vywzhcP9qTEfg8wTrPtIFvaCZBeX4XuB7xNeyhkAACCw2j_DgzVOpTctykyLrcU5lMWha_gsLn_IUYIKwabdgNK-p3i1vpKUwInE1k1q8_XyvIw43Pks9n0UL_G4fMAK-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d443212p00c00{\"v\":\"KERI10JSON0001b7_\",\"t\":\"icp\",\"d\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DHK3QY22__M-g-r6aenExqCZDkrDDjYAS4D9QNHDPIoS\"],\"nt\":\"1\",\"n\":[\"ENaBPETNOtxW0qFWWuM9ik-EWvkwjdkbBxszCdTAMWOw\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[]}-VBq-AABAADN_CZ_3eoMeBeDbUPG5u8mqT5xuGLUxnM-rkXEEv6P8vKygh5SgR4zwCrtSDZP9-DBqt1bXIBuUeKX4A0LzrQG-BADAABkb-TucbxzyCG2WSBXWG1pZdJj7YBAN7VSxuKrJ8eID4rHIivv62F8NjCBPHFR_WkJUJEfpT0jfJoi3TYkr9gKABD7MM1UJsZzDcwF-eCOQsIGhQ6QtrPaFdui7u-woPHeO6MUiYyIEsDRqFesa64RojvndtHgPwCglsDfhBIv3-AFACAHyigAReA-PblfZmNmgoXswdE1IRAJRKXHEe9u_Tm0vKjNaQ9ytBVwSifp-9Q-s38jtgXfvI-waLNiBVXANjgE-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d763350p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"1\",\"p\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"a\":[{\"i\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"s\":\"0\",\"d\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\"}]}-VBq-AABAABOHeZrhLDPHUoB-vcLhPGVNaSzZpRXaigmVoHEDH7at2JGc9ywO1upEF9vciH_hZNQAfoqeRUziuuZ52rYX0IF-BADAADgcyIB0_J2TjU3ynQWBv6Bf5bAiIRKsDz_3Ceiwxea79EVnZ_42LZro5KsNEmAz3i9xA4BRKBUYoNELDX1AlMKABDTobQWaJhKPowsE03sbZQR2k-vDLwpX_EXdv5-jg-zhoe6Rhvza0O2nFN2Yva4IH7IerVuzfdngeJODHVtqzgEACDIB7f13YZPWBqg94cJ8ti67ils6gXqNeLpUOVAiirvMZCMv7Dm5A4bVzIqKhuvlRhCx1srU7HNDIvx-qZsxxMJ-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c38d128107p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EPJ3yPRSBaDntd5YhrHzuSdMQtke7tm_rr0MJS0AAozM\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"2\",\"p\":\"EH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5\",\"a\":[{\"i\":\"EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo\",\"s\":\"0\",\"d\":\"EBHKMw2yQzRQqZuPa0xahKYhDUNlneTaEYiW176B3j6J\"}]}-VBq-AABAAC9_eSk2dI6Bd2kHTKFEyySUxocBK6KPfdvX-EyVgS-KYYIfAWUcp9bJXkI6yaMzOxi_DRm5MhtbCnKdiz3Rj4F-BADAAC2ONz9D2E_K7QKZyCyMD9yOEz8v3iLiOWNh7PWx7sLOa-3hjog79U3R539XiiMXMXg4KR1WxKi7nHzKwpAW5kPABAYuUlJ_fToLiqCILPVAe8NFsq_4Gpw6KVHIyexr2S5Mi-D-90RVtfGyTjQ3H5z2o8387YWhMr81tCigFjh9DYIACDp1-50CHrZERSwtpOiueHxceipF4bQf9o8oButC4Au_IjIPiOAHkqglbU2eCdIs5dGnIbd5Te5p0fX97-m8FYA-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d160699p00c00{\"v\":\"KERI10JSON000113_\",\"t\":\"vcp\",\"d\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"i\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"ii\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"s\":\"0\",\"c\":[\"NB\"],\"bt\":\"0\",\"b\":[],\"n\":\"AJVgZbUEagvvBdKPc-VXOhdKwIc-vYLPnfukzFtZsImS\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAABEAQ4u3MCJFZQuZmrpbfDkymd4Ow0SZqz9hKssQw7zX4_{\"v\":\"KERI10JSON0000ed_\",\"t\":\"iss\",\"d\":\"EAaMenfuD8insWq_MqOqntu_L0acrmL4RwHHqTwsClZs\",\"i\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"s\":\"0\",\"ri\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"dt\":\"2026-06-11T05:26:27.161000+00:00\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAACEEO5ecpf-eQIX5kHGkYamO96wWWblQlwVgZnVckBJLGn{\"v\":\"ACDC10JSON0005c8_\",\"d\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"i\":\"EE90lsKcXR7s-nULTURBhtKD6Eyjtgwtn7T_HKAYGovn\",\"ri\":\"ELvoz8SYcyons7ytNhhMzOY2GgvM-RO7mhj1GK6D8SFf\",\"s\":\"ENPXp1vQzRF6JwIuS-mp2U8Uf1MoADoP_GqQ62VsDZWY\",\"a\":{\"d\":\"ECakQY3CY0BAdwD-gCe-2Jurs7WibLea3ilNtZBdBi2X\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"LEI\":\"875500ELOZEL05BVXV37\",\"dt\":\"2026-06-11T05:26:27.161000+00:00\"},\"e\":{\"d\":\"EFyuG5XkRQkOKfHcubrp9cNTXkKrLdKTPSFky1ntcedI\",\"qvi\":{\"n\":\"EFfRtRsxpEej-zIHPIcsfUDGrLRwS_2aVgOzOwbL941o\",\"s\":\"EBfdlu8R27Fbx-ehrqwImnK-8Cm79sqbAQ4MmvEAYqao\"}},\"r\":{\"d\":\"EGZ97EjPSINR-O-KHDN_uw4fdrTxeuRXrqT5ZHHQJujQ\",\"usageDisclaimer\":{\"l\":\"Usage of a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, does not assert that the Legal Entity is trustworthy, honest, reputable in its business dealings, safe to do business with, or compliant with any laws or that an implied or expressly intended purpose will be fulfilled.\"},\"issuanceDisclaimer\":{\"l\":\"All information in a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, is accurate as of the date the validation process was complete. The vLEI Credential has been issued to the legal entity or person named in the vLEI Credential as the subject; and the qualified vLEI Issuer exercised reasonable care to perform the validation process set forth in the vLEI Ecosystem Governance Framework.\"}}}-IABED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni0AAAAAAAAAAAAAAAAAAAAAAAEAaMenfuD8insWq_MqOqntu_L0acrmL4RwHHqTwsClZs{\"v\":\"KERI10JSON0001b7_\",\"t\":\"icp\",\"d\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DHK3QY22__M-g-r6aenExqCZDkrDDjYAS4D9QNHDPIoS\"],\"nt\":\"1\",\"n\":[\"ENaBPETNOtxW0qFWWuM9ik-EWvkwjdkbBxszCdTAMWOw\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[]}-VBq-AABAADN_CZ_3eoMeBeDbUPG5u8mqT5xuGLUxnM-rkXEEv6P8vKygh5SgR4zwCrtSDZP9-DBqt1bXIBuUeKX4A0LzrQG-BADAABkb-TucbxzyCG2WSBXWG1pZdJj7YBAN7VSxuKrJ8eID4rHIivv62F8NjCBPHFR_WkJUJEfpT0jfJoi3TYkr9gKABD7MM1UJsZzDcwF-eCOQsIGhQ6QtrPaFdui7u-woPHeO6MUiYyIEsDRqFesa64RojvndtHgPwCglsDfhBIv3-AFACAHyigAReA-PblfZmNmgoXswdE1IRAJRKXHEe9u_Tm0vKjNaQ9ytBVwSifp-9Q-s38jtgXfvI-waLNiBVXANjgE-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c15d763350p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"1\",\"p\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"a\":[{\"i\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"s\":\"0\",\"d\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\"}]}-VBq-AABAABOHeZrhLDPHUoB-vcLhPGVNaSzZpRXaigmVoHEDH7at2JGc9ywO1upEF9vciH_hZNQAfoqeRUziuuZ52rYX0IF-BADAADgcyIB0_J2TjU3ynQWBv6Bf5bAiIRKsDz_3Ceiwxea79EVnZ_42LZro5KsNEmAz3i9xA4BRKBUYoNELDX1AlMKABDTobQWaJhKPowsE03sbZQR2k-vDLwpX_EXdv5-jg-zhoe6Rhvza0O2nFN2Yva4IH7IerVuzfdngeJODHVtqzgEACDIB7f13YZPWBqg94cJ8ti67ils6gXqNeLpUOVAiirvMZCMv7Dm5A4bVzIqKhuvlRhCx1srU7HNDIvx-qZsxxMJ-EAB0AAAAAAAAAAAAAAAAAAAAAAB1AAG2026-06-11T05c26c38d128107p00c00{\"v\":\"KERI10JSON00013a_\",\"t\":\"ixn\",\"d\":\"EPJ3yPRSBaDntd5YhrHzuSdMQtke7tm_rr0MJS0AAozM\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"2\",\"p\":\"EH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5\",\"a\":[{\"i\":\"EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo\",\"s\":\"0\",\"d\":\"EBHKMw2yQzRQqZuPa0xahKYhDUNlneTaEYiW176B3j6J\"}]}-VBq-AABAAC9_eSk2dI6Bd2kHTKFEyySUxocBK6KPfdvX-EyVgS-KYYIfAWUcp9bJXkI6yaMzOxi_DRm5MhtbCnKdiz3Rj4F-BADAAC2ONz9D2E_K7QKZyCyMD9yOEz8v3iLiOWNh7PWx7sLOa-3hjog79U3R539XiiMXMXg4KR1WxKi7nHzKwpAW5kPABAYuUlJ_fToLiqCILPVAe8NFsq_4Gpw6KVHIyexr2S5Mi-D-90RVtfGyTjQ3H5z2o8387YWhMr81tCigFjh9DYIACDp1-50CHrZERSwtpOiueHxceipF4bQf9o8oButC4Au_IjIPiOAHkqglbU2eCdIs5dGnIbd5Te5p0fX97-m8FYA-EAB0AAAAAAAAAAAAAAAAAAAAAAC1AAG2026-06-11T05c26c38d160699p00c00{\"v\":\"KERI10JSON0001b7_\",\"t\":\"icp\",\"d\":\"EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ\",\"i\":\"EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ\",\"s\":\"0\",\"kt\":\"1\",\"k\":[\"DENUslY77aNd5ez5mQGnZLQi9YJSKCt2mer8mPCjHeNx\"],\"nt\":\"1\",\"n\":[\"EIVDLsI2ulIfhIlHlH-kCKqtiuCw_Pc642I0r98_Qo8u\"],\"bt\":\"3\",\"b\":[\"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha\",\"BLskRTInXnMxWaGqcpSyMgo0nYbalW99cGZESrz3zapM\",\"BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX\"],\"c\":[],\"a\":[]}-VBq-AABAABmYlUzVzuGTJXFr3zviRAPWtQHStBe2tLowYqNzjuAzpK5gknf0udEIiHZ-o_RPF2KrnjA5XCwA7zZVe2p57AF-BADAADOS7aLgNlCYnR1dO1Lfldd-MYBYiQHOtg32HDb0PTw7FEx2WEX5POITVnIeJWAHXlM137x9llZEh2t7LGP2GsNABAeSCw0ycKP_VDqkZxOBGM8e-L7Tsup1VJ3E_GzxQRM98YHgN5i1P0VZz7qTNi9NDHx7aVef8KZf2nrV3DdA90LACAfXhTVWETo3mxgdvv0vFtCt4uA7ls-TappbNRYtyC_7sYrlBwOyaUVSJwRy9ni3BGTpJUbHUDwTdxM_FcsSsYO-EAB0AAAAAAAAAAAAAAAAAAAAAAA1AAG2026-06-11T05c26c14d690903p00c00{\"v\":\"KERI10JSON000113_\",\"t\":\"vcp\",\"d\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"i\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"ii\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"s\":\"0\",\"c\":[\"NB\"],\"bt\":\"0\",\"b\":[],\"n\":\"AMfztkZztZR2U0MFg-ee2Ln_OnMSo_FeLiZKdz_5f--M\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAABEH03qv-5vJj7Aj0xqqAiJtb8lLHdRigqZ0YJml5-6WC5{\"v\":\"KERI10JSON0000ed_\",\"t\":\"iss\",\"d\":\"EBHKMw2yQzRQqZuPa0xahKYhDUNlneTaEYiW176B3j6J\",\"i\":\"EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo\",\"s\":\"0\",\"ri\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"dt\":\"2026-06-11T05:26:35.317000+00:00\"}-VAS-GAB0AAAAAAAAAAAAAAAAAAAAAACEPJ3yPRSBaDntd5YhrHzuSdMQtke7tm_rr0MJS0AAozM{\"v\":\"ACDC10JSON0007dc_\",\"d\":\"EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo\",\"u\":\"0ABn4IzwUDKKhmE7QsLHRaP4\",\"i\":\"EASg13cakYl180PhXoDyGaCC_L_Vp7ZhIphZioA1Oed2\",\"ri\":\"EENW45f2OuBe9nOO99KyXw0iGQ8zNRGHCc0dty3vRqjA\",\"s\":\"EEy9PkikFcANV1l7EHukCeXqrzT1hNZjGlUk7wuMO5jw\",\"a\":{\"d\":\"EMQbEw2G0VSZN9DJuH5nyXRGMq4Ry6BesBykVDxGJPWt\",\"i\":\"EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ\",\"LEI\":\"875500ELOZEL05BVXV37\",\"personLegalName\":\"John Doe\",\"engagementContextRole\":\"Managing Director\",\"dt\":\"2026-06-11T05:26:35.317000+00:00\"},\"e\":{\"d\":\"EN-tndHWF0jJITEJYL2-iyif-yk-spZ_PZcfBvsv6NEk\",\"le\":{\"n\":\"ED9pqCxYI519oB3fOqq1WLBCq8QwQO8tvlUfiFbksNni\",\"s\":\"ENPXp1vQzRF6JwIuS-mp2U8Uf1MoADoP_GqQ62VsDZWY\"}},\"r\":{\"d\":\"EIfq_m1DI2IQ1MgHhUl9sq3IQ_PJP9WQ1LhbMscngDCB\",\"usageDisclaimer\":{\"l\":\"Usage of a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, does not assert that the Legal Entity is trustworthy, honest, reputable in its business dealings, safe to do business with, or compliant with any laws or that an implied or expressly intended purpose will be fulfilled.\"},\"issuanceDisclaimer\":{\"l\":\"All information in a valid, unexpired, and non-revoked vLEI Credential, as defined in the associated Ecosystem Governance Framework, is accurate as of the date the validation process was complete. The vLEI Credential has been issued to the legal entity or person named in the vLEI Credential as the subject; and the qualified vLEI Issuer exercised reasonable care to perform the validation process set forth in the vLEI Ecosystem Governance Framework.\"},\"privacyDisclaimer\":{\"l\":\"It is the sole responsibility of Holders as Issuees of an ECR vLEI Credential to present that Credential in a privacy-preserving manner using the mechanisms provided in the Issuance and Presentation Exchange (IPEX) protocol specification and the Authentic Chained Data Container (ACDC) specification. https://github.com/WebOfTrust/IETF-IPEX and https://github.com/trustoverip/tswg-acdc-specification.\"}}}-IABEHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo0AAAAAAAAAAAAAAAAAAAAAAAEBHKMw2yQzRQqZuPa0xahKYhDUNlneTaEYiW176B3j6J", - "lei": "875500ELOZEL05BVXV37", - "aid": "EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ" -} \ No newline at end of file diff --git a/scripts/demo/vlei/signify/out/tier1-outputs.json b/scripts/demo/vlei/signify/out/tier1-outputs.json deleted file mode 100644 index 1f32957..0000000 --- a/scripts/demo/vlei/signify/out/tier1-outputs.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "gleifPrefix": "EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk", - "rolePrefix": "EDHSXmNtZy3QDgOv_jB6cJesIcMdqnPYZoBnla-qwIZJ", - "roleBran": "DWvi_zlnWH8sKWYLEsSh1", - "LEI": "875500ELOZEL05BVXV37", - "ecrCredentialSaid": "EHiDXP4s7QaMGMbpHGmm3e1GYET4EtrrGyhMcDEz3Mmo", - "gleifOOBI": "http://keria:3902/oobi/EEc4ZankjRGMnFyu1AZrYtf_jg3VLVylci2n51KgAuXk/agent/ENvos4PmBAa28ZTPKVrSgtXZ3bRhgRP_zpRk0Q914d2L" -} \ No newline at end of file From 8326827ee724c054ba9b57bb53b9bb6a37a4c4fa Mon Sep 17 00:00:00 2001 From: James Hateley Date: Wed, 17 Jun 2026 10:16:21 +1000 Subject: [PATCH 06/21] fix(migrations): identity_subject_aid 009->008 Signed-off-by: James Hateley --- ...{009_identity_subject_aid.sql => 008_identity_subject_aid.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename internal/adapter/store/sqlite/migrations/{009_identity_subject_aid.sql => 008_identity_subject_aid.sql} (100%) diff --git a/internal/adapter/store/sqlite/migrations/009_identity_subject_aid.sql b/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql similarity index 100% rename from internal/adapter/store/sqlite/migrations/009_identity_subject_aid.sql rename to internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql From 3ba47b4c6b79cc160f7626f9c9e3883a0377c9d8 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Wed, 17 Jun 2026 10:53:02 +1000 Subject: [PATCH 07/21] fix(test): fix rebase error Signed-off-by: James Hateley --- internal/ra/service/identity_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/ra/service/identity_test.go b/internal/ra/service/identity_test.go index 885d9eb..ad69da3 100644 --- a/internal/ra/service/identity_test.go +++ b/internal/ra/service/identity_test.go @@ -1530,6 +1530,7 @@ func TestReleaseClaim_LeakedClaimIsLoggedNotSwallowed(t *testing.T) { sqlite.NewAgentStore(db), didresolver.NewNoopResolver(), sealer, + leiverifier.NewNoop(), db, ).WithSigner(service.EventSigner{KeyManager: km, KeyID: "ra-signer", RaID: "ra-test"}). WithClock(clock.Now).WithLogger(zerolog.New(io.Discard)) From 32cf93c4717bc6a060d57c7b8616e52369ec6206 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Wed, 17 Jun 2026 10:53:28 +1000 Subject: [PATCH 08/21] fix(doc): fix stale comments Signed-off-by: James Hateley --- internal/domain/identity.go | 4 ++-- internal/ra/service/identity.go | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/domain/identity.go b/internal/domain/identity.go index 5caff07..cd67e71 100644 --- a/internal/domain/identity.go +++ b/internal/domain/identity.go @@ -85,8 +85,8 @@ type VerifiedIdentity struct { Value string Status IdentityStatus // ProofMethod names the control proof that verified this - // identity ("did-web-sig" | "did-key-sig"). Empty until the - // first successful verify-control. + // identity ("did-web-sig" | "did-key-sig" | "lei-vlei-acdc"). + // Empty until the first successful verify-control. ProofMethod string // PendingValue stages a same-kind replacement during rotation // (§4.2): set by StageRotation, applied by CompleteVerification. diff --git a/internal/ra/service/identity.go b/internal/ra/service/identity.go index d0e4756..ecf3736 100644 --- a/internal/ra/service/identity.go +++ b/internal/ra/service/identity.go @@ -222,9 +222,9 @@ func (s *IdentityService) raID() string { } // verifierFor returns the kind's control verifier, or the precise -// IDENTIFIER_KIND_UNSUPPORTED error when this deployment has none — -// lei is recognized lexically but postponed: the route exists, the -// kind does not until its verifier registers (identitykinds.go). +// IDENTIFIER_KIND_UNSUPPORTED error when this deployment has none. +// Kinds are recognized lexically but only enabled once their verifier +// registers (identitykinds.go). func (s *IdentityService) verifierFor(kind domain.IdentifierKind) (controlVerifier, error) { v, ok := s.verifiers[kind] if !ok { From a083b03b2b954f1af57d4d4a7d3e2e8e7bc82337 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Wed, 17 Jun 2026 14:33:30 +1000 Subject: [PATCH 09/21] fix: fixes from review feedback Signed-off-by: James Hateley --- cmd/ans-ra/main.go | 10 +- internal/adapter/docsui/openapi/ra.yaml | 28 +++--- .../adapter/leiverifier/leiverifier_test.go | 18 ++++ internal/adapter/leiverifier/noop.go | 2 +- internal/adapter/leiverifier/verifier.go | 42 +++++---- internal/adapter/store/sqlite/identity.go | 48 ++++++---- .../adapter/store/sqlite/identity_test.go | 51 ++++++++++ .../migrations/008_identity_subject_aid.sql | 6 ++ internal/domain/identity.go | 33 +++++-- internal/domain/identity_test.go | 30 ++++-- internal/port/leiverifier.go | 10 +- internal/ra/handler/identity.go | 5 +- internal/ra/handler/identity_handler_test.go | 92 +++++++++++++++++++ internal/ra/service/identity.go | 4 +- internal/ra/service/identity_lei_test.go | 72 +++++++++++++++ internal/ra/service/identitykinds.go | 20 +++- internal/ra/service/leiverifier.go | 11 ++- scripts/demo/vlei/docker-compose.yml | 16 ++-- scripts/demo/vlei/signify/scripts_ts/utils.ts | 2 +- spec/api-spec-v2.yaml | 28 +++--- 20 files changed, 429 insertions(+), 99 deletions(-) diff --git a/cmd/ans-ra/main.go b/cmd/ans-ra/main.go index 0b74a13..6377435 100644 --- a/cmd/ans-ra/main.go +++ b/cmd/ans-ra/main.go @@ -164,6 +164,10 @@ func run(cfgPath string) error { Dur("challengeTTL", cfg.Identity.ChallengeTTL). Msg("verified-identity surface configured") + if cfg.VLEI.Type == "noop" { + logger.Warn().Msg("vlei.type=noop — signature & authorization checks waived, NOT for production") + } + logger.Info(). Str("tlPublicBaseURL", cfg.TLClient.PublicBaseURL). Str("tlBaseURL", cfg.TLClient.BaseURL). @@ -525,9 +529,9 @@ func selectDIDResolver(cfg *config.RAConfig, logger zerolog.Logger) port.DIDReso // selectLEIVerifier returns the configured vLEI control verifier — the // lei kind's analog of selectDIDResolver. "verifier" is the hardened // HTTP client for an internal vlei-verifier (config-validated base -// URL); the default "noop" runs real Ed25519 crypto over the signing -// input but waives the GLEIF authorization binding, for self-contained -// local development. +// URL); the default "noop" performs structural-only qb64 checks and +// waives both the GLEIF authorization binding and the cryptographic +// signature check func selectLEIVerifier(cfg *config.RAConfig) port.LEIControlVerifier { switch cfg.VLEI.Type { case "verifier": diff --git a/internal/adapter/docsui/openapi/ra.yaml b/internal/adapter/docsui/openapi/ra.yaml index 90d48a2..4288e61 100644 --- a/internal/adapter/docsui/openapi/ra.yaml +++ b/internal/adapter/docsui/openapi/ra.yaml @@ -1096,6 +1096,12 @@ paths: closed. The nonce is consumed exactly once, inside the success transaction — a failed attempt does not consume it. + The `lei` kind instead submits a single `cesrSignature` over + the same `signingInput`: the RA forwards it to the + vlei-verifier, which live-rechecks the subject AID's + authorization and verifies the signature against its current + KEL key state. + JWS bearing unrecognized `crit` header parameters are rejected (RFC 7515 §4.1.11) — this verifier implements no critical extensions. @@ -1155,14 +1161,14 @@ paths: description: | Proof rejected — `PRICC_SIGNATURE_INVALID`, `DID_VERIFICATION_METHOD_INVALID`, `DID_RESOLUTION_FAILED`, - `DID_DOCUMENT_ID_MISMATCH`, `IDENTIFIER_PROOF_INVALID`. + `DID_DOCUMENT_ID_MISMATCH`, `IDENTIFIER_PROOF_INVALID`, `LEI_NOT_AUTHORIZED`, `LEI_MISMATCH`. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '503': - description: Transparency Log unavailable (TL_UNAVAILABLE — retryable; the nonce is NOT consumed) + description: Upstream unavailable (TL_UNAVAILABLE, or LEI_VERIFIER_UNAVAILABLE — retryable; the nonce is NOT consumed) content: application/json: schema: @@ -2111,15 +2117,6 @@ components: description: The canonical identifier this round proves status: $ref: '#/components/schemas/IdentityLifecycleStatus' - presentationStatus: - type: string - description: | - The lei register-time advisory authorization status from - the vlei-verifier (`AUTHORIZED` | `PENDING`). Omitted for - kinds with no register-time presentation (`did:web`, - `did:key`). Advisory only — control is finally established - by a LIVE re-authorization at verify-control. - enum: ['AUTHORIZED', 'PENDING'] nonce: type: string description: Base64url 32-byte single-use anti-replay nonce @@ -2130,6 +2127,15 @@ components: type: array items: $ref: '#/components/schemas/IdentityProofChallenge' + presentationStatus: + type: string + enum: [AUTHORIZED, PENDING] + description: | + The lei register-time advisory authorization status from + the vlei-verifier (`AUTHORIZED` | `PENDING`). Omitted for + kinds with no register-time presentation (`did:web`, + `did:key`). Advisory only — control is finally established + by a LIVE re-authorization at verify-control. required: - identityId - kind diff --git a/internal/adapter/leiverifier/leiverifier_test.go b/internal/adapter/leiverifier/leiverifier_test.go index 702cc67..0fa2ef5 100644 --- a/internal/adapter/leiverifier/leiverifier_test.go +++ b/internal/adapter/leiverifier/leiverifier_test.go @@ -2,9 +2,11 @@ package leiverifier import ( "context" + "encoding/json" "errors" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -363,6 +365,22 @@ func TestPresentedCredentialSAID(t *testing.T) { } } +// TestCollectEdgeNodesDepthBound pins the recursion guard: a shallow `n` +// is collected, one nested past maxEdgeDepth (64) is ignored, and the +// walk terminates on adversarial deep nesting instead of overflowing. +func TestCollectEdgeNodesDepthBound(t *testing.T) { + raw := json.RawMessage(`{"n":"ESHALLOW","deep":` + + strings.Repeat(`{"x":`, 100) + `{"n":"EDEEP"}` + strings.Repeat(`}`, 100) + `}`) + seen := map[string]struct{}{} + collectEdgeNodes(raw, seen) + if _, ok := seen["ESHALLOW"]; !ok { + t.Fatal("shallow edge node not collected") + } + if _, ok := seen["EDEEP"]; ok { + t.Fatal("edge node past maxEdgeDepth must be ignored") + } +} + func isCode(err error, code string) bool { var de *domain.Error return errors.As(err, &de) && de.Code == code diff --git a/internal/adapter/leiverifier/noop.go b/internal/adapter/leiverifier/noop.go index 4040112..a192d9c 100644 --- a/internal/adapter/leiverifier/noop.go +++ b/internal/adapter/leiverifier/noop.go @@ -69,7 +69,7 @@ func (n *Noop) Present(_ context.Context, cesr string) (port.PresentationResult, return port.PresentationResult{ SubjectAID: leaf.A.I, LEI: leaf.A.LEI, - Status: "AUTHORIZED", + Status: port.StatusAuthorized, }, nil } diff --git a/internal/adapter/leiverifier/verifier.go b/internal/adapter/leiverifier/verifier.go index 7376f1b..0f3ac68 100644 --- a/internal/adapter/leiverifier/verifier.go +++ b/internal/adapter/leiverifier/verifier.go @@ -138,7 +138,7 @@ func (v *Verifier) Present(ctx context.Context, cesr string) (port.PresentationR req.Header.Set("Content-Type", "application/json+cesr") var pres presentationResponse - status, err := v.do(req, &pres) + status, err := v.do(req, &pres, "present") if err != nil { return port.PresentationResult{}, err } @@ -162,14 +162,14 @@ func (v *Verifier) Present(ctx context.Context, cesr string) (port.PresentationR if err != nil { return port.PresentationResult{}, err } - status0 := "PENDING" + presStatus := port.StatusPending if auth.Authorized { - status0 = "AUTHORIZED" + presStatus = port.StatusAuthorized } return port.PresentationResult{ SubjectAID: pres.AID, LEI: auth.LEI, - Status: status0, + Status: presStatus, }, nil } @@ -188,7 +188,7 @@ func (v *Verifier) Authorization(ctx context.Context, subjectAID string) (port.A return port.AuthorizationResult{}, v.unavailable("authorize") } var auth authorizationResponse - status, err := v.do(req, &auth) + status, err := v.do(req, &auth, "authorize") if err != nil { return port.AuthorizationResult{}, err } @@ -234,7 +234,7 @@ func (v *Verifier) VerifySignature(ctx context.Context, subjectAID, signingInput } req.Header.Set("Content-Type", "application/json") - status, err := v.do(req, nil) + status, err := v.do(req, nil, "verify-signature") if err != nil { return false, err } @@ -255,7 +255,7 @@ func (v *Verifier) VerifySignature(ctx context.Context, subjectAID, signingInput // do executes the request, enforces the response-size cap, and (when // out is non-nil and the status carries a JSON body) decodes it. // Returns the status code so callers map it to domain semantics. -func (v *Verifier) do(req *http.Request, out any) (int, error) { +func (v *Verifier) do(req *http.Request, out any, op string) (int, error) { // The request URL is built only from the operator-configured baseURL // (a trusted internal vlei-verifier) plus verifier-controlled path // segments — never from registrant input — so the SSRF posture the @@ -263,16 +263,16 @@ func (v *Verifier) do(req *http.Request, out any) (int, error) { resp, err := v.client.Do(req) //nolint:gosec // baseURL is operator-configured; no caller-controlled host if err != nil { - return 0, v.unavailable(req.Method) + return 0, v.unavailable(op) } defer func() { _ = resp.Body.Close() }() body, err := io.ReadAll(io.LimitReader(resp.Body, v.maxBodyBytes+1)) if err != nil { - return resp.StatusCode, v.unavailable(req.Method) + return resp.StatusCode, v.unavailable(op) } if int64(len(body)) > v.maxBodyBytes { - return resp.StatusCode, v.unavailable(req.Method) + return resp.StatusCode, v.unavailable(op) } // Decode strictly on a 2xx success — the contract callers rely on. // A 200 with malformed JSON would otherwise leave `out` zero-valued @@ -293,8 +293,8 @@ func (v *Verifier) do(req *http.Request, out any) (int, error) { // protocol failure. The detail names the operation but never the // configured host (no internal-topology leak). func (v *Verifier) unavailable(op string) error { - return domain.NewInternalError("LEI_VERIFIER_UNAVAILABLE", - fmt.Sprintf("the vlei verifier is unavailable (%s)", op), nil) + return domain.NewUnavailableError("LEI_VERIFIER_UNAVAILABLE", + fmt.Sprintf("the vlei verifier is unavailable (%s)", op)) } // isQB64 reports whether s is a non-empty CESR qb64 token — the @@ -367,7 +367,7 @@ func scanACDCChain(cesr string) ([]acdcFrame, map[string]struct{}) { start := offset + loc[0] obj, end := balancedJSONObject(cesr, start) if obj == "" { - offset = start + 1 + offset = end // unbalanced tail: jump to end, no O(N²) byte rescan continue } offset = end @@ -425,8 +425,14 @@ func collectEdgeNodes(raw json.RawMessage, seen map[string]struct{}) { if err := json.Unmarshal(raw, &doc); err != nil { return } - var walk func(v any) - walk = func(v any) { + // maxEdgeDepth bounds recursion over attacker-controlled edge JSON; + // real ECR→LE→QVI chains nest ~3 deep. + const maxEdgeDepth = 64 + var walk func(v any, depth int) + walk = func(v any, depth int) { + if depth > maxEdgeDepth { + return + } switch t := v.(type) { case map[string]any: for k, val := range t { @@ -435,15 +441,15 @@ func collectEdgeNodes(raw json.RawMessage, seen map[string]struct{}) { seen[s] = struct{}{} } } - walk(val) + walk(val, depth+1) } case []any: for _, el := range t { - walk(el) + walk(el, depth+1) } } } - walk(doc) + walk(doc, 0) } // balancedJSONObject returns the JSON object beginning at start diff --git a/internal/adapter/store/sqlite/identity.go b/internal/adapter/store/sqlite/identity.go index 3406c77..a569db5 100644 --- a/internal/adapter/store/sqlite/identity.go +++ b/internal/adapter/store/sqlite/identity.go @@ -26,6 +26,7 @@ type identityRow struct { ProofMethod string `db:"proof_method"` PendingValue string `db:"pending_value"` SubjectAID sql.NullString `db:"subject_aid"` + PendingSubjectAID sql.NullString `db:"pending_subject_aid"` ChallengeNonce sql.NullString `db:"challenge_nonce"` ChallengeExpiresAtMs sql.NullInt64 `db:"challenge_expires_at_ms"` ChallengeConsumedAtMs sql.NullInt64 `db:"challenge_consumed_at_ms"` @@ -35,21 +36,22 @@ type identityRow struct { } const identityCols = `identity_id, provider_id, kind, value, status, proof_method, - pending_value, subject_aid, challenge_nonce, challenge_expires_at_ms, + pending_value, subject_aid, pending_subject_aid, challenge_nonce, challenge_expires_at_ms, challenge_consumed_at_ms, verified_at_ms, created_at_ms, updated_at_ms` func (r identityRow) toDomain() *domain.VerifiedIdentity { v := &domain.VerifiedIdentity{ - IdentityID: r.IdentityID, - ProviderID: r.ProviderID, - Kind: domain.IdentifierKind(r.Kind), - Value: r.Value, - Status: domain.IdentityStatus(r.Status), - ProofMethod: r.ProofMethod, - PendingValue: r.PendingValue, - SubjectAID: r.SubjectAID.String, - CreatedAt: msToTime(r.CreatedAtMs), - UpdatedAt: msToTime(r.UpdatedAtMs), + IdentityID: r.IdentityID, + ProviderID: r.ProviderID, + Kind: domain.IdentifierKind(r.Kind), + Value: r.Value, + Status: domain.IdentityStatus(r.Status), + ProofMethod: r.ProofMethod, + PendingValue: r.PendingValue, + SubjectAID: r.SubjectAID.String, + PendingSubjectAID: r.PendingSubjectAID.String, + CreatedAt: msToTime(r.CreatedAtMs), + UpdatedAt: msToTime(r.UpdatedAtMs), } if r.VerifiedAtMs.Valid { v.VerifiedAt = msToTime(r.VerifiedAtMs.Int64) @@ -87,19 +89,23 @@ func (s *IdentityStore) Save(ctx context.Context, v *domain.VerifiedIdentity) er if !v.VerifiedAt.IsZero() { verifiedAt = sql.NullInt64{Int64: v.VerifiedAt.UnixMilli(), Valid: true} } - var subjectAID sql.NullString + var subjectAID, pendingSubjectAID sql.NullString if v.SubjectAID != "" { subjectAID = sql.NullString{String: v.SubjectAID, Valid: true} } + if v.PendingSubjectAID != "" { + pendingSubjectAID = sql.NullString{String: v.PendingSubjectAID, Valid: true} + } const q = ` INSERT INTO identities (` + identityCols + `) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(identity_id) DO UPDATE SET value = excluded.value, status = excluded.status, proof_method = excluded.proof_method, pending_value = excluded.pending_value, subject_aid = excluded.subject_aid, + pending_subject_aid = excluded.pending_subject_aid, challenge_nonce = excluded.challenge_nonce, challenge_expires_at_ms = excluded.challenge_expires_at_ms, challenge_consumed_at_ms = excluded.challenge_consumed_at_ms, @@ -113,7 +119,7 @@ func (s *IdentityStore) Save(ctx context.Context, v *domain.VerifiedIdentity) er updated_at_ms = excluded.updated_at_ms` _, err := s.db.extx(ctx).ExecContext(ctx, q, v.IdentityID, v.ProviderID, string(v.Kind), v.Value, string(v.Status), - v.ProofMethod, v.PendingValue, subjectAID, + v.ProofMethod, v.PendingValue, subjectAID, pendingSubjectAID, nonce, expiresAt, consumedAt, verifiedAt, v.CreatedAt.UnixMilli(), v.UpdatedAt.UnixMilli(), ) @@ -316,9 +322,12 @@ func (s *IdentityStore) StageChallenge( if !v.Challenge.ExpiresAt.IsZero() { expires = sql.NullInt64{Int64: v.Challenge.ExpiresAt.UnixMilli(), Valid: true} } - var subjectAID sql.NullString - if v.SubjectAID != "" { - subjectAID = sql.NullString{String: v.SubjectAID, Valid: true} + // Stage the presented AID into pending_subject_aid; the proven + // subject_aid is left untouched so an abandoned rotation never + // overwrites it (promotion happens on verify, in Save). + var pendingSubjectAID sql.NullString + if v.PendingSubjectAID != "" { + pendingSubjectAID = sql.NullString{String: v.PendingSubjectAID, Valid: true} } res, err := s.db.extx(ctx).ExecContext(ctx, ` UPDATE identities @@ -327,13 +336,13 @@ func (s *IdentityStore) StageChallenge( challenge_consumed_at_ms = NULL, challenge_claimed_at_ms = NULL, pending_value = ?, - subject_aid = ?, + pending_subject_aid = ?, updated_at_ms = ? WHERE identity_id = ? AND status = ? AND (challenge_nonce = ? OR (challenge_nonce IS NULL AND ? = '')) AND (challenge_claimed_at_ms IS NULL OR challenge_claimed_at_ms < ?)`, - v.Challenge.Nonce, expires, v.PendingValue, subjectAID, v.UpdatedAt.UnixMilli(), + v.Challenge.Nonce, expires, v.PendingValue, pendingSubjectAID, v.UpdatedAt.UnixMilli(), v.IdentityID, string(expectedStatus), expectedNonce, expectedNonce, staleBefore.UnixMilli()) if err != nil { @@ -375,6 +384,7 @@ func (s *IdentityStore) MarkRevoked(ctx context.Context, identityID string, now UPDATE identities SET status = 'REVOKED', pending_value = '', + pending_subject_aid = NULL, challenge_nonce = NULL, challenge_expires_at_ms = NULL, challenge_consumed_at_ms = NULL, diff --git a/internal/adapter/store/sqlite/identity_test.go b/internal/adapter/store/sqlite/identity_test.go index 9644f62..c36a7ca 100644 --- a/internal/adapter/store/sqlite/identity_test.go +++ b/internal/adapter/store/sqlite/identity_test.go @@ -455,6 +455,57 @@ func TestIdentityStore_StageChallengeOptimisticConcurrency(t *testing.T) { } } +// TestIdentityStore_SubjectAIDRoundTrip pins the lei subject-AID +// columns: Save promotes a verified SubjectAID into subject_aid (read +// back on FindByID), and StageChallenge writes a rotation's +// PendingSubjectAID into pending_subject_aid while leaving the proven +// subject_aid untouched — the H1 store guarantee that an abandoned +// rotation never overwrites the live signer. +func TestIdentityStore_SubjectAIDRoundTrip(t *testing.T) { + db := newTestDB(t) + store := NewIdentityStore(db) + ctx := context.Background() + + v := newIdentityFixture(t, "id-lei", "owner-1", "5493001KJTIIGC8Y1R17") + if v.Kind != domain.KindLEI { + t.Fatalf("fixture kind = %s, want lei", v.Kind) + } + // Stage then promote the verifier-derived AID, mirroring a verify. + if err := v.StageSubjectAID("EHolderAID", identityNow); err != nil { + t.Fatal(err) + } + if _, err := v.CompleteVerification(identityNow); err != nil { + t.Fatal(err) + } + if err := store.Save(ctx, v); err != nil { + t.Fatalf("save: %v", err) + } + got, err := store.FindByID(ctx, "id-lei") + if err != nil { + t.Fatal(err) + } + if got.SubjectAID != "EHolderAID" || got.PendingSubjectAID != "" { + t.Fatalf("proven AID round-trip: proven=%q pending=%q", got.SubjectAID, got.PendingSubjectAID) + } + + // A rotation stages a new AID via StageChallenge: pending_subject_aid + // is written, the proven subject_aid is left untouched. + got.PendingSubjectAID = "ERotatedAID" + if err := got.IssueChallenge("nonce-rot", time.Hour, identityNow.Add(time.Minute)); err != nil { + t.Fatal(err) + } + if err := store.StageChallenge(ctx, got, domain.IdentityVerified, "", identityNow); err != nil { + t.Fatalf("stage: %v", err) + } + reloaded, err := store.FindByID(ctx, "id-lei") + if err != nil { + t.Fatal(err) + } + if reloaded.SubjectAID != "EHolderAID" || reloaded.PendingSubjectAID != "ERotatedAID" { + t.Fatalf("staged AID round-trip: proven=%q pending=%q", reloaded.SubjectAID, reloaded.PendingSubjectAID) + } +} + func TestIdentityStore_MarkRevokedConditional(t *testing.T) { db := newTestDB(t) store := NewIdentityStore(db) diff --git a/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql b/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql index 4cd32da..cc806fa 100644 --- a/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql +++ b/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql @@ -11,3 +11,9 @@ -- No CHECK and no index — the column is read only on the verify-control -- path for the row already loaded by identity_id. ALTER TABLE identities ADD COLUMN subject_aid TEXT; + +-- pending_subject_aid stages the AID a rotation presents; it is +-- promoted to subject_aid only on a successful verify-control, so an +-- abandoned rotation never overwrites the proven signer. Mirrors +-- pending_value. Nullable; NULL for every other kind. +ALTER TABLE identities ADD COLUMN pending_subject_aid TEXT; diff --git a/internal/domain/identity.go b/internal/domain/identity.go index cd67e71..4469472 100644 --- a/internal/domain/identity.go +++ b/internal/domain/identity.go @@ -99,6 +99,10 @@ type VerifiedIdentity struct { // Empty for kinds with no register-time presentation (did:web, // did:key). SubjectAID string + // PendingSubjectAID stages the AID a rotation/registration presents, + // promoted to SubjectAID only by CompleteVerification — an abandoned + // rotation never overwrites the proven signer. Mirrors PendingValue. + PendingSubjectAID string // Challenge is the live anti-replay nonce, if any. Challenge *IdentityChallenge VerifiedAt time.Time // zero until first proof @@ -164,8 +168,7 @@ func InferIdentifierKind(raw string) (IdentifierKind, string, error) { // isLEI reports whether the value is shaped like an ISO 17442 LEI: // exactly 20 alphanumeric characters. (The mod-97 check digit and the -// GLEIF status precondition belong to the lei control verifier, which -// is postponed — this is lexical dispatch only.) +// GLEIF status precondition belong to the lei control verifier) func isLEI(value string) bool { if len(value) != 20 { return false @@ -392,14 +395,25 @@ func (v *VerifiedIdentity) StageRotation(rawValue string, now time.Time) error { return nil } -// SetSubjectAID pins the lei holder AID the verifier derived from the -// presentation (§3.6). Rejects an empty AID — pinning a blank signer -// would let any key satisfy verify-control. -func (v *VerifiedIdentity) SetSubjectAID(aid string, now time.Time) error { +// EffectiveSubjectAID is the lei holder AID the current proof round is +// over: the staged AID during a rotation/registration, else the proven +// one. Mirrors EffectiveValue. +func (v *VerifiedIdentity) EffectiveSubjectAID() string { + if v.PendingSubjectAID != "" { + return v.PendingSubjectAID + } + return v.SubjectAID +} + +// StageSubjectAID stages the lei holder AID the verifier derived from +// the presentation (§3.6); CompleteVerification promotes it to the +// proven SubjectAID. Rejects an empty AID — a blank signer would let +// any key satisfy verify-control. +func (v *VerifiedIdentity) StageSubjectAID(aid string, now time.Time) error { if aid == "" { return NewValidationError("LEI_PRESENTATION_INVALID", "subject AID is required") } - v.SubjectAID = aid + v.PendingSubjectAID = aid v.UpdatedAt = now.UTC() return nil } @@ -432,7 +446,11 @@ func (v *VerifiedIdentity) CompleteVerification(now time.Time) (string, error) { return "", NewInvalidStateError("IDENTITY_INVALID_STATE", fmt.Sprintf("unexpected identity status %s", v.Status)) } + if v.PendingSubjectAID != "" { + v.SubjectAID = v.PendingSubjectAID + } v.PendingValue = "" + v.PendingSubjectAID = "" v.ProofMethod = proofMethodForKind(v.Kind) v.VerifiedAt = now.UTC() v.UpdatedAt = now.UTC() @@ -451,6 +469,7 @@ func (v *VerifiedIdentity) Revoke(now time.Time) error { } v.Status = IdentityRevoked v.PendingValue = "" + v.PendingSubjectAID = "" v.Challenge = nil v.UpdatedAt = now.UTC() return nil diff --git a/internal/domain/identity_test.go b/internal/domain/identity_test.go index a401ed9..f0d46cc 100644 --- a/internal/domain/identity_test.go +++ b/internal/domain/identity_test.go @@ -309,28 +309,40 @@ func TestInferIdentifierKind_DIDWebSegmentRejections(t *testing.T) { } } -func TestSetSubjectAID(t *testing.T) { +func TestStageSubjectAID(t *testing.T) { v := newPendingIdentity(t, "5493001KJTIIGC8Y1R17") // Empty AID is rejected and mutates nothing. - err := v.SetSubjectAID("", idNow) + err := v.StageSubjectAID("", idNow) var domainErr *Error if !errors.As(err, &domainErr) || domainErr.Code != "LEI_PRESENTATION_INVALID" { t.Fatalf("want LEI_PRESENTATION_INVALID, got %v", err) } - if v.SubjectAID != "" { - t.Fatalf("subject AID should remain unset, got %q", v.SubjectAID) + if v.PendingSubjectAID != "" || v.EffectiveSubjectAID() != "" { + t.Fatalf("subject AID should remain unset, got %q", v.EffectiveSubjectAID()) } - // A non-empty AID pins the field and stamps UpdatedAt. + // A non-empty AID stages into PendingSubjectAID (not the proven + // field) and stamps UpdatedAt; EffectiveSubjectAID returns it. later := idNow.Add(time.Minute) - if err := v.SetSubjectAID("EAID123", later); err != nil { - t.Fatalf("SetSubjectAID: %v", err) + if err := v.StageSubjectAID("EAID123", later); err != nil { + t.Fatalf("StageSubjectAID: %v", err) + } + if v.SubjectAID != "" { + t.Fatalf("proven subject AID should stay empty until verify, got %q", v.SubjectAID) } - if v.SubjectAID != "EAID123" { - t.Fatalf("subject AID = %q, want EAID123", v.SubjectAID) + if v.EffectiveSubjectAID() != "EAID123" { + t.Fatalf("effective subject AID = %q, want EAID123", v.EffectiveSubjectAID()) } if !v.UpdatedAt.Equal(later.UTC()) { t.Fatalf("UpdatedAt = %v, want %v", v.UpdatedAt, later.UTC()) } + + // CompleteVerification promotes the staged AID to the proven field. + if _, err := v.CompleteVerification(later); err != nil { + t.Fatalf("CompleteVerification: %v", err) + } + if v.SubjectAID != "EAID123" || v.PendingSubjectAID != "" { + t.Fatalf("after verify: SubjectAID=%q PendingSubjectAID=%q, want EAID123/empty", v.SubjectAID, v.PendingSubjectAID) + } } diff --git a/internal/port/leiverifier.go b/internal/port/leiverifier.go index 21729a8..9c7e31b 100644 --- a/internal/port/leiverifier.go +++ b/internal/port/leiverifier.go @@ -2,6 +2,14 @@ package port import "context" +// PresentationStatus represents the state of a LEI presentation. +type PresentationStatus string + +const ( + StatusAuthorized PresentationStatus = "AUTHORIZED" + StatusPending PresentationStatus = "PENDING" +) + // PresentationResult is what a vLEI presentation yields once the // verifier has parsed the full-chain CESR export: the holder's subject // AID (derived FROM the presentation, never caller-asserted — the @@ -20,7 +28,7 @@ type PresentationResult struct { // LEI is the LEI the presented credential authorizes the AID for. LEI string // Status is "AUTHORIZED" or "PENDING". - Status string + Status PresentationStatus } // AuthorizationResult is the verifier's LIVE view of an AID's vLEI diff --git a/internal/ra/handler/identity.go b/internal/ra/handler/identity.go index bffcc0c..1f0eada 100644 --- a/internal/ra/handler/identity.go +++ b/internal/ra/handler/identity.go @@ -115,6 +115,7 @@ func (h *IdentityHandler) Register(w http.ResponseWriter, r *http.Request) { if !ok { return } + r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB — matches registration.go var req identityRegisterRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { WriteError(w, domain.NewValidationError("INVALID_REQUEST_BODY", "request body is not valid JSON")) @@ -149,6 +150,7 @@ func (h *IdentityHandler) Rotate(w http.ResponseWriter, r *http.Request) { if !ok { return } + r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB — matches registration.go var req identityRegisterRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { WriteError(w, domain.NewValidationError("INVALID_REQUEST_BODY", "request body is not valid JSON")) @@ -174,6 +176,7 @@ func (h *IdentityHandler) VerifyControl(w http.ResponseWriter, r *http.Request) if !ok { return } + r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB — matches registration.go var req verifyControlRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { WriteError(w, domain.NewValidationError("INVALID_REQUEST_BODY", "request body is not valid JSON")) @@ -337,7 +340,7 @@ func toChallengeResponse(res *service.IdentityChallengeResponse) identityChallen Kind: string(res.Identity.Kind), Value: res.Identity.EffectiveValue(), Status: string(res.Identity.Status), - PresentationStatus: res.PresentationStatus, + PresentationStatus: string(res.PresentationStatus), Nonce: res.Nonce, ExpiresAt: res.ExpiresAt.UTC().Format(time.RFC3339), Challenges: challenges, diff --git a/internal/ra/handler/identity_handler_test.go b/internal/ra/handler/identity_handler_test.go index 796c8a2..dbf05fa 100644 --- a/internal/ra/handler/identity_handler_test.go +++ b/internal/ra/handler/identity_handler_test.go @@ -16,6 +16,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -307,6 +308,97 @@ func TestIdentityHandler_AuthAndValidation(t *testing.T) { } } +// TestIdentityHandler_BodyCap pins the 1 MiB MaxBytesReader on the +// three JSON-decoding identity routes: an over-cap body fails the +// decode → 422, never reaching the parser (DoS guard). +func TestIdentityHandler_BodyCap(t *testing.T) { + t.Parallel() + f := newIdentityHTTPFixture(t) + + // Valid JSON envelope padded past 1 MiB inside the cesr field. + oversized := `{"value":"did:web:a.com","vleiPresentation":{"cesr":"` + + strings.Repeat("A", 1<<20) + `"}}` + for _, route := range []struct{ method, path string }{ + {http.MethodPost, "/v2/ans/identities"}, + {http.MethodPut, "/v2/ans/identities/x"}, + {http.MethodPost, "/v2/ans/identities/x/verify-control"}, + } { + if rec := f.doRaw(t, "owner-1", route.method, route.path, oversized); rec.Code != http.StatusUnprocessableEntity { + t.Fatalf("oversized body %s %s: %d", route.method, route.path, rec.Code) + } + } +} + +// TestIdentityHandler_LEIRoundTrip drives the lei lane end-to-end over +// HTTP against the noop verifier and the real SQLite store: register +// with vleiPresentation.cesr → 202 carrying the advisory +// presentationStatus and the subject-AID challenge, then verify-control +// with cesrSignature → 200, and detail reflects the sealed VERIFIED +// state. This exercises the request DTO (vleiPresentation, +// cesrSignature) and response DTO (presentationStatus) wiring plus the +// subject_aid store round-trip the service-only tests cannot reach. +func TestIdentityHandler_LEIRoundTrip(t *testing.T) { + t.Parallel() + f := newIdentityHTTPFixture(t) + owner := "owner-lei" + + // The noop verifier reads the leaf credential's subject AID (a.i) + // and LEI (a.LEI) straight from the full-chain CESR export. + const lei = "5493001KJTIIGC8Y1R17" + const cesr = `{"v":"ACDC10JSON00011c_","d":"ECredSAID123","a":{"i":"EHolderAID123","LEI":"5493001KJTIIGC8Y1R17"}}` + + rec := f.do(t, owner, http.MethodPost, "/v2/ans/identities", + map[string]any{"value": lei, "vleiPresentation": map[string]string{"cesr": cesr}}) + if rec.Code != http.StatusAccepted { + t.Fatalf("register: %d %s", rec.Code, rec.Body) + } + var ch struct { + IdentityID string `json:"identityId"` + Kind string `json:"kind"` + Status string `json:"status"` + PresentationStatus string `json:"presentationStatus"` + Challenges []struct { + Kid string `json:"kid"` + SigningInput string `json:"signingInput"` + } `json:"challenges"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &ch); err != nil { + t.Fatal(err) + } + if ch.Kind != "lei" || ch.Status != "PENDING_CONTROL" || ch.PresentationStatus != "AUTHORIZED" { + t.Fatalf("202 lei shape: %+v", ch) + } + if len(ch.Challenges) != 1 || ch.Challenges[0].Kid != "EHolderAID123" || ch.Challenges[0].SigningInput == "" { + t.Fatalf("challenge over the pinned subject AID: %+v", ch.Challenges) + } + + // verify-control with a well-formed qb64 CESR signature → 200. + rec = f.do(t, owner, http.MethodPost, "/v2/ans/identities/"+ch.IdentityID+"/verify-control", + map[string]any{"cesrSignature": "0BwellFormedQb64Signature"}) + if rec.Code != http.StatusOK { + t.Fatalf("verify-control: %d %s", rec.Code, rec.Body) + } + + // Detail confirms the lei seal landed and the store round-tripped the + // VERIFIED state with the lei proof method. + rec = f.do(t, owner, http.MethodGet, "/v2/ans/identities/"+ch.IdentityID, nil) + if rec.Code != http.StatusOK { + t.Fatalf("detail: %d %s", rec.Code, rec.Body) + } + var detail struct { + Status string `json:"status"` + Kind string `json:"kind"` + Value string `json:"value"` + ProofMethod string `json:"proofMethod"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &detail); err != nil { + t.Fatal(err) + } + if detail.Status != "VERIFIED" || detail.Kind != "lei" || detail.Value != lei || detail.ProofMethod != "lei-vlei-acdc" { + t.Fatalf("verified detail: %+v", detail) + } +} + func TestIdentityHandler_FullLifecycleOverHTTP(t *testing.T) { t.Parallel() f := newIdentityHTTPFixture(t) diff --git a/internal/ra/service/identity.go b/internal/ra/service/identity.go index ecf3736..85882c5 100644 --- a/internal/ra/service/identity.go +++ b/internal/ra/service/identity.go @@ -76,7 +76,7 @@ type IdentityChallengeResponse struct { // with a register-time presentation reports ("AUTHORIZED" | // "PENDING"); empty for kinds without one (did:web, did:key). The // handler emits it on the 202 only when set. - PresentationStatus string + PresentationStatus port.PresentationStatus } // IdentityService owns the Verified Identity lifecycle: register → @@ -349,7 +349,7 @@ func (s *IdentityService) challenge(ctx context.Context, identity *domain.Verifi // their verifier here, pinning the verifier-derived subject AID on // the aggregate before the challenge enumerates it. Discovered by // capability — non-presentation kinds skip this entirely. - var presentationStatus string + var presentationStatus port.PresentationStatus if pr, ok := verifier.(presentationRegistrar); ok { presentationStatus, err = pr.RegisterPresentation(ctx, identity, opt, now) if err != nil { diff --git a/internal/ra/service/identity_lei_test.go b/internal/ra/service/identity_lei_test.go index 4ae8e6e..12c6dd7 100644 --- a/internal/ra/service/identity_lei_test.go +++ b/internal/ra/service/identity_lei_test.go @@ -129,6 +129,78 @@ func sha256Sum(s string) []byte { return sum[:] } +// TestIdentityRotate_LEI drives the lei rotation path: a VERIFIED lei +// identity re-presents through Rotate, which re-runs RegisterPresentation +// and stages the verifier-derived subject AID. The H1 invariant is that +// the PUT stages the new AID into PendingSubjectAID and seals nothing — +// the proven SubjectAID stands until verify-control completes — so an +// abandoned rotation can never swap the proven signer out from under the +// identity. verify-control then promotes the staged AID and seals +// IDENTITY_UPDATED over it. +func TestIdentityRotate_LEI(t *testing.T) { + t.Parallel() + fake := authorizedFakeLEI() + fx := newIdentityFixtureWithLEI(t, nil, fake) + ctx := context.Background() + + // Register + verify → VERIFIED, proven subject AID EHolderAID. + res, err := fx.svc.Register(ctx, fx.providerID, testLEI, + service.RegisterOptions{VLEIPresentation: "chain-v1"}) + if err != nil { + t.Fatalf("register: %v", err) + } + if _, err := fx.svc.VerifyControl(ctx, fx.providerID, res.Identity.IdentityID, + service.ProofSubmission{CESRSignature: "0Bsig-v1"}); err != nil { + t.Fatalf("verify-control: %v", err) + } + fx.drainSealed(t) + + // The rotation re-presents the SAME LEI, but the verifier now derives + // a new holder AID (a re-presented credential). + fake.present = port.PresentationResult{SubjectAID: "ERotatedAID", LEI: testLEI, Status: "AUTHORIZED"} + rot, err := fx.svc.Rotate(ctx, fx.providerID, res.Identity.IdentityID, testLEI, + service.RegisterOptions{VLEIPresentation: "chain-v2"}) + if err != nil { + t.Fatalf("rotate: %v", err) + } + + // H1: the proven AID stands, the new AID is only staged, the + // challenge is over the staged AID, and the PUT seals nothing. + if rot.Identity.Status != domain.IdentityVerified { + t.Fatalf("status after PUT = %s, want VERIFIED", rot.Identity.Status) + } + if rot.Identity.SubjectAID != "EHolderAID" || rot.Identity.PendingSubjectAID != "ERotatedAID" { + t.Fatalf("staged AID state: proven=%q pending=%q", rot.Identity.SubjectAID, rot.Identity.PendingSubjectAID) + } + if len(rot.Challenges) != 1 || rot.Challenges[0].Kid != "ERotatedAID" { + t.Fatalf("challenge must be over the staged AID: %+v", rot.Challenges) + } + if rows := fx.drainSealed(t); len(rows) != 0 { + t.Fatalf("PUT must not seal, got %d rows", len(rows)) + } + + // verify-control over the rotation promotes the staged AID and seals + // IDENTITY_UPDATED — value unchanged (same LEI), so no previousValue. + rotated, err := fx.svc.VerifyControl(ctx, fx.providerID, res.Identity.IdentityID, + service.ProofSubmission{CESRSignature: "0Bsig-v2"}) + if err != nil { + t.Fatalf("rotation verify-control: %v", err) + } + if rotated.SubjectAID != "ERotatedAID" || rotated.PendingSubjectAID != "" { + t.Fatalf("promoted AID state: proven=%q pending=%q", rotated.SubjectAID, rotated.PendingSubjectAID) + } + + rows := fx.drainSealed(t) + if len(rows) != 1 { + t.Fatalf("rotation rows: %d", len(rows)) + } + inner := fx.decodeSealed(t, rows[0]) + if inner.EventType != identityevent.TypeIdentityUpdated || len(inner.Keys) != 1 || + inner.Keys[0].ID() != "ERotatedAID" { + t.Fatalf("IDENTITY_UPDATED over rotated AID: %+v", inner) + } +} + func TestIdentityRegister_LEIFailures(t *testing.T) { t.Parallel() ctx := context.Background() diff --git a/internal/ra/service/identitykinds.go b/internal/ra/service/identitykinds.go index 45de40c..73fa87f 100644 --- a/internal/ra/service/identitykinds.go +++ b/internal/ra/service/identitykinds.go @@ -91,13 +91,29 @@ type RegisterOptions struct { // method. RegisterPresentation runs inside the shared challenge path, // so an idempotent re-add (and a rotation) re-presents and refreshes // the verifier's authorization window for free. +// +// RACE INVARIANT: RegisterPresentation runs BEFORE challenge() captures +// the conditional-persist snapshot (identity.go:360), and is itself a +// slow network call. The snapshot reads the in-memory load-time Status +// and Challenge.Nonce, and the store's StageChallenge refuses the write +// unless the row still matches them — so the conditional persist only +// brackets the presentation fetch (a concurrent verify/revoke during it +// → 0 rows → conflict, never a clobber) AS LONG AS RegisterPresentation +// does NOT mutate Status or Challenge.Nonce. It may pin kind-specific +// state (lei: PendingSubjectAID) and bump UpdatedAt; it must touch neither +// guard column. Mutating Status here would make the snapshot reflect a +// post-presentation value, opening exactly the status-regression race +// (VERIFIED → PENDING_CONTROL) the conditional persist exists to close. +// See docs/identity-challenge-race.md. type presentationRegistrar interface { // RegisterPresentation submits the kind's register-time credential // material to its verifier, pins the derived subject identifier on // the aggregate, reconciles it against the requested value, and // returns the advisory presentation status ("AUTHORIZED" | - // "PENDING") for the 202 body. - RegisterPresentation(ctx context.Context, identity *domain.VerifiedIdentity, opts RegisterOptions, now time.Time) (string, error) + // "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) } // controlVerifier is the per-kind control-proof gate — the design's diff --git a/internal/ra/service/leiverifier.go b/internal/ra/service/leiverifier.go index f7b2ffb..a7af674 100644 --- a/internal/ra/service/leiverifier.go +++ b/internal/ra/service/leiverifier.go @@ -46,7 +46,7 @@ func (lv *leiVerifier) RegisterPresentation( identity *domain.VerifiedIdentity, opts RegisterOptions, now time.Time, -) (string, error) { +) (port.PresentationStatus, error) { if opts.VLEIPresentation == "" { return "", domain.NewValidationError("IDENTIFIER_PRESENTATION_REQUIRED", "lei registration requires vleiPresentation.cesr") @@ -67,7 +67,7 @@ func (lv *leiVerifier) RegisterPresentation( return "", domain.NewValidationError("LEI_MISMATCH", fmt.Sprintf("presented credential authorizes LEI %q, not %q", res.LEI, identity.EffectiveValue())) } - if err := identity.SetSubjectAID(res.SubjectAID, now); err != nil { + if err := identity.StageSubjectAID(res.SubjectAID, now); err != nil { return "", err } return res.Status, nil @@ -82,11 +82,12 @@ func (lv *leiVerifier) Challenges( identity *domain.VerifiedIdentity, signingInput string, ) ([]ProofChallenge, error) { - if identity.SubjectAID == "" { + aid := identity.EffectiveSubjectAID() + if aid == "" { return nil, domain.NewInternalError("LEI_SUBJECT_AID_MISSING", "subject AID was not pinned before challenge", nil) } - return []ProofChallenge{{Kid: identity.SubjectAID, SigningInput: signingInput}}, nil + return []ProofChallenge{{Kid: aid, SigningInput: signingInput}}, nil } // VerifyProofs runs the lei control proof: a LIVE authorization @@ -103,7 +104,7 @@ func (lv *leiVerifier) VerifyProofs( if sub.CESRSignature == "" { return nil, domain.NewValidationError("IDENTIFIER_PROOF_INVALID", "cesrSignature is required") } - aid := identity.SubjectAID + aid := identity.EffectiveSubjectAID() if aid == "" { return nil, domain.NewInvalidStateError("LEI_SUBJECT_AID_MISSING", "no subject AID is pinned; re-register the identifier with its presentation") diff --git a/scripts/demo/vlei/docker-compose.yml b/scripts/demo/vlei/docker-compose.yml index 019456d..2263820 100644 --- a/scripts/demo/vlei/docker-compose.yml +++ b/scripts/demo/vlei/docker-compose.yml @@ -54,9 +54,9 @@ services: - witness - demo ports: - - "5642:5642" - - "5643:5643" - - "5644:5644" + - "127.0.0.1:5642:5642" + - "127.0.0.1:5643:5643" + - "127.0.0.1:5644:5644" # weboftrust/keri ships no curl; use the bundled python3 to probe the # witness HTTP endpoint (127.0.0.1 to avoid IPv6-localhost refusal). healthcheck: @@ -77,7 +77,7 @@ services: # OOBI resolution — gleif/vlei:1.0.0 ships schemas under /vLEI/schema, and # the verifier's durls fail to parse an empty body if they're not served. ports: - - "7723:7723" + - "127.0.0.1:7723:7723" healthcheck: test: ["CMD", "curl", "-f", "http://localhost:7723/health"] interval: 5s @@ -114,9 +114,9 @@ services: - --loglevel - DEBUG ports: - - "3901:3901" - - "3902:3902" - - "3903:3903" + - "127.0.0.1:3901:3901" + - "127.0.0.1:3902:3902" + - "127.0.0.1:3903:3903" depends_on: witnesses: condition: service_healthy @@ -145,7 +145,7 @@ services: - VERIFIER_CONFIG_FILE=verifier-config-docker-local.json - PYTHONUNBUFFERED=1 ports: - - "7676:7676" + - "127.0.0.1:7676:7676" depends_on: witnesses: condition: service_healthy diff --git a/scripts/demo/vlei/signify/scripts_ts/utils.ts b/scripts/demo/vlei/signify/scripts_ts/utils.ts index 51dd866..2802ddf 100644 --- a/scripts/demo/vlei/signify/scripts_ts/utils.ts +++ b/scripts/demo/vlei/signify/scripts_ts/utils.ts @@ -95,7 +95,7 @@ export async function initializeAndConnectClient( tier: Tier = Tier.low ): Promise<{ client: SignifyClient;clientState: State }> { - console.log(`Using Passcode (bran): ${bran}`); + console.log('Connecting client with provided passcode (bran) [redacted].'); const client = new SignifyClient(adminUrl, bran, tier, bootUrl); diff --git a/spec/api-spec-v2.yaml b/spec/api-spec-v2.yaml index 90d48a2..4288e61 100644 --- a/spec/api-spec-v2.yaml +++ b/spec/api-spec-v2.yaml @@ -1096,6 +1096,12 @@ paths: closed. The nonce is consumed exactly once, inside the success transaction — a failed attempt does not consume it. + The `lei` kind instead submits a single `cesrSignature` over + the same `signingInput`: the RA forwards it to the + vlei-verifier, which live-rechecks the subject AID's + authorization and verifies the signature against its current + KEL key state. + JWS bearing unrecognized `crit` header parameters are rejected (RFC 7515 §4.1.11) — this verifier implements no critical extensions. @@ -1155,14 +1161,14 @@ paths: description: | Proof rejected — `PRICC_SIGNATURE_INVALID`, `DID_VERIFICATION_METHOD_INVALID`, `DID_RESOLUTION_FAILED`, - `DID_DOCUMENT_ID_MISMATCH`, `IDENTIFIER_PROOF_INVALID`. + `DID_DOCUMENT_ID_MISMATCH`, `IDENTIFIER_PROOF_INVALID`, `LEI_NOT_AUTHORIZED`, `LEI_MISMATCH`. content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '503': - description: Transparency Log unavailable (TL_UNAVAILABLE — retryable; the nonce is NOT consumed) + description: Upstream unavailable (TL_UNAVAILABLE, or LEI_VERIFIER_UNAVAILABLE — retryable; the nonce is NOT consumed) content: application/json: schema: @@ -2111,15 +2117,6 @@ components: description: The canonical identifier this round proves status: $ref: '#/components/schemas/IdentityLifecycleStatus' - presentationStatus: - type: string - description: | - The lei register-time advisory authorization status from - the vlei-verifier (`AUTHORIZED` | `PENDING`). Omitted for - kinds with no register-time presentation (`did:web`, - `did:key`). Advisory only — control is finally established - by a LIVE re-authorization at verify-control. - enum: ['AUTHORIZED', 'PENDING'] nonce: type: string description: Base64url 32-byte single-use anti-replay nonce @@ -2130,6 +2127,15 @@ components: type: array items: $ref: '#/components/schemas/IdentityProofChallenge' + presentationStatus: + type: string + enum: [AUTHORIZED, PENDING] + description: | + The lei register-time advisory authorization status from + the vlei-verifier (`AUTHORIZED` | `PENDING`). Omitted for + kinds with no register-time presentation (`did:web`, + `did:key`). Advisory only — control is finally established + by a LIVE re-authorization at verify-control. required: - identityId - kind From 41ad74f9e5b6864b4137fafd623dec29a4bfa7c2 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Wed, 17 Jun 2026 16:43:40 +1000 Subject: [PATCH 10/21] fix(demo): co-pilot review feedback Signed-off-by: James Hateley --- .../vlei/signify/scripts_ts/build-chain.ts | 10 ++-- .../vlei/signify/scripts_ts/sign-proof.ts | 7 ++- scripts/demo/vlei/signify/scripts_ts/utils.ts | 46 +++++++++---------- 3 files changed, 32 insertions(+), 31 deletions(-) diff --git a/scripts/demo/vlei/signify/scripts_ts/build-chain.ts b/scripts/demo/vlei/signify/scripts_ts/build-chain.ts index 803cf27..f3420ec 100644 --- a/scripts/demo/vlei/signify/scripts_ts/build-chain.ts +++ b/scripts/demo/vlei/signify/scripts_ts/build-chain.ts @@ -20,7 +20,7 @@ // ============================================================================ import "npm:libsodium-wrappers-sumo@0.7.15"; -import { randomPasscode, Saider } from "npm:signify-ts@^0.3.0-rc1"; +import { randomPasscode, Saider, SignifyClient } from "npm:signify-ts@0.3.0-rc1"; import { initializeSignify, initializeAndConnectClient, @@ -54,7 +54,7 @@ const WITNESS_OOBIS = [ { url: "http://witness-demo:5644/oobi/BIKKuvBwpmDVA4Ds-EpL5bt9OqPzWPja2LigFYZN2YfX/controller?name=wes&tag=witness", alias: "wes" }, ]; -async function resolveWitnesses(client, who: string) { +async function resolveWitnesses(client: SignifyClient, who: string) { for (const w of WITNESS_OOBIS) { await resolveOOBI(client, w.url, `${who}-${w.alias}`); } @@ -132,7 +132,7 @@ let approved = false; for (let attempt = 1; attempt <= 10 && !approved; attempt++) { try { const gleifApproval = await gleifClient.delegations().approve(gleifAlias, delegationSeal); - await gleifClient.operations().wait(await gleifApproval.op(), AbortSignal.timeout(30000)); + await gleifClient.operations().wait(await gleifApproval.op(), { signal: AbortSignal.timeout(30000) }); approved = true; } catch (_e) { prMessage(`Waiting for qvi's dip to reach gleif's delegation escrow (attempt ${attempt})...`); @@ -143,8 +143,8 @@ if (!approved) throw new Error("gleif failed to approve qvi's delegated inceptio // 3. qvi pulls gleif's anchoring event, then its delegated inception completes. const qviQueryOp = await qviClient.keyStates().query(gleifPrefix); -await qviClient.operations().wait(qviQueryOp, AbortSignal.timeout(60000)); -await qviClient.operations().wait(qviIcpOp, AbortSignal.timeout(60000)); +await qviClient.operations().wait(qviQueryOp, { signal: AbortSignal.timeout(60000) }); +await qviClient.operations().wait(qviIcpOp, { signal: AbortSignal.timeout(60000) }); await qviClient.operations().delete(qviIcpOp.name); await addEndRoleForAID(qviClient, qviAlias, ROLE_AGENT); diff --git a/scripts/demo/vlei/signify/scripts_ts/sign-proof.ts b/scripts/demo/vlei/signify/scripts_ts/sign-proof.ts index f2bcec7..aa16535 100644 --- a/scripts/demo/vlei/signify/scripts_ts/sign-proof.ts +++ b/scripts/demo/vlei/signify/scripts_ts/sign-proof.ts @@ -34,9 +34,14 @@ // rejected as SIGNATURE_INVALID. // ============================================================================ +// Pin libsodium-wrappers-sumo to 0.7.15 BEFORE signify-ts (must be the first +// import). signify-ts's range otherwise resolves 0.7.16, whose ESM packaging +// Deno cannot resolve (ERR_MODULE_NOT_FOUND on libsodium-sumo.mjs). Mirrors +// build-chain.ts so both scripts and the compose pre-cache agree. +import "npm:libsodium-wrappers-sumo@0.7.15"; // Pinned to match build-chain.ts so both scripts (and the compose pre-cache) // resolve the same signify-ts the holder's KERIA agent was created with. -import { ready, SignifyClient, Tier } from "npm:signify-ts@^0.3.0-rc1"; +import { ready, SignifyClient, Tier } from "npm:signify-ts@0.3.0-rc1"; import { DEFAULT_ADMIN_URL, DEFAULT_BOOT_URL } from "./utils.ts"; const ROLE_ALIAS = "role"; diff --git a/scripts/demo/vlei/signify/scripts_ts/utils.ts b/scripts/demo/vlei/signify/scripts_ts/utils.ts index 2802ddf..cd7b231 100644 --- a/scripts/demo/vlei/signify/scripts_ts/utils.ts +++ b/scripts/demo/vlei/signify/scripts_ts/utils.ts @@ -8,7 +8,7 @@ import { Contact, Salter, Serder -} from 'npm:signify-ts'; +} from 'npm:signify-ts@0.3.0-rc1'; class Ansi { // Text Colors @@ -109,7 +109,7 @@ export async function initializeAndConnectClient( console.log(' Client AID Prefix: ', clientState?.controller?.state?.i); console.log(' Agent AID Prefix: ', clientState?.agent?.i); - return { client, clientState }; + return { client, clientState: clientState as unknown as State }; } catch (error) { console.error('Failed to initialize or connect client:', error); throw error; @@ -122,13 +122,13 @@ export async function initializeAndConnectClient( * @param {SignifyClient} client - The initialized SignifyClient. * @param {string} alias - A human-readable alias for the AID. * @param {CreateIdentiferArgs} [identifierArgs=DEFAULT_IDENTIFIER_ARGS] - Configuration for the new AID. - * @returns {Promise<{ aid: any; operation: Operation }>} The created AID's inception event and the operation details. + * @returns {Promise<{ aid: any; operation: Operation }>} The created AID's inception event and the operation details. */ export async function createNewAID( client: SignifyClient, alias: string, identifierArgs: CreateIdentiferArgs = DEFAULT_IDENTIFIER_ARGS -): Promise<{ aid: any; operation: Operation }> { +): Promise<{ aid: any; operation: Operation }> { console.log(`Initiating AID inception for alias: ${alias}`); try { const inceptionResult = await client.identifiers().create(alias, identifierArgs as any); @@ -136,13 +136,13 @@ export async function createNewAID( const completedOperation = await client .operations() - .wait(operationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + .wait(operationDetails, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); if (completedOperation.error) { throw new Error(`AID creation failed: ${JSON.stringify(completedOperation.error)}`); } - const newAidInceptionEvent = completedOperation.response; + const newAidInceptionEvent = completedOperation.response as any; console.log(`Successfully created AID with prefix: ${newAidInceptionEvent?.i}`); await client.operations().delete(completedOperation.name); @@ -157,13 +157,13 @@ export async function createNewAID( /** * Assigns an end role for a given AID to the client's KERIA Agent AID. * - * @returns {Promise<{ operation: Operation }>} The operation details. + * @returns {Promise<{ operation: Operation }>} The operation details. */ export async function addEndRoleForAID( client: SignifyClient, aidAlias: string, role: string -): Promise<{ operation: Operation }> { +): Promise<{ operation: Operation }> { if (!client.agent?.pre) { throw new Error('Client agent prefix is not available.'); } @@ -179,7 +179,7 @@ export async function addEndRoleForAID( const completedOperation = await client .operations() - .wait(operationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + .wait(operationDetails, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); console.log(`Successfully assigned '${role}' role for AID alias ${aidAlias}.`); @@ -221,19 +221,19 @@ export async function generateOOBI( /** * Resolves an OOBI URL * - * @returns {Promise<{ operation: Operation; contacts?: Contact[] }>} The operation details and the resolved contact. + * @returns {Promise<{ operation: Operation; contacts?: Contact[] }>} The operation details and the resolved contact. */ export async function resolveOOBI( client: SignifyClient, oobiUrl: string, contactAlias?: string -): Promise<{ operation: Operation; contacts?: Contact[] }> { +): Promise<{ operation: Operation; contacts?: Contact[] }> { console.log(`Resolving OOBI URL: ${oobiUrl} with alias ${contactAlias}`); try { const resolveOperationDetails = await client.oobis().resolve(oobiUrl, contactAlias); const completedOperation = await client .operations() - .wait(resolveOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + .wait(resolveOperationDetails, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); if (completedOperation.error) { throw new Error(`OOBI resolution failed: ${JSON.stringify(completedOperation.error)}`); @@ -250,7 +250,7 @@ export async function resolveOOBI( await client.operations().delete(completedOperation.name); - return { operation: completedOperation, contact: contact }; + return { operation: completedOperation, contacts: contact }; } catch (error) { console.error(`Failed to resolve OOBI URL "${oobiUrl}":`, error); throw error; @@ -282,13 +282,13 @@ export async function createCredentialRegistry( const operationDetails = await createRegistryResult.op(); const completedOperation = await client .operations() - .wait(operationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + .wait(operationDetails, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); if (completedOperation.error) { throw new Error(`Credential registry creation failed: ${JSON.stringify(completedOperation.error)}`); } - const registrySaid = completedOperation?.response?.anchor?.i; + const registrySaid = (completedOperation?.response as any)?.anchor?.i; console.log(`Successfully created credential registry: ${registrySaid}`); await client.operations().delete(completedOperation.name); @@ -341,13 +341,13 @@ export async function issueCredential( const operationDetails = await issueResult.op; const completedOperation = await client .operations() - .wait(operationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + .wait(operationDetails, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); if (completedOperation.error) { throw new Error(`Credential issuance failed: ${JSON.stringify(completedOperation.error)}`); } console.log(completedOperation) // ************ - const credentialSad = completedOperation.response; // The full Self-Addressing Data (SAD) of the credential + const credentialSad = completedOperation.response as any; // The full Self-Addressing Data (SAD) of the credential const credentialSaid = credentialSad?.ced?.d; // The SAID of the credential console.log(`Successfully issued credential with SAID: ${credentialSaid}`); @@ -392,7 +392,7 @@ export async function ipexGrantCredential( const completedOperation = await client .operations() - .wait(submitGrantOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + .wait(submitGrantOperationDetails, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); if (completedOperation.error) { throw new Error(`IPEX grant submission failed: ${JSON.stringify(completedOperation.error)}`); @@ -411,15 +411,11 @@ export async function ipexGrantCredential( * Waits for and retrieves a specific notification. * @param {SignifyClient} client - The SignifyClient instance. * @param {string} expectedRoute - The expected route in the notification attributes (e.g., IPEX_GRANT_ROUTE). - * @param {number} [retries=DEFAULT_RETRIES] - Number of retry attempts. - * @param {number} [delayMs=DEFAULT_DELAY_MS] - Delay between retries in milliseconds. * @returns {Promise} The first matching unread notification. */ export async function waitForAndGetNotification( client: SignifyClient, - expectedRoute: string, - retries: number = DEFAULT_RETRIES, - delayMs: number = DEFAULT_DELAY_MS + expectedRoute: string ): Promise { console.log(`Waiting for notification with route "${expectedRoute}"...`); @@ -431,7 +427,7 @@ export async function waitForAndGetNotification( // List notifications, filtering for unread IPEX_GRANT_ROUTE messages. let allNotifications = await client.notifications().list() notifications = allNotifications.notes.filter( - (n) => n.a.r === expectedRoute && n.r === false // n.r is 'read' status + (n: any) => n.a.r === expectedRoute && n.r === false // n.r is 'read' status ); if(notifications.length === 0){ throw new Error("Notification not found yet."); // Throw error to trigger retry @@ -482,7 +478,7 @@ export async function ipexAdmitGrant( const completedOperation = await client .operations() - .wait(admitOperationDetails, AbortSignal.timeout(DEFAULT_TIMEOUT_MS)); + .wait(admitOperationDetails, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); if (completedOperation.error) { throw new Error(`IPEX admit submission failed: ${JSON.stringify(completedOperation.error)}`); From 1e326027bac9bad1481e152c3f0330ac8ef3d1cf Mon Sep 17 00:00:00 2001 From: James Hateley Date: Fri, 19 Jun 2026 11:44:10 +1000 Subject: [PATCH 11/21] feat(identity): enforce verify-control oneOf proof-family contract MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- config/ra-local.yaml | 8 ++--- internal/ra/service/identity.go | 7 ++++ internal/ra/service/identity_test.go | 33 +++++++++++++++++++ internal/ra/service/identitykinds.go | 14 ++++++++ scripts/demo/vlei/README.md | 5 +-- scripts/demo/vlei/signify/scripts_ts/utils.ts | 1 - 6 files changed, 61 insertions(+), 7 deletions(-) diff --git a/config/ra-local.yaml b/config/ra-local.yaml index 897c99e..ebae721 100644 --- a/config/ra-local.yaml +++ b/config/ra-local.yaml @@ -80,10 +80,10 @@ identity: vlei: # The lei (vLEI) control verifier behind the `lei` identifier kind, # mirroring the DNS verifier's and did:web resolver's noop/real split: - # "noop" — no I/O; runs REAL Ed25519 crypto over the served - # signingInput, but waives the GLEIF/vlei-verifier - # authorization binding (anyone can present any LEI). - # Zero-infra quickstart only — NOT for production. + # "noop" — no I/O; accepts the same CESR presentation payload but + # performs structural qb64 checks only and waives the + # vlei-verifier authorization + cryptographic signature checks + # (zero-infra quickstart only — NOT for production). # "verifier" — a hardened HTTP client for an internal GLEIF # vlei-verifier (present / authorize / verify). The RA # never parses KERI key state itself; the verifier is diff --git a/internal/ra/service/identity.go b/internal/ra/service/identity.go index 85882c5..b0590ed 100644 --- a/internal/ra/service/identity.go +++ b/internal/ra/service/identity.go @@ -431,6 +431,13 @@ func (s *IdentityService) VerifyControl(ctx context.Context, providerID, identit if err := identity.CheckChallenge(now); err != nil { return nil, err } + // Enforce the wire oneOf contract before kind dispatch: exactly one + // proof family per request. Each per-kind verifier validates only + // its own member, so a body carrying both families would otherwise + // slip through silently. Kind-independent, hence here above dispatch. + if err := sub.validateExactlyOneFamily(); err != nil { + return nil, err + } verifier, err := s.verifierFor(identity.Kind) if err != nil { return nil, err diff --git a/internal/ra/service/identity_test.go b/internal/ra/service/identity_test.go index ad69da3..6ea24cc 100644 --- a/internal/ra/service/identity_test.go +++ b/internal/ra/service/identity_test.go @@ -511,6 +511,39 @@ func TestIdentityVerifyControl_FailClosed(t *testing.T) { } } +// TestIdentityVerifyControl_BothProofFamilies covers the wire oneOf +// contract: a body that sets BOTH signedProofs and cesrSignature is +// rejected, not silently accepted on the JWS member alone. The +// neither-set case is covered by the "no proofs" row in FailClosed. +func TestIdentityVerifyControl_BothProofFamilies(t *testing.T) { + t.Parallel() + fx := newIdentityFixture(t, nil) + ctx := context.Background() + + res, err := fx.svc.Register(ctx, fx.providerID, "did:web:a.com") + if err != nil { + t.Fatal(err) + } + id := res.Identity.IdentityID + did := res.Identity.Value + good := signProof(t, genKey(t), did+"#key-1", res.Challenges[0].SigningInput, true) + + _, err = fx.svc.VerifyControl(ctx, fx.providerID, id, service.ProofSubmission{ + SignedProofs: []string{good}, + CESRSignature: "0Bcesr-signature-bytes", + }) + if err == nil || !strings.Contains(err.Error(), "IDENTIFIER_PROOF_INVALID") { + t.Fatalf("want IDENTIFIER_PROOF_INVALID, got %v", err) + } + + // The rejected attempt must not consume the nonce — the clean + // single-family proof still lands afterward. + if _, err := fx.svc.VerifyControl(ctx, fx.providerID, id, + service.ProofSubmission{SignedProofs: []string{good}}); err != nil { + t.Fatalf("clean proof after both-families rejection: %v", err) + } +} + func TestIdentityVerifyControl_WrongSignature(t *testing.T) { t.Parallel() fx := newIdentityFixture(t, nil) diff --git a/internal/ra/service/identitykinds.go b/internal/ra/service/identitykinds.go index 73fa87f..7327fb1 100644 --- a/internal/ra/service/identitykinds.go +++ b/internal/ra/service/identitykinds.go @@ -69,6 +69,20 @@ type ProofSubmission struct { CESRSignature string } +// validateExactlyOneFamily enforces the wire oneOf contract declared +// by VerifyControlRequest in spec/api-spec-v2.yaml: EXACTLY ONE proof +// family is set per request (JWS kinds → signedProofs; lei → +// cesrSignature). +func (s ProofSubmission) validateExactlyOneFamily() error { + hasJWS := len(s.SignedProofs) > 0 + hasCESR := s.CESRSignature != "" + if hasJWS == hasCESR { + return domain.NewValidationError("IDENTIFIER_PROOF_INVALID", + "exactly one of signedProofs or cesrSignature must be set") + } + return nil +} + // RegisterOptions carries the additive, per-kind material a register // (or rotate) call may need beyond the identifier value. It is empty // for kinds with no register-time presentation (did:web, did:key); diff --git a/scripts/demo/vlei/README.md b/scripts/demo/vlei/README.md index 06209d2..9d1d95d 100644 --- a/scripts/demo/vlei/README.md +++ b/scripts/demo/vlei/README.md @@ -73,8 +73,9 @@ the stack, builds the chain, and runs the register + verify-control flow. Re-running is safe: a running RA and a previously-registered agent are reused. **Why "mode" matters.** `vlei.type` selects the `lei` control verifier: `noop` -runs real Ed25519 crypto but waives the GLEIF authorization binding (zero-infra -quickstart); `verifier` routes every CESR/KERI question to this stack's +performs structural qb64 checks only and waives the GLEIF authorization + +cryptographic signature verification (zero-infra quickstart); +`verifier` routes every CESR/KERI question to this stack's `vlei-verifier`. This demo presents **real CESR**, which only `verifier` accepts. So `run-vlei.sh` guarantees verifier mode — starting the RA in it if down, or restarting via `stop.sh` + `start.sh --keep` (preserves the registered diff --git a/scripts/demo/vlei/signify/scripts_ts/utils.ts b/scripts/demo/vlei/signify/scripts_ts/utils.ts index cd7b231..b45a21b 100644 --- a/scripts/demo/vlei/signify/scripts_ts/utils.ts +++ b/scripts/demo/vlei/signify/scripts_ts/utils.ts @@ -346,7 +346,6 @@ export async function issueCredential( if (completedOperation.error) { throw new Error(`Credential issuance failed: ${JSON.stringify(completedOperation.error)}`); } - console.log(completedOperation) // ************ const credentialSad = completedOperation.response as any; // The full Self-Addressing Data (SAD) of the credential const credentialSaid = credentialSad?.ced?.d; // The SAID of the credential console.log(`Successfully issued credential with SAID: ${credentialSaid}`); From 45d9a2052f9e51da44ca55f766c92fa8c5f7fbc5 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Fri, 19 Jun 2026 14:06:08 +1000 Subject: [PATCH 12/21] feat(leiverifier): log operational verifier failures 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 --- cmd/ans-ra/main.go | 6 +-- .../adapter/leiverifier/leiverifier_test.go | 31 +++++++++++++ internal/adapter/leiverifier/verifier.go | 46 +++++++++++++++++++ 3 files changed, 80 insertions(+), 3 deletions(-) diff --git a/cmd/ans-ra/main.go b/cmd/ans-ra/main.go index 6377435..65b94a6 100644 --- a/cmd/ans-ra/main.go +++ b/cmd/ans-ra/main.go @@ -157,7 +157,7 @@ func run(cfgPath string) error { // vLEI control verifier — noop (quickstart) or HTTP client for an internal vlei-verifier, // the lei kind's analog of // the did:web resolver selection. - leiVerifier := selectLEIVerifier(cfg) + leiVerifier := selectLEIVerifier(cfg, logger) logger.Info(). Str("resolver", cfg.Identity.Resolver.Type). Str("vleiVerifier", cfg.VLEI.Type). @@ -532,10 +532,10 @@ func selectDIDResolver(cfg *config.RAConfig, logger zerolog.Logger) port.DIDReso // URL); the default "noop" performs structural-only qb64 checks and // waives both the GLEIF authorization binding and the cryptographic // signature check -func selectLEIVerifier(cfg *config.RAConfig) port.LEIControlVerifier { +func selectLEIVerifier(cfg *config.RAConfig, logger zerolog.Logger) port.LEIControlVerifier { switch cfg.VLEI.Type { case "verifier": - var opts []leiverifier.VerifierOption + opts := []leiverifier.VerifierOption{leiverifier.WithLogger(logger)} if cfg.VLEI.PresentTimeout > 0 { opts = append(opts, leiverifier.WithTimeout(cfg.VLEI.PresentTimeout)) } diff --git a/internal/adapter/leiverifier/leiverifier_test.go b/internal/adapter/leiverifier/leiverifier_test.go index 0fa2ef5..b1af2f0 100644 --- a/internal/adapter/leiverifier/leiverifier_test.go +++ b/internal/adapter/leiverifier/leiverifier_test.go @@ -1,6 +1,7 @@ package leiverifier import ( + "bytes" "context" "encoding/json" "errors" @@ -10,6 +11,8 @@ import ( "testing" "time" + "github.com/rs/zerolog" + "github.com/godaddy/ans/internal/domain" ) @@ -381,6 +384,34 @@ func TestCollectEdgeNodesDepthBound(t *testing.T) { } } +// TestVerifierLogsOperationalFailure pins the coarse-wire / detailed-log +// split (the did:web resolver's WithLogger precedent): an operational +// verifier failure surfaces the deliberately coarse LEI_VERIFIER_UNAVAILABLE +// wire error, which never names the configured host, while the diagnosable +// category — operation and HTTP status — goes only to the server-side log. +func TestVerifierLogsOperationalFailure(t *testing.T) { + var logbuf bytes.Buffer + srv := httptest.NewServer((&vleiServer{authStatus: http.StatusBadGateway}).handler()) + t.Cleanup(srv.Close) + v := NewVerifier(srv.URL, WithHTTPClient(srv.Client()), WithLogger(zerolog.New(&logbuf))) + + _, err := v.Authorization(context.Background(), "EAID") + if !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) + } + // The wire error never echoes the configured host (no topology leak). + if strings.Contains(err.Error(), "127.") || strings.Contains(err.Error(), srv.URL) { + t.Fatalf("wire error leaked the verifier host: %v", err) + } + // The diagnosable category reaches only the log. + out := logbuf.String() + if !strings.Contains(out, "vlei verifier call failed") || + !strings.Contains(out, `"op":"authorize"`) || + !strings.Contains(out, `"status":502`) { + t.Fatalf("log did not record the failure category: %q", out) + } +} + func isCode(err error, code string) bool { var de *domain.Error return errors.As(err, &de) && de.Code == code diff --git a/internal/adapter/leiverifier/verifier.go b/internal/adapter/leiverifier/verifier.go index 0f3ac68..6538405 100644 --- a/internal/adapter/leiverifier/verifier.go +++ b/internal/adapter/leiverifier/verifier.go @@ -11,6 +11,8 @@ import ( "strings" "time" + "github.com/rs/zerolog" + "github.com/godaddy/ans/internal/domain" "github.com/godaddy/ans/internal/port" ) @@ -47,6 +49,7 @@ type Verifier struct { baseURL string client *http.Client maxBodyBytes int64 + logger zerolog.Logger } // VerifierOption customizes the Verifier. @@ -80,6 +83,22 @@ func WithMaxBodyBytes(n int64) VerifierOption { } } +// WithLogger attaches a server-side logger (default: no-op). It records +// the failure CATEGORY behind a verifier I/O or protocol failure — the +// operation, an unexpected HTTP status, the underlying transport error, +// an oversized body, a 2xx body that failed to decode (the fail-closed +// degradation), or a contract violation (a 2xx with no subject AID) — so +// an on-call engineer can tell an internal vlei-verifier outage from a +// 5xx from a malformed response. None of this reaches the API caller: the +// wire error (unavailable) stays deliberately coarse and never names the +// configured host (no internal-topology leak). This mirrors the did:web +// resolver's coarse-wire / detailed-log split. +func WithLogger(logger zerolog.Logger) VerifierOption { + return func(v *Verifier) { + v.logger = logger.With().Str("component", "vlei-verifier").Logger() + } +} + // NewVerifier constructs the production verifier against baseURL (e.g. // "http://vlei-verifier:7676"), with the trailing slash trimmed. func NewVerifier(baseURL string, opts ...VerifierOption) *Verifier { @@ -87,6 +106,7 @@ func NewVerifier(baseURL string, opts ...VerifierOption) *Verifier { baseURL: strings.TrimRight(baseURL, "/"), client: &http.Client{Timeout: 5 * time.Second}, maxBodyBytes: 1 << 20, + logger: zerolog.Nop(), } for _, opt := range opts { opt(v) @@ -149,9 +169,11 @@ func (v *Verifier) Present(ctx context.Context, cesr string) (port.PresentationR return port.PresentationResult{}, domain.NewValidationError("LEI_PRESENTATION_INVALID", "the vlei verifier rejected the presented credential") default: + v.logFailure("present", "verifier returned an unexpected status", status, nil) return port.PresentationResult{}, v.unavailable("present") } if pres.AID == "" { + v.logFailure("present", "verifier accepted the presentation but returned no subject AID", status, nil) return port.PresentationResult{}, v.unavailable("present") } @@ -199,6 +221,7 @@ func (v *Verifier) Authorization(ctx context.Context, subjectAID string) (port.A // 401: presented but not authorized; 404: not yet processed. return port.AuthorizationResult{Authorized: false}, nil default: + v.logFailure("authorize", "verifier returned an unexpected status", status, nil) return port.AuthorizationResult{}, v.unavailable("authorize") } } @@ -248,6 +271,7 @@ func (v *Verifier) VerifySignature(ctx context.Context, subjectAID, signingInput // proof from the registrant's perspective, not a verifier outage. return false, nil default: + v.logFailure("verify-signature", "verifier returned an unexpected status", status, nil) return false, v.unavailable("verify-signature") } } @@ -263,15 +287,18 @@ func (v *Verifier) do(req *http.Request, out any, op string) (int, error) { resp, err := v.client.Do(req) //nolint:gosec // baseURL is operator-configured; no caller-controlled host if err != nil { + v.logFailure(op, "request to the verifier failed", 0, err) return 0, v.unavailable(op) } defer func() { _ = resp.Body.Close() }() body, err := io.ReadAll(io.LimitReader(resp.Body, v.maxBodyBytes+1)) if err != nil { + v.logFailure(op, "reading the verifier response failed", resp.StatusCode, err) return resp.StatusCode, v.unavailable(op) } if int64(len(body)) > v.maxBodyBytes { + v.logFailure(op, "verifier response exceeded the size cap", resp.StatusCode, nil) return resp.StatusCode, v.unavailable(op) } // Decode strictly on a 2xx success — the contract callers rely on. @@ -283,12 +310,31 @@ func (v *Verifier) do(req *http.Request, out any, op string) (int, error) { // are not consumed by callers, so we leave them undecoded. if out != nil && len(body) > 0 && resp.StatusCode >= 200 && resp.StatusCode < 300 { if err := json.Unmarshal(body, out); err != nil { + v.logFailure(op, "verifier 2xx body failed to decode (failing closed)", resp.StatusCode, err) return resp.StatusCode, v.unavailable("decode") } } return resp.StatusCode, nil } +// logFailure records an operational verifier failure server-side, at the +// same coarse-wire / detailed-log split as the did:web resolver. The wire +// error (v.unavailable) never names the configured host or echoes the +// response body; the diagnosable category goes ONLY here, so an on-call +// engineer can distinguish an internal vlei-verifier outage (transport +// error, status 0) from a 5xx, an oversized body, a fail-closed decode, +// or a contract violation (a 2xx carrying no subject AID). status is 0 +// when no HTTP response was received; err is nil for the status- and +// contract-derived failures the response itself already describes. +func (v *Verifier) logFailure(op, reason string, status int, err error) { + v.logger.Warn(). + Err(err). + Str("op", op). + Str("reason", reason). + Int("status", status). + Msg("vlei verifier call failed") +} + // unavailable builds the operator-facing error for a verifier I/O or // protocol failure. The detail names the operation but never the // configured host (no internal-topology leak). From 5ed3627ef025f9bc8b039ceee24033b8b8138b15 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Tue, 23 Jun 2026 09:36:47 +1000 Subject: [PATCH 13/21] fix(leiverifier): fail closed on 200 authorization with no LEI 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 --- internal/adapter/leiverifier/leiverifier_test.go | 12 ++++++++++++ internal/adapter/leiverifier/verifier.go | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/internal/adapter/leiverifier/leiverifier_test.go b/internal/adapter/leiverifier/leiverifier_test.go index b1af2f0..39dca31 100644 --- a/internal/adapter/leiverifier/leiverifier_test.go +++ b/internal/adapter/leiverifier/leiverifier_test.go @@ -254,6 +254,18 @@ func TestVerifierAuthorization(t *testing.T) { t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) } }) + // A 200 carrying no LEI (empty body or {}) must fail closed: an empty + // LEI reads downstream as the noop waiver of the AID↔LEI binding, so + // returning {Authorized:true, LEI:""} would silently degrade the + // production verifier to noop semantics. Mirror the empty-AID guard. + for _, body := range []string{"", "{}", `{"lei":""}`} { + t.Run("200 without LEI unavailable", func(t *testing.T) { + v := newVerifierFor(t, &vleiServer{authStatus: http.StatusOK, authBody: body}) + if _, err := v.Authorization(ctx, "EAID"); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { + t.Fatalf("body %q: want LEI_VERIFIER_UNAVAILABLE, got %v", body, err) + } + }) + } t.Run("non-qb64 AID rejected before dial", func(t *testing.T) { v := newVerifierFor(t, &vleiServer{authStatus: http.StatusOK, authBody: `{"lei":"L1"}`}) if _, err := v.Authorization(ctx, "../signature/verify"); !isCode(err, "LEI_SUBJECT_AID_INVALID") { diff --git a/internal/adapter/leiverifier/verifier.go b/internal/adapter/leiverifier/verifier.go index 6538405..aa0e448 100644 --- a/internal/adapter/leiverifier/verifier.go +++ b/internal/adapter/leiverifier/verifier.go @@ -216,6 +216,10 @@ func (v *Verifier) Authorization(ctx context.Context, subjectAID string) (port.A } switch status { case http.StatusOK: + if auth.LEI == "" { + v.logFailure("authorize", "verifier authorized the AID but returned no LEI (failing closed)", status, nil) + return port.AuthorizationResult{}, v.unavailable("authorize") + } return port.AuthorizationResult{Authorized: true, LEI: auth.LEI}, nil case http.StatusUnauthorized, http.StatusNotFound: // 401: presented but not authorized; 404: not yet processed. From 8b194fda081ab3cae450bc9be55aa2e7939505aa Mon Sep 17 00:00:00 2001 From: James Hateley Date: Tue, 23 Jun 2026 10:36:15 +1000 Subject: [PATCH 14/21] docs(spec): document register/rotate identity verifier error codes 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 --- internal/adapter/docsui/openapi/ra.yaml | 31 +++++++++++++++++++++++-- spec/api-spec-v2.yaml | 31 +++++++++++++++++++++++-- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/internal/adapter/docsui/openapi/ra.yaml b/internal/adapter/docsui/openapi/ra.yaml index 4288e61..7cabf34 100644 --- a/internal/adapter/docsui/openapi/ra.yaml +++ b/internal/adapter/docsui/openapi/ra.yaml @@ -960,7 +960,20 @@ paths: schema: $ref: '#/components/schemas/ErrorResponse' '422': - description: Invalid or unsupported identifier + description: | + Invalid or unsupported identifier; for the `did:web` kind the + register-time resolution may fail with `DID_RESOLUTION_FAILED` + or `DID_DOCUMENT_ID_MISMATCH`; for the `lei` kind — + `IDENTIFIER_PRESENTATION_REQUIRED`, `LEI_PRESENTATION_INVALID`, + `LEI_MISMATCH`, `LEI_SUBJECT_AID_INVALID`. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '503': + description: | + Upstream unavailable — `LEI_VERIFIER_UNAVAILABLE` (the `lei` + verifier runs synchronously at register; retryable). content: application/json: schema: @@ -1074,7 +1087,21 @@ paths: schema: $ref: '#/components/schemas/ErrorResponse' '422': - description: Invalid replacement value (incl. IDENTIFIER_KIND_MISMATCH) + description: | + Invalid replacement value (incl. `IDENTIFIER_KIND_MISMATCH`); + for the `did:web` kind the register-time resolution may fail + with `DID_RESOLUTION_FAILED` or `DID_DOCUMENT_ID_MISMATCH`; + for the `lei` kind — `IDENTIFIER_PRESENTATION_REQUIRED`, + `LEI_PRESENTATION_INVALID`, `LEI_MISMATCH`, + `LEI_SUBJECT_AID_INVALID`. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '503': + description: | + Upstream unavailable — `LEI_VERIFIER_UNAVAILABLE` (the `lei` + verifier runs synchronously at rotate; retryable). content: application/json: schema: diff --git a/spec/api-spec-v2.yaml b/spec/api-spec-v2.yaml index 4288e61..7cabf34 100644 --- a/spec/api-spec-v2.yaml +++ b/spec/api-spec-v2.yaml @@ -960,7 +960,20 @@ paths: schema: $ref: '#/components/schemas/ErrorResponse' '422': - description: Invalid or unsupported identifier + description: | + Invalid or unsupported identifier; for the `did:web` kind the + register-time resolution may fail with `DID_RESOLUTION_FAILED` + or `DID_DOCUMENT_ID_MISMATCH`; for the `lei` kind — + `IDENTIFIER_PRESENTATION_REQUIRED`, `LEI_PRESENTATION_INVALID`, + `LEI_MISMATCH`, `LEI_SUBJECT_AID_INVALID`. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '503': + description: | + Upstream unavailable — `LEI_VERIFIER_UNAVAILABLE` (the `lei` + verifier runs synchronously at register; retryable). content: application/json: schema: @@ -1074,7 +1087,21 @@ paths: schema: $ref: '#/components/schemas/ErrorResponse' '422': - description: Invalid replacement value (incl. IDENTIFIER_KIND_MISMATCH) + description: | + Invalid replacement value (incl. `IDENTIFIER_KIND_MISMATCH`); + for the `did:web` kind the register-time resolution may fail + with `DID_RESOLUTION_FAILED` or `DID_DOCUMENT_ID_MISMATCH`; + for the `lei` kind — `IDENTIFIER_PRESENTATION_REQUIRED`, + `LEI_PRESENTATION_INVALID`, `LEI_MISMATCH`, + `LEI_SUBJECT_AID_INVALID`. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '503': + description: | + Upstream unavailable — `LEI_VERIFIER_UNAVAILABLE` (the `lei` + verifier runs synchronously at rotate; retryable). content: application/json: schema: From f4fdc95d6e43762592b77f8a2ecae72957c3468f Mon Sep 17 00:00:00 2001 From: James Hateley Date: Tue, 23 Jun 2026 11:01:28 +1000 Subject: [PATCH 15/21] docs(identity): refresh stale lei comments and document proof-family 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 --- internal/domain/identity.go | 6 +++--- internal/ra/service/identitykinds.go | 7 +++++++ internal/tl/event/identity/event.go | 4 ++-- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/internal/domain/identity.go b/internal/domain/identity.go index 4469472..7d1101e 100644 --- a/internal/domain/identity.go +++ b/internal/domain/identity.go @@ -14,7 +14,7 @@ type IdentifierKind string // Identifier kinds. A kind being *recognized* here is independent of // it being *enabled* — the service layer dispatches per kind and // returns IDENTIFIER_KIND_UNSUPPORTED for kinds this deployment has -// no control verifier for (lei is recognized but postponed). +// no control verifier wired for. const ( // KindDIDWeb — did:web. The authoritative keys live in the DID // document fetched from the operator's web host; control is @@ -26,8 +26,8 @@ const ( KindDIDKey IdentifierKind = "did:key" // KindLEI — an ISO 17442 Legal Entity Identifier, proven through - // a vLEI credential presentation. Postponed: recognized so the - // error is precise, but no control verifier ships yet. + // a vLEI credential presentation verified by the LEIControlVerifier + // port (noop quickstart adapter, or the real vlei-verifier client). KindLEI IdentifierKind = "lei" ) diff --git a/internal/ra/service/identitykinds.go b/internal/ra/service/identitykinds.go index 7327fb1..041065d 100644 --- a/internal/ra/service/identitykinds.go +++ b/internal/ra/service/identitykinds.go @@ -73,6 +73,13 @@ type ProofSubmission struct { // by VerifyControlRequest in spec/api-spec-v2.yaml: EXACTLY ONE proof // family is set per request (JWS kinds → signedProofs; lei → // cesrSignature). +// +// Checks value-presence, not the spec oneOf's literal key-presence: +// the plain []string/string types collapse absent, null, and empty to +// the same zero value, so key-presence is not recoverable here. Value- +// presence is stricter — it rejects a body with no usable proof rather +// than deferring to a per-kind verifier — diverging only on a body with +// both keys present but one empty, which routes by the non-empty family. func (s ProofSubmission) validateExactlyOneFamily() error { hasJWS := len(s.SignedProofs) > 0 hasCESR := s.CESRSignature != "" diff --git a/internal/tl/event/identity/event.go b/internal/tl/event/identity/event.go index 00f2ffe..1737297 100644 --- a/internal/tl/event/identity/event.go +++ b/internal/tl/event/identity/event.go @@ -178,8 +178,8 @@ type Event struct { // conveniences (anyone can derive RFC 7638 from the sealed source); // they are never part of the sealed contract. // -// The postponed lei kind is the one deliberate exception: it will -// seal the subject AID + a key thumbprint only — there is no +// The lei kind is the one deliberate exception: it seals the +// subject AID + a key thumbprint only — there is no // document to quote, the ACDC is PII, and KERI's KEL is already the // authoritative key history. Seal verbatim what has no other // tamper-evident home; commit minimally where one exists. From cb94574dded8e867e341ce0de6e8098cd3d7d1c2 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Mon, 13 Jul 2026 11:56:38 +1000 Subject: [PATCH 16/21] refactor(ra): return facts from RegisterPresentation instead of mutating aggregate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- internal/ra/service/identity.go | 14 +++++++--- internal/ra/service/identitykinds.go | 42 +++++++++------------------- internal/ra/service/leiverifier.go | 39 +++++++++++--------------- 3 files changed, 40 insertions(+), 55 deletions(-) diff --git a/internal/ra/service/identity.go b/internal/ra/service/identity.go index b0590ed..389bedc 100644 --- a/internal/ra/service/identity.go +++ b/internal/ra/service/identity.go @@ -346,15 +346,21 @@ func (s *IdentityService) challenge(ctx context.Context, identity *domain.Verifi } // Kinds carrying a register-time presentation (lei) submit it to - // their verifier here, pinning the verifier-derived subject AID on - // the aggregate before the challenge enumerates it. Discovered by - // capability — non-presentation kinds skip this entirely. + // their verifier here and get back the derived subject AID, which we + // stage on the aggregate before the challenge enumerates it. + // Discovered by capability — non-presentation kinds skip this + // entirely. StageSubjectAID touches only PendingSubjectAID + + // UpdatedAt, never a guard column, so it never disturbs the snapshot. var presentationStatus port.PresentationStatus if pr, ok := verifier.(presentationRegistrar); ok { - presentationStatus, err = pr.RegisterPresentation(ctx, identity, opt, now) + var subjectAID string + subjectAID, presentationStatus, err = pr.RegisterPresentation(ctx, identity.EffectiveValue(), opt) if err != nil { return nil, err } + if err := identity.StageSubjectAID(subjectAID, now); err != nil { + return nil, err + } } // Load-time snapshot for the conditional persist. diff --git a/internal/ra/service/identitykinds.go b/internal/ra/service/identitykinds.go index 041065d..cf2a412 100644 --- a/internal/ra/service/identitykinds.go +++ b/internal/ra/service/identitykinds.go @@ -47,7 +47,6 @@ import ( "encoding/json" "fmt" "strings" - "time" anscrypto "github.com/godaddy/ans/internal/crypto" "github.com/godaddy/ans/internal/domain" @@ -105,36 +104,21 @@ type RegisterOptions struct { // presentationRegistrar is the optional capability a kind implements // when it carries credential material at REGISTER time (lei's vLEI -// presentation). The service discovers it by type-assertion on the -// kind's controlVerifier — the same discover-by-capability pattern the -// 202 response uses for presentationStatus — so kinds with no -// register-time presentation (did:web, did:key) never grow a dead -// method. RegisterPresentation runs inside the shared challenge path, -// so an idempotent re-add (and a rotation) re-presents and refreshes -// the verifier's authorization window for free. +// presentation), discovered by type-assertion on the controlVerifier so +// kinds without one (did:web, did:key) grow no dead method. // -// RACE INVARIANT: RegisterPresentation runs BEFORE challenge() captures -// the conditional-persist snapshot (identity.go:360), and is itself a -// slow network call. The snapshot reads the in-memory load-time Status -// and Challenge.Nonce, and the store's StageChallenge refuses the write -// unless the row still matches them — so the conditional persist only -// brackets the presentation fetch (a concurrent verify/revoke during it -// → 0 rows → conflict, never a clobber) AS LONG AS RegisterPresentation -// does NOT mutate Status or Challenge.Nonce. It may pin kind-specific -// state (lei: PendingSubjectAID) and bump UpdatedAt; it must touch neither -// guard column. Mutating Status here would make the snapshot reflect a -// post-presentation value, opening exactly the status-regression race -// (VERIFIED → PENDING_CONTROL) the conditional persist exists to close. -// See docs/identity-challenge-race.md. +// It returns derived facts and never receives the aggregate, so it +// cannot touch the conditional-persist guard columns (Status, +// Challenge.Nonce): challenge() stages the returned identifier itself. +// The presentation fetch is thus race-safe by construction — see the +// StageChallenge doc block in internal/adapter/store/sqlite/identity.go +// for the conditional-persist guard the snapshot rides. type presentationRegistrar interface { - // RegisterPresentation submits the kind's register-time credential - // material to its verifier, pins the derived subject identifier on - // the aggregate, reconciles it against the requested value, and - // returns the advisory presentation status ("AUTHORIZED" | - // "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) + // RegisterPresentation submits the register-time credential to the + // verifier, reconciles it against effectiveValue, and returns the + // verifier-derived subject identifier and advisory presentation + // status ("AUTHORIZED" | "PENDING") for the 202. + RegisterPresentation(ctx context.Context, effectiveValue string, opts RegisterOptions) (subjectAID string, status port.PresentationStatus, err error) } // controlVerifier is the per-kind control-proof gate — the design's diff --git a/internal/ra/service/leiverifier.go b/internal/ra/service/leiverifier.go index a7af674..125a7c0 100644 --- a/internal/ra/service/leiverifier.go +++ b/internal/ra/service/leiverifier.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "strings" - "time" "github.com/godaddy/ans/internal/domain" "github.com/godaddy/ans/internal/port" @@ -24,10 +23,10 @@ import ( // // - The credential presentation arrives at REGISTER time, so lei // also implements presentationRegistrar: the shared challenge path -// submits the CESR, pins the verifier-derived subject AID on the -// aggregate, and reports the advisory presentation status. A -// re-add (or rotation) re-presents and refreshes the verifier's -// authorization window for free. +// submits the CESR and gets back the verifier-derived subject AID +// and advisory presentation status. A re-add (or rotation) +// re-presents and refreshes the verifier's authorization window +// for free. // - The proof is a single CESR signature over the served // signingInput (not a JWS array), and the seal commits the subject // AID + a thumbprint only — no JWK, no document. The KEL is the @@ -37,40 +36,36 @@ type leiVerifier struct { v port.LEIControlVerifier } -// RegisterPresentation submits the register-time CESR to the verifier, -// pins the derived subject AID, and reconciles the credential's LEI -// against the requested value. Returns the advisory presentation -// status for the 202. +// RegisterPresentation submits the register-time CESR to the verifier +// and reconciles the credential's LEI against effectiveValue. Returns +// the derived subject AID and the advisory presentation status for the +// 202; the caller stages the AID. func (lv *leiVerifier) RegisterPresentation( ctx context.Context, - identity *domain.VerifiedIdentity, + effectiveValue string, opts RegisterOptions, - now time.Time, -) (port.PresentationStatus, error) { +) (string, port.PresentationStatus, error) { if opts.VLEIPresentation == "" { - return "", domain.NewValidationError("IDENTIFIER_PRESENTATION_REQUIRED", + return "", "", domain.NewValidationError("IDENTIFIER_PRESENTATION_REQUIRED", "lei registration requires vleiPresentation.cesr") } res, err := lv.v.Present(ctx, opts.VLEIPresentation) if err != nil { - return "", err + return "", "", err } if res.SubjectAID == "" { - return "", domain.NewValidationError("LEI_PRESENTATION_INVALID", + return "", "", domain.NewValidationError("LEI_PRESENTATION_INVALID", "the vlei verifier returned no subject AID for the presentation") } // Reconcile the presented LEI against the registered value. The // noop adapter waives the AID↔LEI binding and returns an empty LEI // (the documented quickstart waiver, mirroring noop-DNS); skip the // equality check in that case. - if res.LEI != "" && !strings.EqualFold(res.LEI, identity.EffectiveValue()) { - return "", domain.NewValidationError("LEI_MISMATCH", - fmt.Sprintf("presented credential authorizes LEI %q, not %q", res.LEI, identity.EffectiveValue())) - } - if err := identity.StageSubjectAID(res.SubjectAID, now); err != nil { - return "", err + if res.LEI != "" && !strings.EqualFold(res.LEI, effectiveValue) { + return "", "", domain.NewValidationError("LEI_MISMATCH", + fmt.Sprintf("presented credential authorizes LEI %q, not %q", res.LEI, effectiveValue)) } - return res.Status, nil + return res.SubjectAID, res.Status, nil } // Challenges returns the single lei challenge entry: the pinned From 31bda0adeb569e74736cd7bd58d9556cea06d019 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Mon, 13 Jul 2026 11:59:10 +1000 Subject: [PATCH 17/21] fix(migrations): rename migrations file Signed-off-by: James Hateley --- ...{008_identity_subject_aid.sql => 011_identity_subject_aid.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename internal/adapter/store/sqlite/migrations/{008_identity_subject_aid.sql => 011_identity_subject_aid.sql} (100%) diff --git a/internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql b/internal/adapter/store/sqlite/migrations/011_identity_subject_aid.sql similarity index 100% rename from internal/adapter/store/sqlite/migrations/008_identity_subject_aid.sql rename to internal/adapter/store/sqlite/migrations/011_identity_subject_aid.sql From 2bebcd07854650b66cb13bba4df4e4f9507bafcb Mon Sep 17 00:00:00 2001 From: James Hateley Date: Mon, 13 Jul 2026 13:26:08 +1000 Subject: [PATCH 18/21] feat(vlei): default vlei to off Signed-off-by: James Hateley --- cmd/ans-ra/main.go | 11 +++++++---- internal/config/config.go | 11 ++++++----- internal/config/defaults.go | 2 +- internal/ra/service/identitykinds.go | 11 +++++++---- 4 files changed, 21 insertions(+), 14 deletions(-) diff --git a/cmd/ans-ra/main.go b/cmd/ans-ra/main.go index 2bf0427..011d5dd 100644 --- a/cmd/ans-ra/main.go +++ b/cmd/ans-ra/main.go @@ -598,9 +598,10 @@ func selectDIDResolver(cfg *config.RAConfig, logger zerolog.Logger) port.DIDReso // selectLEIVerifier returns the configured vLEI control verifier — the // lei kind's analog of selectDIDResolver. "verifier" is the hardened // HTTP client for an internal vlei-verifier (config-validated base -// URL); the default "noop" performs structural-only qb64 checks and -// waives both the GLEIF authorization binding and the cryptographic -// signature check +// URL); "noop" performs structural-only qb64 checks and waives both +// the GLEIF authorization binding and the cryptographic signature +// check; the default "off" returns nil, leaving the lei kind +// unregistered (recognized values then fail IDENTIFIER_KIND_UNSUPPORTED). func selectLEIVerifier(cfg *config.RAConfig, logger zerolog.Logger) port.LEIControlVerifier { switch cfg.VLEI.Type { case "verifier": @@ -609,7 +610,9 @@ func selectLEIVerifier(cfg *config.RAConfig, logger zerolog.Logger) port.LEICont opts = append(opts, leiverifier.WithTimeout(cfg.VLEI.PresentTimeout)) } return leiverifier.NewVerifier(cfg.VLEI.BaseURL, opts...) - default: + case "noop": return leiverifier.NewNoop() + default: // "off" + return nil } } diff --git a/internal/config/config.go b/internal/config/config.go index 8381330..abbee51 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -519,12 +519,13 @@ func validateCAServer(s *CAServer) error { return nil } -// validateVLEI checks the vLEI control-verifier selection: "noop" -// needs nothing, "verifier" needs a valid http(s) base URL, and the -// per-request timeout may not be negative. +// validateVLEI checks the vLEI control-verifier selection: "off" +// (disables the lei kind) and "noop" need nothing, "verifier" needs a +// valid http(s) base URL, and the per-request timeout may not be +// negative. func validateVLEI(v *VLEI) error { switch v.Type { - case "noop": + case "off", "noop": case "verifier": if v.BaseURL == "" { return errors.New("vlei.base-url is required when vlei.type is 'verifier'") @@ -534,7 +535,7 @@ func validateVLEI(v *VLEI) error { return fmt.Errorf("vlei.base-url must be a valid http(s) URL, got %q", v.BaseURL) } default: - return fmt.Errorf("vlei.type %q not supported (expected 'noop' or 'verifier')", v.Type) + return fmt.Errorf("vlei.type %q not supported (expected 'off', 'noop', or 'verifier')", v.Type) } if v.PresentTimeout < 0 { return errors.New("vlei.present-timeout must not be negative") diff --git a/internal/config/defaults.go b/internal/config/defaults.go index c325798..56a0304 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -27,7 +27,7 @@ func defaultRAConfig() *RAConfig { LinkRateLimit: 60, SealTimeout: 5 * time.Second, }, - VLEI: VLEI{Type: "noop"}, + VLEI: VLEI{Type: "off"}, Keys: Keys{ Type: "file", File: &KeysFile{Path: "./data/ra/keys"}, diff --git a/internal/ra/service/identitykinds.go b/internal/ra/service/identitykinds.go index cf2a412..16fc833 100644 --- a/internal/ra/service/identitykinds.go +++ b/internal/ra/service/identitykinds.go @@ -147,13 +147,16 @@ func newControlVerifiers(resolver port.DIDResolver, leiCtl port.LEIControlVerifi // NOTE: deliberately NOT exhaustive over IdentifierKind — a // recognized-but-absent kind (did:plc, did:ion, did:ethr, until // their verifiers ship) MUST fail with IDENTIFIER_KIND_UNSUPPORTED - // rather than register a stub. The 404-is-the-signal rule. lei - // now registers — its noop adapter is the zero-infra quickstart. - return map[domain.IdentifierKind]controlVerifier{ + // rather than register a stub. The 404-is-the-signal rule. LEI + // only registered when configured. + m := map[domain.IdentifierKind]controlVerifier{ domain.KindDIDWeb: &didWebVerifier{resolver: resolver}, domain.KindDIDKey: &didKeyVerifier{}, - domain.KindLEI: &leiVerifier{v: leiCtl}, } + if leiCtl != nil { + m[domain.KindLEI] = &leiVerifier{v: leiCtl} // absent → IDENTIFIER_KIND_UNSUPPORTED + } + return m } // ----- shared JWS proof machinery ----- From f8cfe730b0658eb4d0efd87343ae97e04db535d7 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Mon, 13 Jul 2026 14:47:51 +1000 Subject: [PATCH 19/21] feat(vlei): cap links payload Signed-off-by: James Hateley --- internal/ra/handler/identity.go | 1 + internal/ra/handler/identity_handler_test.go | 5 +++++ internal/ra/service/identitykinds.go | 1 + 3 files changed, 7 insertions(+) diff --git a/internal/ra/handler/identity.go b/internal/ra/handler/identity.go index 1f0eada..976c1be 100644 --- a/internal/ra/handler/identity.go +++ b/internal/ra/handler/identity.go @@ -290,6 +290,7 @@ func (h *IdentityHandler) Link(w http.ResponseWriter, r *http.Request) { 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 { WriteError(w, domain.NewValidationError("INVALID_REQUEST_BODY", "request body is not valid JSON")) diff --git a/internal/ra/handler/identity_handler_test.go b/internal/ra/handler/identity_handler_test.go index bf8bdc3..e535fd4 100644 --- a/internal/ra/handler/identity_handler_test.go +++ b/internal/ra/handler/identity_handler_test.go @@ -311,6 +311,11 @@ func TestIdentityHandler_AuthAndValidation(t *testing.T) { if rec := f.do(t, "owner-1", http.MethodPut, "/v2/ans/identities/x", map[string]string{}); rec.Code != http.StatusUnprocessableEntity { t.Fatalf("empty value rotate: %d", rec.Code) } + // Over the Link route's 32 KiB cap → MaxBytesReader trips → 422 + oversized := `{"agentIds":"` + strings.Repeat("A", 32<<10) + `"}` + if rec := f.doRaw(t, "owner-1", http.MethodPost, "/v2/ans/identities/x/links", oversized); rec.Code != http.StatusUnprocessableEntity { + t.Fatalf("oversized body: %d", rec.Code) + } } // TestIdentityHandler_BodyCap pins the 1 MiB MaxBytesReader on the diff --git a/internal/ra/service/identitykinds.go b/internal/ra/service/identitykinds.go index 16fc833..7609108 100644 --- a/internal/ra/service/identitykinds.go +++ b/internal/ra/service/identitykinds.go @@ -149,6 +149,7 @@ func newControlVerifiers(resolver port.DIDResolver, leiCtl port.LEIControlVerifi // their verifiers ship) MUST fail with IDENTIFIER_KIND_UNSUPPORTED // rather than register a stub. The 404-is-the-signal rule. LEI // only registered when configured. + //exhaustive:ignore // registry is intentionally partial; absent kinds map to IDENTIFIER_KIND_UNSUPPORTED m := map[domain.IdentifierKind]controlVerifier{ domain.KindDIDWeb: &didWebVerifier{resolver: resolver}, domain.KindDIDKey: &didKeyVerifier{}, From 25a32e86d200f6facc76fa7907c5c8afb0774983 Mon Sep 17 00:00:00 2001 From: James Hateley Date: Mon, 13 Jul 2026 15:10:36 +1000 Subject: [PATCH 20/21] feat(vlei): fix coverage of outbound verfier calls Signed-off-by: James Hateley --- .../adapter/leiverifier/leiverifier_test.go | 103 +++++++++++++++++- 1 file changed, 100 insertions(+), 3 deletions(-) diff --git a/internal/adapter/leiverifier/leiverifier_test.go b/internal/adapter/leiverifier/leiverifier_test.go index 39dca31..a3ca494 100644 --- a/internal/adapter/leiverifier/leiverifier_test.go +++ b/internal/adapter/leiverifier/leiverifier_test.go @@ -5,9 +5,11 @@ import ( "context" "encoding/json" "errors" + "io" "net/http" "net/http/httptest" "strings" + "sync" "testing" "time" @@ -126,6 +128,13 @@ func TestNoopVerifySignature(t *testing.T) { } } +type recordedRequest struct { + method string + path string + contentType string + body string +} + // vleiServer is a programmable stand-in for the vlei-verifier service. type vleiServer struct { presentStatus int @@ -133,19 +142,35 @@ type vleiServer struct { authStatus int authBody string verifyStatus int + + 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), + }) } func (s *vleiServer) handler() http.Handler { mux := http.NewServeMux() - mux.HandleFunc("/presentations/", func(w http.ResponseWriter, _ *http.Request) { + mux.HandleFunc("/presentations/", func(w http.ResponseWriter, r *http.Request) { + s.record(r) w.WriteHeader(s.presentStatus) _, _ = w.Write([]byte(s.presentBody)) }) - mux.HandleFunc("/authorizations/", func(w http.ResponseWriter, _ *http.Request) { + mux.HandleFunc("/authorizations/", func(w http.ResponseWriter, r *http.Request) { + s.record(r) w.WriteHeader(s.authStatus) _, _ = w.Write([]byte(s.authBody)) }) - mux.HandleFunc("/signature/verify", func(w http.ResponseWriter, _ *http.Request) { + mux.HandleFunc("/signature/verify", func(w http.ResponseWriter, r *http.Request) { + s.record(r) w.WriteHeader(s.verifyStatus) }) return mux @@ -196,6 +221,78 @@ func TestVerifierPresentPendingAuthorization(t *testing.T) { } } +// TestVerifierRequestShapes asserts the OUTBOUND contract — what the +// adapter sends, pins the path template, the content type, request-body fields +func TestVerifierRequestShapes(t *testing.T) { + s := &vleiServer{ + presentStatus: http.StatusAccepted, + presentBody: `{"aid":"EHolderAID","said":"ECredSAID123"}`, + authStatus: http.StatusOK, + authBody: `{"lei":"5493001KJTIIGC8Y1R17"}`, + verifyStatus: http.StatusAccepted, + } + v := newVerifierFor(t, s) + + // Present → PUT /presentations/ECredSAID123 (leaf SAID from validCESR), + // then GET /authorizations/EHolderAID (subject AID from the response). + if _, err := v.Present(context.Background(), validCESR); err != nil { + t.Fatalf("Present: %v", err) + } + // VerifySignature → POST /signature/verify. + if _, err := v.VerifySignature(context.Background(), "EHolderAID", "the-signing-input", "0BtheSignature"); err != nil { + t.Fatalf("VerifySignature: %v", err) + } + + if len(s.requests) != 3 { + t.Fatalf("recorded %d requests, want 3: %+v", len(s.requests), s.requests) + } + present, auth, verify := s.requests[0], s.requests[1], s.requests[2] + + // PUT /presentations/{said}, application/json+cesr, CESR body verbatim. + if present.method != http.MethodPut || present.path != "/presentations/ECredSAID123" { + t.Errorf("present line = %s %s, want PUT /presentations/ECredSAID123", present.method, present.path) + } + if present.contentType != "application/json+cesr" { + t.Errorf("present content-type = %q, want application/json+cesr", present.contentType) + } + if present.body != validCESR { + t.Errorf("present body = %q, want the CESR export verbatim", present.body) + } + + // GET /authorizations/{aid}, no body. + if auth.method != http.MethodGet || auth.path != "/authorizations/EHolderAID" { + t.Errorf("authorize line = %s %s, want GET /authorizations/EHolderAID", auth.method, auth.path) + } + + // POST /signature/verify, application/json, exactly the three + // snake_case tags bound to the right values. Decoding into a map keys + // on the wire tags, so a struct-tag typo (signerAid, nonPrefixedDigest, + // …) leaves the expected key absent and fails here. + if verify.method != http.MethodPost || verify.path != "/signature/verify" { + t.Errorf("verify line = %s %s, want POST /signature/verify", verify.method, verify.path) + } + if verify.contentType != "application/json" { + t.Errorf("verify content-type = %q, want application/json", verify.contentType) + } + var got map[string]any + if err := json.Unmarshal([]byte(verify.body), &got); err != nil { + t.Fatalf("verify body is not JSON: %v (%q)", err, verify.body) + } + want := map[string]any{ + "signer_aid": "EHolderAID", + "signature": "0BtheSignature", + "non_prefixed_digest": "the-signing-input", + } + for k, wv := range want { + if got[k] != wv { + t.Errorf("verify body[%q] = %v, want %v", k, got[k], wv) + } + } + if len(got) != len(want) { + t.Errorf("verify body has %d fields, want exactly %d: %q", len(got), len(want), verify.body) + } +} + func TestVerifierPresentFailures(t *testing.T) { t.Run("no ACDC frame", func(t *testing.T) { v := newVerifierFor(t, &vleiServer{}) From 5fdc719be25bb34d633dbf5538a645118c93ed8d Mon Sep 17 00:00:00 2001 From: James Hateley Date: Mon, 13 Jul 2026 16:04:53 +1000 Subject: [PATCH 21/21] feat(vlei): use recorded fixtures for vlei verifier contract Signed-off-by: James Hateley --- .../adapter/leiverifier/leiverifier_test.go | 81 +++++++++++++++---- .../vlei-verifier-0.1.5/PROVENANCE.md | 58 +++++++++++++ .../authorizations-200-aid-only.json | 1 + .../authorizations-200-credential.json | 1 + .../authorizations-401-unknown.json | 1 + .../vlei-verifier-0.1.5/present-202.json | 1 + .../signature-verify-202.json | 1 + .../signature-verify-401.json | 1 + scripts/demo/vlei/docker-compose.yml | 7 +- 9 files changed, 137 insertions(+), 15 deletions(-) create mode 100644 internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/PROVENANCE.md create mode 100644 internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-200-aid-only.json create mode 100644 internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-200-credential.json create mode 100644 internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-401-unknown.json create mode 100644 internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/present-202.json create mode 100644 internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/signature-verify-202.json create mode 100644 internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/signature-verify-401.json diff --git a/internal/adapter/leiverifier/leiverifier_test.go b/internal/adapter/leiverifier/leiverifier_test.go index a3ca494..8b46794 100644 --- a/internal/adapter/leiverifier/leiverifier_test.go +++ b/internal/adapter/leiverifier/leiverifier_test.go @@ -8,6 +8,8 @@ import ( "io" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "sync" "testing" @@ -142,6 +144,7 @@ type vleiServer struct { authStatus int authBody string verifyStatus int + verifyBody string mu sync.Mutex requests []recordedRequest // method, path, contentType, body @@ -172,6 +175,7 @@ func (s *vleiServer) handler() http.Handler { mux.HandleFunc("/signature/verify", func(w http.ResponseWriter, r *http.Request) { s.record(r) w.WriteHeader(s.verifyStatus) + _, _ = w.Write([]byte(s.verifyBody)) }) return mux } @@ -180,6 +184,26 @@ func (s *vleiServer) handler() http.Handler { // self-addressing `d` is the presented credential SAID. const validCESR = `{"v":"ACDC10JSON00011c_","d":"ECredSAID123","i":"EHolderAID","s":"ESchema","a":{"LEI":"5493001KJTIIGC8Y1R17"}}-CESR-attachments` +// fixtureDir holds the recorded vlei-verifier 0.1.5 response bodies (see +// its PROVENANCE.md). These files are the SINGLE SOURCE OF TRUTH for the +// verifier's response shapes: the happy-path harness below serves them +// verbatim rather than hand-written JSON, so the whole suite is verified +// against the real 0.1.5 contract, not against what we assume it returns. +// A field-name / structural drift on a version bump changes the re-derived +// fixture and fails the matching test. Only deliberately-malformed or +// edge-shaped bodies (missing fields, junk JSON) stay inline below — those +// are synthetic by design and have no real counterpart to record. +const fixtureDir = "testdata/vlei-verifier-0.1.5" + +func fixture(t *testing.T, name string) string { + t.Helper() + b, err := os.ReadFile(filepath.Join(fixtureDir, name)) + if err != nil { + t.Fatalf("read fixture %s: %v", name, err) + } + return string(b) +} + func newVerifierFor(t *testing.T, s *vleiServer) *Verifier { t.Helper() srv := httptest.NewServer(s.handler()) @@ -188,11 +212,14 @@ func newVerifierFor(t *testing.T, s *vleiServer) *Verifier { } func TestVerifierPresentHappy(t *testing.T) { + // Served bodies are the recorded 0.1.5 responses: PUT /presentations + // 202 → {creds, aid, msg} (note: no `said` — the adapter reads `aid`), + // GET /authorizations 200 → {aid, said, lei, role, msg}. s := &vleiServer{ presentStatus: http.StatusAccepted, - presentBody: `{"aid":"EHolderAID","said":"ECredSAID123"}`, + presentBody: fixture(t, "present-202.json"), authStatus: http.StatusOK, - authBody: `{"aid":"EHolderAID","lei":"5493001KJTIIGC8Y1R17","role":"OOR"}`, + authBody: fixture(t, "authorizations-200-credential.json"), } v := newVerifierFor(t, s) res, err := v.Present(context.Background(), validCESR) @@ -208,7 +235,7 @@ func TestVerifierPresentPendingAuthorization(t *testing.T) { // Presentation accepted but authorization still processing → PENDING. s := &vleiServer{ presentStatus: http.StatusOK, - presentBody: `{"aid":"EHolderAID","said":"ECredSAID123"}`, + presentBody: fixture(t, "present-202.json"), authStatus: http.StatusNotFound, } v := newVerifierFor(t, s) @@ -226,10 +253,11 @@ func TestVerifierPresentPendingAuthorization(t *testing.T) { func TestVerifierRequestShapes(t *testing.T) { s := &vleiServer{ presentStatus: http.StatusAccepted, - presentBody: `{"aid":"EHolderAID","said":"ECredSAID123"}`, + presentBody: fixture(t, "present-202.json"), authStatus: http.StatusOK, - authBody: `{"lei":"5493001KJTIIGC8Y1R17"}`, + authBody: fixture(t, "authorizations-200-credential.json"), verifyStatus: http.StatusAccepted, + verifyBody: fixture(t, "signature-verify-202.json"), } v := newVerifierFor(t, s) @@ -332,9 +360,20 @@ func TestVerifierPresentFailures(t *testing.T) { func TestVerifierAuthorization(t *testing.T) { ctx := context.Background() t.Run("authorized", func(t *testing.T) { - v := newVerifierFor(t, &vleiServer{authStatus: http.StatusOK, authBody: `{"lei":"L1"}`}) - auth, err := v.Authorization(ctx, "EAID") - if err != nil || !auth.Authorized || auth.LEI != "L1" { + // Recorded 0.1.5 credential-login 200: {aid, said, lei, role, msg}. + // The adapter reads `lei`; the extra fields must not perturb it. + v := newVerifierFor(t, &vleiServer{authStatus: http.StatusOK, authBody: fixture(t, "authorizations-200-credential.json")}) + auth, err := v.Authorization(ctx, "EHolderAID") + if err != nil || !auth.Authorized || auth.LEI != "5493001KJTIIGC8Y1R17" { + t.Fatalf("auth=%+v err=%v", auth, err) + } + }) + t.Run("unknown AID unauthorized (recorded 401 body)", func(t *testing.T) { + // Recorded 0.1.5 401: {"msg":"unknown AID: …"}. 401/404 → not + // authorized, not an error; the non-2xx body is not consumed. + v := newVerifierFor(t, &vleiServer{authStatus: http.StatusUnauthorized, authBody: fixture(t, "authorizations-401-unknown.json")}) + auth, err := v.Authorization(ctx, "EHolderAID") + if err != nil || auth.Authorized { t.Fatalf("auth=%+v err=%v", auth, err) } }) @@ -351,11 +390,14 @@ func TestVerifierAuthorization(t *testing.T) { t.Fatalf("want LEI_VERIFIER_UNAVAILABLE, got %v", err) } }) - // A 200 carrying no LEI (empty body or {}) must fail closed: an empty - // LEI reads downstream as the noop waiver of the AID↔LEI binding, so - // returning {Authorized:true, LEI:""} would silently degrade the - // production verifier to noop semantics. Mirror the empty-AID guard. - for _, body := range []string{"", "{}", `{"lei":""}`} { + // A 200 carrying no LEI must fail closed: an empty LEI reads downstream + // as the noop waiver of the AID↔LEI binding, so returning + // {Authorized:true, LEI:""} would silently degrade the production + // verifier to noop semantics. Mirror the empty-AID guard. The first + // three bodies are synthetic edges; the last is the RECORDED 0.1.5 + // AID-only-login 200, which carries `lei: null` — the real shape that + // triggers this guard (a valid AID account with no bound credential). + for _, body := range []string{"", "{}", `{"lei":""}`, fixture(t, "authorizations-200-aid-only.json")} { t.Run("200 without LEI unavailable", func(t *testing.T) { v := newVerifierFor(t, &vleiServer{authStatus: http.StatusOK, authBody: body}) if _, err := v.Authorization(ctx, "EAID"); !isCode(err, "LEI_VERIFIER_UNAVAILABLE") { @@ -374,12 +416,23 @@ func TestVerifierAuthorization(t *testing.T) { func TestVerifierVerifySignature(t *testing.T) { ctx := context.Background() t.Run("verifies", func(t *testing.T) { - v := newVerifierFor(t, &vleiServer{verifyStatus: http.StatusAccepted}) + // Recorded 0.1.5 202: {"msg":"Signature Valid","code":3}. The adapter + // maps on status; serving the real body proves it ignores the + // unmodeled `code` field rather than choking on it. + v := newVerifierFor(t, &vleiServer{verifyStatus: http.StatusAccepted, verifyBody: fixture(t, "signature-verify-202.json")}) ok, err := v.VerifySignature(ctx, "EAID", "input", "0Bsig") if err != nil || !ok { t.Fatalf("ok=%v err=%v", ok, err) } }) + t.Run("invalid (recorded 401 body)", func(t *testing.T) { + // Recorded 0.1.5 401: {"msg":…,"code":1} → non-verifying false. + v := newVerifierFor(t, &vleiServer{verifyStatus: http.StatusUnauthorized, verifyBody: fixture(t, "signature-verify-401.json")}) + ok, err := v.VerifySignature(ctx, "EAID", "input", "0Bsig") + if err != nil || ok { + t.Fatalf("ok=%v err=%v", ok, err) + } + }) // 401: bad signature; 400: malformed input; 404: AID unknown to the // verifier's KEL — all non-verifying signatures, never outages. for _, code := range []int{http.StatusUnauthorized, http.StatusBadRequest, http.StatusNotFound} { diff --git a/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/PROVENANCE.md b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/PROVENANCE.md new file mode 100644 index 0000000..745afef --- /dev/null +++ b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/PROVENANCE.md @@ -0,0 +1,58 @@ +# vlei-verifier 0.1.5 contract fixtures + +Recorded response bodies for the three vlei-verifier endpoints the +`leiverifier.Verifier` adapter speaks. They are the SINGLE SOURCE OF TRUTH +for the verifier's response shapes: the `vleiServer` harness in +`leiverifier_test.go` serves these bytes verbatim on every happy path +(via the `fixture()` loader), so the whole suite is a CI-runnable +stand-in verified against the real 0.1.5 contract rather than against +what we assume the service returns. A field-name / structural drift on a +version bump changes the re-derived fixture and fails the matching test +**loudly** instead of silently. (Only deliberately-malformed or +edge-shaped bodies — missing fields, junk JSON — stay inline in the test; +those are synthetic by design and have no real counterpart to record.) + +## Provenance + +Derived from the vlei-verifier source at the exact commit the demo +docker-compose builds (`scripts/demo/vlei/docker-compose.yml`, +SHA-pinned build context): + +- Repo: `github.com/GLEIF-IT/vlei-verifier` +- Commit: `e742b65b085bb41b9fa25e9ef04dc3cf0644b297` (the `0.1.5` tag) +- File: `src/verifier/core/verifying.py` + +These are **derived from source**, not captured from live traffic. They +reproduce the JSON shapes the handlers emit (`json.dumps(dict(...))`), so +they catch field-name / structural drift. They do NOT capture runtime-only +quirks (field ordering, incidental extra keys, header casing) — a live +capture would be strictly stronger. Re-derive (or re-capture) on every +version bump; the diff in this directory is the loud signal. + +## Fixtures + +| File | Endpoint | Status | Source (`verifying.py`) | +|---|---|---|---| +| `present-202.json` | `PUT /presentations/{said}` (CREDENTIAL) | 202 | `on_put` L500–506: `dict(creds=json.dumps(creds), aid=aid, msg=info)` | +| `authorizations-200-credential.json` | `GET /authorizations/{aid}` (cred login) | 200 | `_process_cred_auth` L659–665: `dict(aid, said, lei, role, msg)` | +| `authorizations-200-aid-only.json` | `GET /authorizations/{aid}` (AID-only login) | 200 | `_process_aid_auth` L631–637: `lei=None, role=None` | +| `authorizations-401-unknown.json` | `GET /authorizations/{aid}` (unknown AID) | 401 | `on_get` L720: `dict(msg=f"unknown AID: {aid}")` | +| `signature-verify-202.json` | `POST /signature/verify` (valid) | 202 | `on_post` L939: `dict(msg="Signature Valid", code=3)` | +| `signature-verify-401.json` | `POST /signature/verify` (bad sig) | 401 | `on_post` L916–918: `dict(msg=..., code=1)` | + +Notes: + +- `present-202.json` `creds` is abbreviated to `"[]"`. The real value is + `json.dumps(creds)` — a large cloned-credential array serialized to a + JSON *string*. The adapter reads only `aid`, so the abbreviation does + not affect the contract under test; it keeps the fixture legible. +- `authorizations-200-aid-only.json` carries `lei: null`. This is the + AID-only login path (a valid AID account with no bound credential). The + adapter must fail closed on an empty LEI — an authorized-but-LEI-less + 200 must NOT be mistaken for a credential-bound authorization — so this + fixture pins that fail-closed behavior against the real shape that + triggers it. +- The request the adapter *sends* (`signer_aid` / `signature` / + `non_prefixed_digest`, the `application/json+cesr` content type, the + path composition) is pinned separately by `TestVerifierRequestShapes`; + `verifying.py` `on_post` L878–880 is the upstream side of that contract. diff --git a/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-200-aid-only.json b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-200-aid-only.json new file mode 100644 index 0000000..4c50f61 --- /dev/null +++ b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-200-aid-only.json @@ -0,0 +1 @@ +{"aid": "EHolderAID", "said": "EHolderAID", "lei": null, "role": null, "msg": "AID EHolderAID has a valid AID login account"} diff --git a/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-200-credential.json b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-200-credential.json new file mode 100644 index 0000000..e919b8e --- /dev/null +++ b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-200-credential.json @@ -0,0 +1 @@ +{"aid": "EHolderAID", "said": "ECredSAID123", "lei": "5493001KJTIIGC8Y1R17", "role": "EBA Data Submitter", "msg": "AID EHolderAID w/ lei 5493001KJTIIGC8Y1R17 has valid login account"} diff --git a/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-401-unknown.json b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-401-unknown.json new file mode 100644 index 0000000..505811a --- /dev/null +++ b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/authorizations-401-unknown.json @@ -0,0 +1 @@ +{"msg": "unknown AID: EHolderAID"} diff --git a/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/present-202.json b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/present-202.json new file mode 100644 index 0000000..049a21e --- /dev/null +++ b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/present-202.json @@ -0,0 +1 @@ +{"creds": "[]", "aid": "EHolderAID", "msg": "Credential ECredSAID123 presented for EHolderAID is cryptographically valid"} diff --git a/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/signature-verify-202.json b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/signature-verify-202.json new file mode 100644 index 0000000..6898daa --- /dev/null +++ b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/signature-verify-202.json @@ -0,0 +1 @@ +{"msg": "Signature Valid", "code": 3} diff --git a/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/signature-verify-401.json b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/signature-verify-401.json new file mode 100644 index 0000000..7911abe --- /dev/null +++ b/internal/adapter/leiverifier/testdata/vlei-verifier-0.1.5/signature-verify-401.json @@ -0,0 +1 @@ +{"msg": "signature 0 invalid or wasn't signed by EHolderAID", "code": 1} diff --git a/scripts/demo/vlei/docker-compose.yml b/scripts/demo/vlei/docker-compose.yml index 2263820..4af530c 100644 --- a/scripts/demo/vlei/docker-compose.yml +++ b/scripts/demo/vlei/docker-compose.yml @@ -133,7 +133,12 @@ services: # the bundled verifier-config-docker-local.json, which already targets # our witness-demo + vlei-server hostnames. build: - context: https://github.com/GLEIF-IT/vlei-verifier.git#0.1.5 + # SHA-pinned, not tag-pinned: a git tag is mutable, and up.sh's + # `--build` re-resolves the ref on every run, so a moved `0.1.5` + # tag would silently change what every developer builds. This SHA + # IS the 0.1.5 tag (github.com/GLEIF-IT/vlei-verifier, resolved via + # `git ls-remote … refs/tags/0.1.5`); re-pin deliberately on a bump. + context: https://github.com/GLEIF-IT/vlei-verifier.git#e742b65b085bb41b9fa25e9ef04dc3cf0644b297 dockerfile: images/verifier.dockerfile image: ans-vlei-verifier:0.1.5 container_name: ans-vlei-verifier