Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions internal/adapter/store/sqlite/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
}
Expand Down Expand Up @@ -180,6 +184,7 @@ type certOrderColumns struct {
ref any
state any
challenges any
verified any
expiresMs any
}

Expand All @@ -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
}
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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 = ?
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
14 changes: 13 additions & 1 deletion internal/adapter/store/sqlite/order_persistence_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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
Expand Down
39 changes: 38 additions & 1 deletion internal/domain/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
19 changes: 19 additions & 0 deletions internal/domain/order_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand Down Expand Up @@ -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)
Expand Down
24 changes: 22 additions & 2 deletions internal/ra/service/lifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down
Loading