From 9c68d3b17b1e92eff725083ed8f0242f5694a459 Mon Sep 17 00:00:00 2001 From: Connor Snitker Date: Wed, 15 Jul 2026 09:31:12 -0500 Subject: [PATCH] fix(ra): seal the gate-verified ACME method into domainValidation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The domain-control challenge gate is any-of — either the DNS-01 TXT record or the HTTP-01 resource satisfies it — but both AGENT_REGISTERED event builders hardcoded domainValidation to "ACME-DNS-01", so an agent whose domain control was proven via HTTP-01 was sealed into the append-only log with the wrong method token. The gate result could not simply be read at emit time: the event is built in a later HTTP call (verify-dns) where the verified type is out of scope, and CertificateOrder had no field to carry it. Persist the satisfied challenge type on the order when the gate passes (migration 012, cert_order_verified_challenge), and derive the sealed token from it in both the V1 and V2 builders. Rows that predate recording omit the field — the schemas mark it optional in both lanes, and an append-only log must never carry a fabricated method token. Fixes #61 Signed-off-by: Connor Snitker --- internal/adapter/store/sqlite/agent.go | 16 +- .../012_cert_order_verified_challenge.sql | 17 ++ .../store/sqlite/order_persistence_test.go | 14 +- internal/domain/order.go | 39 +++- internal/domain/order_test.go | 19 ++ internal/ra/service/lifecycle.go | 24 +- internal/ra/service/order_flow_test.go | 211 ++++++++++++++++++ internal/ra/service/v1event.go | 13 +- 8 files changed, 344 insertions(+), 9 deletions(-) create mode 100644 internal/adapter/store/sqlite/migrations/012_cert_order_verified_challenge.sql diff --git a/internal/adapter/store/sqlite/agent.go b/internal/adapter/store/sqlite/agent.go index 93b86bf..7eb9252 100644 --- a/internal/adapter/store/sqlite/agent.go +++ b/internal/adapter/store/sqlite/agent.go @@ -51,6 +51,7 @@ type agentRow struct { CertOrderRef sql.NullString `db:"cert_order_ref"` CertOrderState sql.NullString `db:"cert_order_state"` CertOrderChallenges sql.NullString `db:"cert_order_challenges"` + CertOrderVerified sql.NullString `db:"cert_order_verified_challenge"` CreatedAtMs int64 `db:"created_at_ms"` UpdatedAtMs int64 `db:"updated_at_ms"` } @@ -81,7 +82,7 @@ func (r agentRow) toDomain() (*domain.AgentRegistration, error) { } order, err := certOrderFromRow( r.CertOrderRef, r.CertOrderState, r.CertOrderChallenges, - r.ACMEDNS01Token, r.ACMEChallengeExpiresAtMs, + r.CertOrderVerified, r.ACMEDNS01Token, r.ACMEChallengeExpiresAtMs, ) if err != nil { return nil, err @@ -143,7 +144,7 @@ func encodeDiscoveryProfiles(profiles []domain.DiscoveryProfile) string { // falling back to synthesizing a self-issued single-DNS-01 order from // the legacy token columns for rows written before migration 008. func certOrderFromRow( - ref, state, challengesJSON sql.NullString, + ref, state, challengesJSON, verifiedChallenge sql.NullString, legacyDNS01 sql.NullString, legacyExpiresMs sql.NullInt64, ) (domain.CertificateOrder, error) { var order domain.CertificateOrder @@ -153,6 +154,9 @@ func certOrderFromRow( } order.OrderRef = ref.String order.State = domain.OrderState(state.String) + // NULL (rows written before migration 012, or a gate that has + // not passed yet) decodes to the empty type — "not recorded". + order.VerifiedChallenge = domain.ChallengeType(verifiedChallenge.String) if legacyExpiresMs.Valid { order.ExpiresAt = msToTime(legacyExpiresMs.Int64) } @@ -180,6 +184,7 @@ type certOrderColumns struct { ref any state any challenges any + verified any expiresMs any } @@ -197,6 +202,7 @@ func certOrderToRow(order domain.CertificateOrder) (certOrderColumns, error) { ref: nullableString(order.OrderRef), state: string(order.State), challenges: string(encoded), + verified: nullableString(string(order.VerifiedChallenge)), expiresMs: nullableMs(order.ExpiresAt), }, nil } @@ -223,10 +229,11 @@ func (s *AgentStore) Save(ctx context.Context, agent *domain.AgentRegistration) registration_timestamp_ms, last_renewal_timestamp_ms, supersedes_registration_id, cert_order_ref, cert_order_state, cert_order_challenges, + cert_order_verified_challenge, acme_challenge_expires_at_ms, discovery_profiles, created_at_ms, updated_at_ms - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` res, err := s.db.extx(ctx).ExecContext(ctx, q, agent.AgentID, agent.OwnerID, @@ -240,6 +247,7 @@ func (s *AgentStore) Save(ctx context.Context, agent *domain.AgentRegistration) nullableMs(agent.Details.LastRenewalTimestamp), nullableInt64(agent.SupersedesRegistrationID), order.ref, order.state, order.challenges, + order.verified, order.expiresMs, nullableString(encodeDiscoveryProfiles(agent.DiscoveryProfiles)), now, now, @@ -265,6 +273,7 @@ func (s *AgentStore) Save(ctx context.Context, agent *domain.AgentRegistration) cert_order_ref = ?, cert_order_state = ?, cert_order_challenges = ?, + cert_order_verified_challenge = ?, acme_challenge_expires_at_ms = ?, discovery_profiles = ?, updated_at_ms = ? @@ -276,6 +285,7 @@ func (s *AgentStore) Save(ctx context.Context, agent *domain.AgentRegistration) nullableMs(agent.Details.LastRenewalTimestamp), nullableInt64(agent.SupersedesRegistrationID), order.ref, order.state, order.challenges, + order.verified, order.expiresMs, nullableString(encodeDiscoveryProfiles(agent.DiscoveryProfiles)), now, diff --git a/internal/adapter/store/sqlite/migrations/012_cert_order_verified_challenge.sql b/internal/adapter/store/sqlite/migrations/012_cert_order_verified_challenge.sql new file mode 100644 index 0000000..7b89a49 --- /dev/null +++ b/internal/adapter/store/sqlite/migrations/012_cert_order_verified_challenge.sql @@ -0,0 +1,17 @@ +-- 012_cert_order_verified_challenge.sql +-- Persist which challenge type satisfied the domain-control gate. +-- +-- The gate (verify-acme) is any-of — DNS-01 TXT record or HTTP-01 +-- resource — but the terminal AGENT_REGISTERED attestation that +-- reports the validation method (`attestations.domainValidation`) is +-- built in a later call (verify-dns), where the gate result is no +-- longer in scope. Before this column the event builders hardcoded +-- "ACME-DNS-01", sealing a wrong method token into the append-only +-- log for HTTP-01-validated agents (issue #61). +-- +-- NULL means "not recorded": either the gate has not passed yet, or +-- the row predates this migration. Event builders omit the field for +-- such rows rather than fabricate a method. + +ALTER TABLE agent_registrations + ADD COLUMN cert_order_verified_challenge TEXT; diff --git a/internal/adapter/store/sqlite/order_persistence_test.go b/internal/adapter/store/sqlite/order_persistence_test.go index e7e6e1d..d951ba0 100644 --- a/internal/adapter/store/sqlite/order_persistence_test.go +++ b/internal/adapter/store/sqlite/order_persistence_test.go @@ -84,11 +84,20 @@ func TestAgentStore_CertOrderRoundTrip(t *testing.T) { if !ok || http01.HTTPPath != "/.well-known/acme-challenge/tok-http" { t.Errorf("http01 challenge lost fields: %+v", http01) } + // Before the gate passes nothing is recorded — the NULL column + // must decode as "not recorded", not as some default method. + if got.CertOrder.VerifiedChallenge != "" { + t.Errorf("verifiedChallenge before gate pass: got %q want empty", got.CertOrder.VerifiedChallenge) + } - // State updates persist through the UPDATE path too. + // State updates persist through the UPDATE path too — including + // the gate-recorded verified challenge type (the write that + // happens on verify-acme when the HTTP-01 artifact satisfied the + // any-of gate). if err := got.CertOrder.MarkIssuing(); err != nil { t.Fatal(err) } + got.CertOrder.RecordVerifiedChallenge(domain.ChallengeTypeHTTP01) if err := NewAgentStore(db).Save(context.Background(), got); err != nil { t.Fatal(err) } @@ -99,6 +108,9 @@ func TestAgentStore_CertOrderRoundTrip(t *testing.T) { if again.CertOrder.State != domain.OrderStateIssuing { t.Errorf("updated state: got %q want ISSUING", again.CertOrder.State) } + if again.CertOrder.VerifiedChallenge != domain.ChallengeTypeHTTP01 { + t.Errorf("verifiedChallenge: got %q want %q", again.CertOrder.VerifiedChallenge, domain.ChallengeTypeHTTP01) + } } // TestAgentStore_ZeroOrderStaysZero: registrations without an order diff --git a/internal/domain/order.go b/internal/domain/order.go index ac5ef10..0c5e96f 100644 --- a/internal/domain/order.go +++ b/internal/domain/order.go @@ -28,6 +28,24 @@ func (t ChallengeType) IsValid() bool { } } +// ACMEMethodToken maps the challenge type to the ACME +// validation-method token the TL attestation schemas enumerate for +// `attestations.domainValidation` ("ACME-DNS-01" / "ACME-HTTP-01"). +// Empty for unrecognized types — callers tag the field omitempty, so +// an unknown method is omitted from the sealed event rather than +// fabricated: the TL is append-only and a wrong method token can +// never be corrected. +func (t ChallengeType) ACMEMethodToken() string { + switch t { + case ChallengeTypeDNS01: + return "ACME-DNS-01" + case ChallengeTypeHTTP01: + return "ACME-HTTP-01" + default: + return "" + } +} + // Challenge is a single domain-control challenge the domain owner must // satisfy by publishing an artifact (a DNS TXT record or an HTTP // resource) in the zone or site they control. Challenges are relayed @@ -150,6 +168,16 @@ type CertificateOrder struct { State OrderState `json:"state,omitempty"` Challenges []Challenge `json:"challenges,omitempty"` ExpiresAt time.Time `json:"expiresAt,omitzero"` + + // VerifiedChallenge is the challenge type whose artifact satisfied + // the domain-control gate (the gate is any-of, so exactly one type + // is recorded — the first found published). Set when the gate + // passes and persisted with the order, because the terminal + // AGENT_REGISTERED attestation that reports the validation method + // is built in a later call (verify-dns) where the gate result is + // no longer in scope. Empty on orders that predate recording and + // on orders whose gate has not passed yet. + VerifiedChallenge ChallengeType `json:"verifiedChallenge,omitempty"` } // NewSelfIssuedOrder builds the BYOC-path validation order from a @@ -169,7 +197,16 @@ func NewSelfIssuedOrder(dns01Token, http01Token string, expiresAt time.Time) Cer // IsZero reports whether the order is unset — true for registrations // that predate order persistence. func (o *CertificateOrder) IsZero() bool { - return o.OrderRef == "" && o.State == "" && len(o.Challenges) == 0 && o.ExpiresAt.IsZero() + return o.OrderRef == "" && o.State == "" && len(o.Challenges) == 0 && + o.ExpiresAt.IsZero() && o.VerifiedChallenge == "" +} + +// RecordVerifiedChallenge pins the challenge type that satisfied the +// domain-control gate onto the order, so the validation method +// survives to the later call that seals it into the terminal +// attestation. +func (o *CertificateOrder) RecordVerifiedChallenge(t ChallengeType) { + o.VerifiedChallenge = t } // ChallengeOfType returns the first challenge of the given type. diff --git a/internal/domain/order_test.go b/internal/domain/order_test.go index 4d26aa1..65f2bcd 100644 --- a/internal/domain/order_test.go +++ b/internal/domain/order_test.go @@ -15,6 +15,15 @@ func TestChallengeType_IsValid(t *testing.T) { assert.False(t, ChallengeType("").IsValid()) } +func TestChallengeType_ACMEMethodToken(t *testing.T) { + assert.Equal(t, "ACME-DNS-01", ChallengeTypeDNS01.ACMEMethodToken()) + assert.Equal(t, "ACME-HTTP-01", ChallengeTypeHTTP01.ACMEMethodToken()) + // Unknown types map to empty so omitempty drops the field — the + // sealed attestation must never carry a fabricated method token. + assert.Empty(t, ChallengeType("TLS_ALPN_01").ACMEMethodToken()) + assert.Empty(t, ChallengeType("").ACMEMethodToken()) +} + func TestChallenge_EffectiveDNSRecordName(t *testing.T) { // RFC 8555 default when the provider didn't override. c := Challenge{Type: ChallengeTypeDNS01, Token: "tok"} @@ -81,11 +90,21 @@ func TestCertificateOrder_IsZero(t *testing.T) { {CertificateOrder{State: OrderStatePending}, false}, {CertificateOrder{Challenges: []Challenge{{}}}, false}, {CertificateOrder{ExpiresAt: time.Now()}, false}, + {CertificateOrder{VerifiedChallenge: ChallengeTypeHTTP01}, false}, } { assert.Equal(t, tc.want, tc.order.IsZero(), "%+v", tc.order) } } +func TestCertificateOrder_RecordVerifiedChallenge(t *testing.T) { + o := NewSelfIssuedOrder("dns-tok", "http-tok", time.Now().Add(time.Hour)) + assert.Empty(t, o.VerifiedChallenge, "gate not passed yet — nothing recorded") + + o.RecordVerifiedChallenge(ChallengeTypeHTTP01) + assert.Equal(t, ChallengeTypeHTTP01, o.VerifiedChallenge) + assert.Equal(t, "ACME-HTTP-01", o.VerifiedChallenge.ACMEMethodToken()) +} + func TestCertificateOrder_ChallengeOfType_Missing(t *testing.T) { o := CertificateOrder{Challenges: []Challenge{{Type: ChallengeTypeDNS01, Token: "t"}}} _, ok := o.ChallengeOfType(ChallengeTypeHTTP01) diff --git a/internal/ra/service/lifecycle.go b/internal/ra/service/lifecycle.go index b728ae1..3951a30 100644 --- a/internal/ra/service/lifecycle.go +++ b/internal/ra/service/lifecycle.go @@ -498,7 +498,10 @@ func (s *RegistrationService) VerifyACME(ctx context.Context, agentID string, in // // Returns the challenge types found published so ACME-style issuers // can answer exactly the satisfied challenge (answering an -// unsatisfied one would invalidate the authorization). +// unsatisfied one would invalidate the authorization). A passing gate +// also records the satisfied type on reg.CertOrder — the terminal +// attestation's `domainValidation` method token is derived from it in +// a later call (verify-dns), so it must survive on the aggregate. // // NOTE: zero-value orders (registrations predating order persistence) // skip the gate — no challenge was ever issued to the operator, so @@ -536,6 +539,17 @@ func (s *RegistrationService) gateOrderChallenges( } verified, verr := s.verifyChallengeArtifacts(ctx, reg.FQDN(), order.Challenges) if len(verified) > 0 { + // Record which challenge type satisfied the gate on the order + // itself. The terminal AGENT_REGISTERED attestation reports the + // validation method, but it is built in a later call + // (verify-dns) where this gate result is out of scope — without + // persisting it here the event builder could only guess. + reg.CertOrder.RecordVerifiedChallenge(verified[0]) + log.Info(). + Str("agentId", reg.AgentID). + Str("fqdn", reg.FQDN()). + Str("challengeType", string(verified[0])). + Msg("domain-control challenge gate passed") return verified, nil } if verr != nil { @@ -1122,8 +1136,14 @@ func (s *RegistrationService) buildAgentRegisteredEvent( // spec — the min(notAfter) across attested certs. inner.ExpiresAt = agentCertExpiry(identityCerts, byocCert, now) + // `domainValidation` is the method that actually satisfied the + // domain-control gate, recorded on the order at gate-pass time + // (gateOrderChallenges). Empty — and therefore omitted, never + // guessed — for registrations that predate recording: the log is + // append-only, so a fabricated method token could never be + // corrected. inner.Attestations = &event.Attestations{ - DomainValidation: "ACME-DNS-01", + DomainValidation: reg.CertOrder.VerifiedChallenge.ACMEMethodToken(), DNSRecordsProvisioned: provisioned, IdentityCerts: idCertInfos, ServerCerts: serverCertInfos, diff --git a/internal/ra/service/order_flow_test.go b/internal/ra/service/order_flow_test.go index 66a34be..d56b1bc 100644 --- a/internal/ra/service/order_flow_test.go +++ b/internal/ra/service/order_flow_test.go @@ -2,6 +2,7 @@ package service_test import ( "context" + "encoding/json" "errors" "strings" "testing" @@ -13,6 +14,8 @@ import ( "github.com/godaddy/ans/internal/domain" "github.com/godaddy/ans/internal/port" "github.com/godaddy/ans/internal/ra/service" + event "github.com/godaddy/ans/internal/tl/event" + eventv1 "github.com/godaddy/ans/internal/tl/event/v1" ) // errStrayFinalize is returned by refOnlyIssuer when handed an empty @@ -1148,11 +1151,219 @@ func (r *refOnlyIssuer) GetCACertificate(ctx context.Context) (string, error) { return r.real.GetCACertificate(ctx) } +// challengeBlindDNSVerifier simulates an operator who never published +// the DNS-01 TXT record but did publish everything else: the +// challenge gate's DOMAIN_VALIDATION probe reports unpublished, while +// the production record set (the verify-dns leg) verifies live. Used +// to force the any-of gate down the HTTP-01 path end-to-end. +type challengeBlindDNSVerifier struct{} + +func (challengeBlindDNSVerifier) VerifyRecords( + _ context.Context, _ string, expected []domain.ExpectedDNSRecord, +) (*port.VerificationResult, error) { + results := make([]port.RecordVerification, len(expected)) + all := true + for i, r := range expected { + found := r.Purpose != "DOMAIN_VALIDATION" + if !found && r.Required { + all = false + } + results[i] = port.RecordVerification{Record: r, Found: found} + if found { + results[i].Actual = r.Value + } + } + return &port.VerificationResult{AllRequired: all, Results: results}, nil +} + +// claimAgentRegistered claims the outbox and returns the canonical +// inner-event bytes of the first AGENT_REGISTERED row carrying the +// given schema version. Both lanes share the eventType token, so the +// probe decode works for either envelope shape. +func claimAgentRegistered(t *testing.T, fx *regFixture, schemaVersion string) []byte { + t.Helper() + rows, err := fx.outboxStore.Claim(context.Background(), 10) + if err != nil { + t.Fatalf("Claim: %v", err) + } + for _, row := range rows { + if row.SchemaVersion != schemaVersion { + continue + } + var p service.OutboxPayload + if err := json.Unmarshal(row.PayloadJSON, &p); err != nil { + t.Fatalf("unmarshal OutboxPayload: %v", err) + } + var probe struct { + EventType string `json:"eventType"` + } + if err := json.Unmarshal(p.InnerEventCanonical, &probe); err != nil { + t.Fatalf("unmarshal inner event: %v", err) + } + if probe.EventType == string(event.TypeAgentRegistered) { + return p.InnerEventCanonical + } + } + t.Fatalf("no AGENT_REGISTERED event with schema version %s in the outbox", schemaVersion) + return nil +} + +// driveToActive registers the fixture request and drives it through +// verify-acme → verify-dns with the given service, returning the +// agentID. The schemaVersion selects the TL lane. +func driveToActive(t *testing.T, fx *regFixture, svc *service.RegistrationService, schemaVersion string) string { + t.Helper() + req := fx.req + req.SchemaVersion = schemaVersion + if _, err := svc.RegisterAgent(context.Background(), req); err != nil { + t.Fatalf("register: %v", err) + } + agentID := anyAgentID(t, fx, fx.req.AnsName) + in := service.VerifyInput{SchemaVersion: schemaVersion} + if _, err := svc.VerifyACME(context.Background(), agentID, in); err != nil { + t.Fatalf("verify-acme: %v", err) + } + if _, err := svc.VerifyDNS(context.Background(), agentID, in); err != nil { + t.Fatalf("verify-dns: %v", err) + } + return agentID +} + +// TestVerifyDNS_HTTP01Gate_SealsACMEHTTP01 is the regression test for +// issue #61: an agent whose domain control was proven via the HTTP-01 +// resource (the DNS-01 TXT record was never published) must be sealed +// into the append-only log with `domainValidation: "ACME-HTTP-01"` — +// not the "ACME-DNS-01" constant the V2 builder previously hardcoded. +// Also pins the structural half of the fix: the satisfied type is +// persisted on the order at verify-acme time, because the event is +// built in the later verify-dns call. +func TestVerifyDNS_HTTP01Gate_SealsACMEHTTP01(t *testing.T) { + t.Parallel() + fx := newRegFixture(t) + svc := rebuildWithIssuer(fx, fx.serverCA, challengeBlindDNSVerifier{}, staticHTTPVerifier{ok: true}) + + req := fx.req + if _, err := svc.RegisterAgent(context.Background(), req); err != nil { + t.Fatalf("register: %v", err) + } + agentID := anyAgentID(t, fx, fx.req.AnsName) + if _, err := svc.VerifyACME(context.Background(), agentID, service.VerifyInput{}); err != nil { + t.Fatalf("verify-acme: %v", err) + } + + // The satisfied challenge type must survive the call boundary: + // persisted with the order, not just threaded into FinalizeOrder. + stored, err := fx.agents.FindByAgentID(context.Background(), agentID) + if err != nil { + t.Fatal(err) + } + if stored.CertOrder.VerifiedChallenge != domain.ChallengeTypeHTTP01 { + t.Fatalf("persisted verified challenge: got %q want %q", + stored.CertOrder.VerifiedChallenge, domain.ChallengeTypeHTTP01) + } + + if _, err := svc.VerifyDNS(context.Background(), agentID, service.VerifyInput{}); err != nil { + t.Fatalf("verify-dns: %v", err) + } + var ev event.Event + if err := json.Unmarshal(claimAgentRegistered(t, fx, event.SchemaVersion), &ev); err != nil { + t.Fatalf("unmarshal inner V2 event: %v", err) + } + if ev.Attestations == nil { + t.Fatal("V2 AGENT_REGISTERED must carry attestations") + } + if ev.Attestations.DomainValidation != "ACME-HTTP-01" { + t.Fatalf("domainValidation: got %q want ACME-HTTP-01", ev.Attestations.DomainValidation) + } +} + +// TestVerifyDNS_HTTP01Gate_SealsACMEHTTP01_V1Lane is the V1-lane half +// of the issue #61 regression: the V1 envelope builder read the same +// hardcoded constant, so an HTTP-01-validated agent registered through +// the V1 API was equally mis-attested. +func TestVerifyDNS_HTTP01Gate_SealsACMEHTTP01_V1Lane(t *testing.T) { + t.Parallel() + fx := newRegFixture(t) + svc := rebuildWithIssuer(fx, fx.serverCA, challengeBlindDNSVerifier{}, staticHTTPVerifier{ok: true}) + + driveToActive(t, fx, svc, "V1") + + var ev eventv1.Event + if err := json.Unmarshal(claimAgentRegistered(t, fx, eventv1.SchemaVersion), &ev); err != nil { + t.Fatalf("unmarshal inner V1 event: %v", err) + } + if ev.Attestations == nil { + t.Fatal("V1 AGENT_REGISTERED must carry attestations") + } + if ev.Attestations.DomainValidation != "ACME-HTTP-01" { + t.Fatalf("domainValidation: got %q want ACME-HTTP-01", ev.Attestations.DomainValidation) + } +} + +// TestVerifyDNS_DNS01Gate_SealsACMEDNS01 pins the complementary path: +// when the DNS-01 TXT record satisfied the gate (the quickstart noop +// verifier accepts it, and DNS-01 is probed first), the sealed method +// token is ACME-DNS-01 — now because it was verified, not hardcoded. +func TestVerifyDNS_DNS01Gate_SealsACMEDNS01(t *testing.T) { + t.Parallel() + fx := newRegFixture(t) + + driveToActive(t, fx, fx.svc, "") + + var ev event.Event + if err := json.Unmarshal(claimAgentRegistered(t, fx, event.SchemaVersion), &ev); err != nil { + t.Fatalf("unmarshal inner V2 event: %v", err) + } + if ev.Attestations == nil || ev.Attestations.DomainValidation != "ACME-DNS-01" { + t.Fatalf("domainValidation: got %+v want ACME-DNS-01", ev.Attestations) + } +} + +// TestVerifyDNS_UnrecordedGateMethod_OmitsDomainValidation covers rows +// that predate verified-challenge recording (pre-migration-012 rows +// mid-flow during a deploy): with no recorded method the builder must +// OMIT domainValidation from the sealed attestation rather than +// fabricate one — the log is append-only and a wrong method token can +// never be corrected. Omission is valid: the field is optional in +// both lanes' attestation schemas. +func TestVerifyDNS_UnrecordedGateMethod_OmitsDomainValidation(t *testing.T) { + t.Parallel() + fx := newRegFixture(t) + + if _, err := fx.svc.RegisterAgent(context.Background(), fx.req); err != nil { + t.Fatalf("register: %v", err) + } + agentID := anyAgentID(t, fx, fx.req.AnsName) + if _, err := fx.svc.VerifyACME(context.Background(), agentID, service.VerifyInput{}); err != nil { + t.Fatalf("verify-acme: %v", err) + } + + // Simulate a row written before recording existed: strip the + // recorded method the gate just persisted. + stored, err := fx.agents.FindByAgentID(context.Background(), agentID) + if err != nil { + t.Fatal(err) + } + stored.CertOrder.VerifiedChallenge = "" + if err := fx.agents.Save(context.Background(), stored); err != nil { + t.Fatal(err) + } + + if _, err := fx.svc.VerifyDNS(context.Background(), agentID, service.VerifyInput{}); err != nil { + t.Fatalf("verify-dns: %v", err) + } + raw := claimAgentRegistered(t, fx, event.SchemaVersion) + if strings.Contains(string(raw), `"domainValidation"`) { + t.Fatalf("domainValidation must be omitted when the gate method was never recorded; canonical event: %s", raw) + } +} + // Compile-time interface checks for the fakes and the ACME adapter. var ( _ port.ServerCertificateIssuer = (*asyncIssuer)(nil) _ port.ServerCertificateIssuer = (*cert.ACMEIssuer)(nil) _ port.DNSVerifier = failingDNSVerifier{} + _ port.DNSVerifier = challengeBlindDNSVerifier{} _ port.HTTPChallengeVerifier = staticHTTPVerifier{} _ = cert.ServerSelfCA{} ) diff --git a/internal/ra/service/v1event.go b/internal/ra/service/v1event.go index 1dd8030..4597b3a 100644 --- a/internal/ra/service/v1event.go +++ b/internal/ra/service/v1event.go @@ -146,7 +146,12 @@ func v1RevokedCertList(certs []*domain.StoredCertificate) ([]eventv1.Certificate // - `dnsRecordsProvisioned` as map[name]data (V1 lossy shape — a // V2 typed-array lands in a single entry per name; collisions // use last-wins). -// - `domainValidation` = "ACME-DNS-01" (reference constant). +// - `domainValidation` = the ACME method that satisfied the +// domain-control gate ("ACME-DNS-01" / "ACME-HTTP-01"), recorded +// on the certificate order at gate-pass time. Omitted for +// registrations that predate recording. (The reference emits a +// constant "ACME-DNS-01" here; its schema enumerates all three +// method tokens, so the faithful value is shape-compatible.) // - `identityCert` singleton — the primary active identity cert. // - `validIdentityCerts[]` rotation array — every currently valid // identity cert (includes the primary). Present even with one @@ -233,9 +238,13 @@ func (s *RegistrationService) buildAgentRegisteredV1Event( // min(notAfter) across attested identity + server certs. inner.ExpiresAt = agentCertExpiry(identityCerts, byocCert, now) + // `domainValidation` mirrors the V2 builder: the method that + // actually satisfied the gate, recorded on the order at gate-pass + // time; omitted (never guessed) for registrations that predate + // recording. inner.Attestations = &eventv1.Attestations{ DNSRecordsProvisioned: dnsMap, - DomainValidation: "ACME-DNS-01", + DomainValidation: reg.CertOrder.VerifiedChallenge.ACMEMethodToken(), IdentityCert: primaryIdentity, ServerCert: primaryServer, ValidIdentityCerts: validIdentity,