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/cmd/ans-ra/main.go b/cmd/ans-ra/main.go index 71f150a..011d5dd 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" @@ -154,11 +155,20 @@ 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) logger.Info(). Str("resolver", cfg.Identity.Resolver.Type). + Str("vleiVerifier", cfg.VLEI.Type). 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). @@ -214,7 +224,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, @@ -584,3 +594,25 @@ 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); "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": + opts := []leiverifier.VerifierOption{leiverifier.WithLogger(logger)} + if cfg.VLEI.PresentTimeout > 0 { + opts = append(opts, leiverifier.WithTimeout(cfg.VLEI.PresentTimeout)) + } + return leiverifier.NewVerifier(cfg.VLEI.BaseURL, opts...) + case "noop": + return leiverifier.NewNoop() + default: // "off" + return nil + } +} diff --git a/config/ra-local.yaml b/config/ra-local.yaml index a9257fc..ebae721 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; 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 + # 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 4e30cd1..b4a8ea1 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 @@ -957,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: @@ -1071,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: @@ -1093,6 +1123,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. @@ -1152,14 +1188,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: @@ -2155,16 +2191,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: | @@ -2195,6 +2253,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 @@ -2227,11 +2294,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 @@ -2245,8 +2321,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..8b46794 --- /dev/null +++ b/internal/adapter/leiverifier/leiverifier_test.go @@ -0,0 +1,580 @@ +package leiverifier + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/rs/zerolog" + + "github.com/godaddy/ans/internal/domain" +) + +// 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"}}` + +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.Fatalf("Present: %v", err) + } + if res.SubjectAID != "EHolderAID" || res.LEI != "5493001KJTIIGC8Y1R17" || res.Status != "AUTHORIZED" { + t.Fatalf("present result: %+v", res) + } +} + +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() + 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 != "EEcrSub" || res.LEI != "875500ELOZEL05BVXV37" { + t.Fatalf("present result: %+v", res) + } +} + +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("Present: %v", err) + } + if res.SubjectAID != "EHolderAID" { + t.Fatalf("want subject AID EHolderAID, got %q", res.SubjectAID) + } +} + +func TestNoopPresentFailures(t *testing.T) { + ctx := context.Background() + n := NewNoop() + cases := []struct { + name string + cesr string + }{ + {"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) { + if _, err := n.Present(ctx, tc.cesr); !isCode(err, "LEI_PRESENTATION_INVALID") { + t.Fatalf("want LEI_PRESENTATION_INVALID, got %v", err) + } + }) + } +} + +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) + } +} + +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) + } + // 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", ""}, + } + 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) + } + }) + } +} + +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 + presentBody string + authStatus int + authBody string + verifyStatus int + verifyBody string + + 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, r *http.Request) { + s.record(r) + w.WriteHeader(s.presentStatus) + _, _ = w.Write([]byte(s.presentBody)) + }) + 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, r *http.Request) { + s.record(r) + w.WriteHeader(s.verifyStatus) + _, _ = w.Write([]byte(s.verifyBody)) + }) + 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` + +// 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()) + t.Cleanup(srv.Close) + return NewVerifier(srv.URL+"/", WithHTTPClient(srv.Client()), WithTimeout(2*time.Second), WithMaxBodyBytes(1<<16)) +} + +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: fixture(t, "present-202.json"), + authStatus: http.StatusOK, + authBody: fixture(t, "authorizations-200-credential.json"), + } + 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: fixture(t, "present-202.json"), + 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) + } +} + +// 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: fixture(t, "present-202.json"), + authStatus: http.StatusOK, + authBody: fixture(t, "authorizations-200-credential.json"), + verifyStatus: http.StatusAccepted, + verifyBody: fixture(t, "signature-verify-202.json"), + } + 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{}) + 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) { + // 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) + } + }) + 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) + } + }) + // 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") { + 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") { + 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) { + // 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} { + 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"}, + // 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. + {"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) + } + }) + } +} + +// 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") + } +} + +// 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/noop.go b/internal/adapter/leiverifier/noop.go new file mode 100644 index 0000000..a192d9c --- /dev/null +++ b/internal/adapter/leiverifier/noop.go @@ -0,0 +1,98 @@ +// Package leiverifier provides the two port.LEIControlVerifier +// adapters behind the lei (vLEI) identifier kind: +// +// - 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). +// +// 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" + + "github.com/godaddy/ans/internal/domain" + "github.com/godaddy/ans/internal/port" +) + +// Noop is the quickstart vLEI verifier. It never dials anywhere. +// +// 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. +// +// What this preserves and what it waives, stated precisely: +// +// - 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{} } + +// 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) { + 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: leaf.A.I, + LEI: leaf.A.LEI, + Status: port.StatusAuthorized, + }, nil +} + +// 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 !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 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. +var _ port.LEIControlVerifier = (*Noop)(nil) 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/internal/adapter/leiverifier/verifier.go b/internal/adapter/leiverifier/verifier.go new file mode 100644 index 0000000..aa0e448 --- /dev/null +++ b/internal/adapter/leiverifier/verifier.go @@ -0,0 +1,537 @@ +package leiverifier + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" + "strings" + "time" + + "github.com/rs/zerolog" + + "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 + logger zerolog.Logger +} + +// 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 + } + } +} + +// 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 { + v := &Verifier{ + baseURL: strings.TrimRight(baseURL, "/"), + client: &http.Client{Timeout: 5 * time.Second}, + maxBodyBytes: 1 << 20, + logger: zerolog.Nop(), + } + 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, "present") + 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: + 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") + } + + // 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 + } + presStatus := port.StatusPending + if auth.Authorized { + presStatus = port.StatusAuthorized + } + return port.PresentationResult{ + SubjectAID: pres.AID, + LEI: auth.LEI, + Status: presStatus, + }, 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, "authorize") + if err != nil { + return port.AuthorizationResult{}, err + } + 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. + return port.AuthorizationResult{Authorized: false}, nil + default: + v.logFailure("authorize", "verifier returned an unexpected status", status, nil) + 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, "verify-signature") + 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: + v.logFailure("verify-signature", "verifier returned an unexpected status", status, nil) + 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, 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 + // 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 { + 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. + // 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 { + 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). +func (v *Verifier) unavailable(op string) error { + 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 +// 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 +} + +// 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`) + +// 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. +func scanACDCChain(cesr string) ([]acdcFrame, map[string]struct{}) { + var frames []acdcFrame + referenced := make(map[string]struct{}) + offset := 0 + for { + loc := acdcFrameMarker.FindStringIndex(cesr[offset:]) + if loc == nil { + break + } + start := offset + loc[0] + obj, end := balancedJSONObject(cesr, start) + if obj == "" { + offset = end // unbalanced tail: jump to end, no O(N²) byte rescan + continue + } + offset = end + var frame acdcFrame + if err := json.Unmarshal([]byte(obj), &frame); err != nil || frame.D == "" { + continue + } + frames = append(frames, frame) + if len(frame.E) > 0 { + collectEdgeNodes(frame.E, referenced) + } + } + 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 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 +// 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 + } + // 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 { + if k == "n" { + if s, ok := val.(string); ok && s != "" { + seen[s] = struct{}{} + } + } + walk(val, depth+1) + } + case []any: + for _, el := range t { + walk(el, depth+1) + } + } + } + walk(doc, 0) +} + +// 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..a569db5 100644 --- a/internal/adapter/store/sqlite/identity.go +++ b/internal/adapter/store/sqlite/identity.go @@ -25,6 +25,8 @@ type identityRow struct { Status string `db:"status"` 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"` @@ -34,20 +36,22 @@ 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, 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, - 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) @@ -85,14 +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, 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, @@ -106,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, + v.ProofMethod, v.PendingValue, subjectAID, pendingSubjectAID, nonce, expiresAt, consumedAt, verifiedAt, v.CreatedAt.UnixMilli(), v.UpdatedAt.UnixMilli(), ) @@ -309,6 +322,13 @@ func (s *IdentityStore) StageChallenge( if !v.Challenge.ExpiresAt.IsZero() { expires = sql.NullInt64{Int64: v.Challenge.ExpiresAt.UnixMilli(), 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 SET challenge_nonce = ?, @@ -316,12 +336,13 @@ func (s *IdentityStore) StageChallenge( challenge_consumed_at_ms = NULL, challenge_claimed_at_ms = NULL, pending_value = ?, + 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, v.UpdatedAt.UnixMilli(), + v.Challenge.Nonce, expires, v.PendingValue, pendingSubjectAID, v.UpdatedAt.UnixMilli(), v.IdentityID, string(expectedStatus), expectedNonce, expectedNonce, staleBefore.UnixMilli()) if err != nil { @@ -363,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/011_identity_subject_aid.sql b/internal/adapter/store/sqlite/migrations/011_identity_subject_aid.sql new file mode 100644 index 0000000..cc806fa --- /dev/null +++ b/internal/adapter/store/sqlite/migrations/011_identity_subject_aid.sql @@ -0,0 +1,19 @@ +-- 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; + +-- 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/config/config.go b/internal/config/config.go index f2e48a2..abbee51 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -172,6 +172,26 @@ 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" 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 + // 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 +279,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 +439,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 +519,30 @@ func validateCAServer(s *CAServer) error { return nil } +// 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 "off", "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 'off', '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..56a0304 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: "off"}, Keys: Keys{ Type: "file", File: &KeysFile{Path: "./data/ra/keys"}, diff --git a/internal/domain/identity.go b/internal/domain/identity.go index 85e0dc0..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" ) @@ -85,13 +85,24 @@ 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. // 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 + // 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 @@ -157,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 @@ -385,6 +395,29 @@ func (v *VerifiedIdentity) StageRotation(rawValue string, now time.Time) error { return nil } +// 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.PendingSubjectAID = aid + v.UpdatedAt = now.UTC() + return nil +} + // CompleteVerification applies a successful control proof: // // - PENDING_CONTROL → VERIFIED (first proof; seals IDENTITY_VERIFIED) @@ -413,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() @@ -432,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 88000f9..f0d46cc 100644 --- a/internal/domain/identity_test.go +++ b/internal/domain/identity_test.go @@ -308,3 +308,41 @@ func TestInferIdentifierKind_DIDWebSegmentRejections(t *testing.T) { t.Fatalf("multi-segment: %v %v %v", kind, canonical, err) } } + +func TestStageSubjectAID(t *testing.T) { + v := newPendingIdentity(t, "5493001KJTIIGC8Y1R17") + + // Empty AID is rejected and mutates nothing. + 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.PendingSubjectAID != "" || v.EffectiveSubjectAID() != "" { + t.Fatalf("subject AID should remain unset, got %q", v.EffectiveSubjectAID()) + } + + // 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.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.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 new file mode 100644 index 0000000..9c7e31b --- /dev/null +++ b/internal/port/leiverifier.go @@ -0,0 +1,77 @@ +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 +// §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 PresentationStatus +} + +// 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 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. 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 + // 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..976c1be 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 @@ -98,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")) @@ -107,7 +125,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 +133,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) { @@ -122,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")) @@ -131,7 +160,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 @@ -147,13 +176,14 @@ 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")) 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 @@ -260,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")) @@ -306,13 +337,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: 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 e336aa0..e535fd4 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" @@ -26,6 +27,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" @@ -92,6 +94,7 @@ func newIdentityHTTPFixture(t *testing.T) *identityHTTPFixture { agents, didresolver.NewNoopResolver(), okSealer{}, + leiverifier.NewNoop(), db, ).WithChallengeTTL(30 * time.Minute) @@ -308,6 +311,102 @@ 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 +// 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) { diff --git a/internal/ra/service/identity.go b/internal/ra/service/identity.go index e83d2c8..389bedc 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 port.PresentationStatus } // 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, @@ -216,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 { @@ -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, false, opt) } // challenge mints a fresh nonce on the identity, runs the kind's @@ -321,7 +339,30 @@ 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 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 { + 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. expectedStatus := identity.Status expectedNonce := "" @@ -350,10 +391,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 +406,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 } @@ -399,6 +437,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_lei_test.go b/internal/ra/service/identity_lei_test.go new file mode 100644 index 0000000..12c6dd7 --- /dev/null +++ b/internal/ra/service/identity_lei_test.go @@ -0,0 +1,298 @@ +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.drainSealed(t) + if len(rows) != 1 { + t.Fatalf("outbox rows: %d", len(rows)) + } + inner := fx.decodeSealed(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[:] +} + +// 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() + + 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..6ea24cc 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) } } @@ -501,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) @@ -1422,6 +1465,7 @@ func TestNilSealerFailsClosed(t *testing.T) { sqlite.NewAgentStore(db), didresolver.NewNoopResolver(), nil, // no sealer + leiverifier.NewNoop(), db, ) ctx := context.Background() @@ -1519,6 +1563,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)) diff --git a/internal/ra/service/identitykinds.go b/internal/ra/service/identitykinds.go index 19f7bad..7609108 100644 --- a/internal/ra/service/identitykinds.go +++ b/internal/ra/service/identitykinds.go @@ -62,6 +62,63 @@ 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 +} + +// 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). +// +// 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 != "" + 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); +// 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), discovered by type-assertion on the controlVerifier so +// kinds without one (did:web, did:key) grow no dead method. +// +// 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 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 @@ -86,15 +143,21 @@ 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 + // 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{}, } + if leiCtl != nil { + m[domain.KindLEI] = &leiVerifier{v: leiCtl} // absent → IDENTIFIER_KIND_UNSUPPORTED + } + return m } // ----- shared JWS proof machinery ----- diff --git a/internal/ra/service/leiverifier.go b/internal/ra/service/leiverifier.go new file mode 100644 index 0000000..125a7c0 --- /dev/null +++ b/internal/ra/service/leiverifier.go @@ -0,0 +1,160 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "strings" + + "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 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 +// 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 +// 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, + effectiveValue string, + opts RegisterOptions, +) (string, port.PresentationStatus, 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, effectiveValue) { + return "", "", domain.NewValidationError("LEI_MISMATCH", + fmt.Sprintf("presented credential authorizes LEI %q, not %q", res.LEI, effectiveValue)) + } + return res.SubjectAID, 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) { + aid := identity.EffectiveSubjectAID() + if aid == "" { + return nil, domain.NewInternalError("LEI_SUBJECT_AID_MISSING", + "subject AID was not pinned before challenge", nil) + } + return []ProofChallenge{{Kid: aid, 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.EffectiveSubjectAID() + 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/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. diff --git a/scripts/demo/start.sh b/scripts/demo/start.sh index e265581..f1f1c74 100755 --- a/scripts/demo/start.sh +++ b/scripts/demo/start.sh @@ -206,6 +206,18 @@ identity: type: ${ANS_IDENTITY_RESOLVER:-noop} challenge-ttl: 1h +vlei: + # The lei (vLEI) control verifier behind the "lei" identifier kind. + # "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} + 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..9d1d95d --- /dev/null +++ b/scripts/demo/vlei/README.md @@ -0,0 +1,175 @@ +# vLEI ecosystem + `verify-control` demo + +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 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 `875500ELOZEL05BVXV37`. A genuine vLEI is +needed *only* against the real GLEIF production root — out of scope here. + +## The RA is the single touchpoint for the verifier + +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`) + +| 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` | — | 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**: + +```bash +scripts/demo/vlei/run-vlei.sh # add --down to tear everything down after +``` + +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` +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 +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 +``` + +### 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 → 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. + +### Run stages individually + +```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.** 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` (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. + +**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: + +```bash +curl -X POST http://localhost:7676/root_of_trust/{gleifRootAID} \ + -H 'Content-Type: application/json' \ + -d '{"vlei":"","oobi":""}' +``` + +## Scope + +The `lei` kind on the identity-scoped `/v2/ans/identities` routes: + +- `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. `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..96e9bfb --- /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 +# - holder-state.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 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 + ok "wrote $f" +done + +header "Chain build complete" +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 new file mode 100644 index 0000000..4af530c --- /dev/null +++ b/scripts/demo/vlei/docker-compose.yml @@ -0,0 +1,211 @@ +# 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: + - "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: + 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: + - "127.0.0.1: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: + - "127.0.0.1:3901:3901" + - "127.0.0.1:3902:3902" + - "127.0.0.1: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: + # 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 + 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: + - "127.0.0.1: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/holder-state.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..7710a75 --- /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..0073f57 --- /dev/null +++ b/scripts/demo/vlei/run-vlei.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# +# One-command vLEI verify-control demo — fully standalone. +# +# 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. 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, +# 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. +# +# Usage: +# scripts/demo/vlei/run-vlei.sh [--down] +# +# Flags: +# --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: +# 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 + +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" +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. 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; +# 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 + 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 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" + +# 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 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" +note "vLEI control proven end-to-end with no manual steps." 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..f3420ec --- /dev/null +++ b/scripts/demo/vlei/signify/scripts_ts/build-chain.ts @@ -0,0 +1,465 @@ +// ============================================================================ +// 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/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; +// 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, SignifyClient } 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: SignifyClient, 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(), { signal: 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, { 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); +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 3: 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 }), + }); + 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. + 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}/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/sign-proof.ts b/scripts/demo/vlei/signify/scripts_ts/sign-proof.ts new file mode 100644 index 0000000..aa16535 --- /dev/null +++ b/scripts/demo/vlei/signify/scripts_ts/sign-proof.ts @@ -0,0 +1,67 @@ +// ============================================================================ +// 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. +// ============================================================================ + +// 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 { 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..b45a21b --- /dev/null +++ b/scripts/demo/vlei/signify/scripts_ts/utils.ts @@ -0,0 +1,512 @@ +import { + ready, + SignifyClient, + Tier, + CreateIdentiferArgs, + State, + Operation, + Contact, + Salter, + Serder +} from 'npm:signify-ts@0.3.0-rc1'; + +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_BLUE = '\x1b[94m'; + + // Background colors + static readonly BG_GREEN = '\x1b[42m'; + static readonly BG_YELLOW = '\x1b[43m'; + static readonly BG_BLUE = '\x1b[44m'; + + // 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 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)); +} + +// 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 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('Connecting client with provided passcode (bran) [redacted].'); + + 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: clientState as unknown as State }; + } 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, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); + + if (completedOperation.error) { + throw new Error(`AID creation failed: ${JSON.stringify(completedOperation.error)}`); + } + + const newAidInceptionEvent = completedOperation.response as any; + 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, { signal: 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, { signal: 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, contacts: contact }; + } catch (error) { + console.error(`Failed to resolve OOBI URL "${oobiUrl}":`, 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, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); + + if (completedOperation.error) { + throw new Error(`Credential registry creation failed: ${JSON.stringify(completedOperation.error)}`); + } + + const registrySaid = (completedOperation?.response as any)?.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; + } +} + +/** + * 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, { signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) }); + + if (completedOperation.error) { + throw new Error(`Credential issuance failed: ${JSON.stringify(completedOperation.error)}`); + } + 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}`); + + 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, { signal: 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; + } +} + +/** + * 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). + * @returns {Promise} The first matching unread notification. + */ +export async function waitForAndGetNotification( + client: SignifyClient, + expectedRoute: string +): 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: 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 + } + 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, { signal: 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; + } +} 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..7418bf6 --- /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 / 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 +# 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")/holder-state.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" +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) ----- +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 4e30cd1..b4a8ea1 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 @@ -957,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: @@ -1071,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: @@ -1093,6 +1123,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. @@ -1152,14 +1188,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: @@ -2155,16 +2191,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: | @@ -2195,6 +2253,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 @@ -2227,11 +2294,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 @@ -2245,8 +2321,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