Skip to content

Commit f4e0619

Browse files
feat(ra): make identityCsrPEM optional on agent registration (#33)
* feat(ra): make identityCsrPEM optional on agent registration Agents may now register without an identity CSR on both the V1 and V2 lanes. When identityCsrPEM is supplied, behavior is unchanged: the RA issues an identity certificate from it at verify-acme. When omitted, the agent registers with no identity certificate, drives through the lifecycle to ACTIVE normally, and emits TL events carrying empty identity certs. - domain: NewRegistration accepts a nil identity CSR. - service: RegisterAgent skips CSR validation/persistence when omitted; VerifyACME treats a missing pending identity CSR as a no-op rather than an inconsistent-state error. - no-add-later guard: an ACTIVE agent that registered without an identity CSR cannot obtain one via SubmitIdentityCSR (409 IDENTITY_CSR_NOT_PERMITTED); it must register a new version instead. - spec: identityCsrPEM removed from the required list; docsui regenerated. Tests follow the repo convention (unit-under-test + concern): - domain/agent_test.go pins nil-CSR acceptance. - service: RegisterAgent cases in registration_errors_test.go; new lifecycle_test.go covers VerifyACME/VerifyDNS V1+V2 wire shapes and the SubmitIdentityCSR guard. - handler: V2 202 + V1 reaches-ACTIVE parity, plus the 409 add-later path. Replaces the stale TestV1Register_MissingIdentityCSR_422. Signed-off-by: James Hateley <jhateley@godaddy.com> * refactor(ra): address code review feedback on identity CSR submission Flatten SubmitIdentityCSR with an early-return AGENT_NOT_ACTIVE guard, removing the now-redundant nested status check. Reword the no-identity-CSR event tests: identityCert/identityCerts/ validIdentityCerts are all omitempty, so the fields are absent on the wire when empty rather than serialized as null/empty arrays. Comments and failure messages no longer assert a wire shape the encoder cannot produce. Signed-off-by: James Hateley <jhateley@godaddy.com> * docs(ra): drop implementation-plan references from test comments Remove AC-* acceptance-criteria identifiers and plan-relative framing ("RED gauge", "the optional-identity-CSR feature", "as before the optional path was introduced") from test comments. These pointed at an implementation plan rather than describing behavior; reword them to state what each test verifies in product terms. Signed-off-by: James Hateley <jhateley@godaddy.com> --------- Signed-off-by: James Hateley <jhateley@godaddy.com>
1 parent 102fc27 commit f4e0619

10 files changed

Lines changed: 492 additions & 61 deletions

File tree

‎internal/adapter/docsui/openapi/ra.yaml‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1065,12 +1065,16 @@ components:
10651065
type: string
10661066
identityCsrPEM:
10671067
type: string
1068+
description: >-
1069+
Optional. When supplied, the RA issues an identity certificate
1070+
from this CSR at verify-acme. When omitted, the agent registers
1071+
without an identity certificate and cannot add one later — it
1072+
must register a new version instead.
10681073
required:
10691074
- agentDisplayName
10701075
- version
10711076
- agentHost
10721077
- endpoints
1073-
- identityCsrPEM
10741078

10751079
AgentRevocationRequest:
10761080
type: object

‎internal/domain/agent.go‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,6 @@ func NewRegistration(
144144
if len(endpoints) == 0 {
145145
return nil, NewValidationError("MISSING_ENDPOINTS", "at least one endpoint is required")
146146
}
147-
if identityCSR == nil {
148-
return nil, NewValidationError("MISSING_IDENTITY_CSR", "identityCsrPEM is required")
149-
}
150147

151148
// Validate endpoints against the agent host.
152149
eps := AgentEndpoints{AgentID: agentID, Endpoints: endpoints}

‎internal/domain/agent_test.go‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,29 @@ func TestNewRegistration_Valid(t *testing.T) {
4545
assert.IsType(t, AgentRegisteredEvent{}, reg.PendingEvents[0])
4646
}
4747

48+
// TestNewRegistration_NilIdentityCSR_Allowed verifies that registering
49+
// without an identity CSR is allowed and leaves IdentityCSR nil.
50+
func TestNewRegistration_NilIdentityCSR_Allowed(t *testing.T) {
51+
ansName, err := NewAnsName(mustSemVer(1, 0, 0), "agent.example.com")
52+
require.NoError(t, err)
53+
endpoints := []AgentEndpoint{
54+
{Protocol: ProtocolMCP, AgentURL: "https://agent.example.com/mcp"},
55+
}
56+
cert := &ByocServerCertificate{
57+
SubjectCommonName: "agent.example.com",
58+
ValidFromTimestamp: time.Now().Add(-time.Hour),
59+
ValidToTimestamp: time.Now().Add(24 * time.Hour),
60+
}
61+
62+
reg, err := NewRegistration(
63+
"agent-uuid", "owner-1", ansName, "My Agent", "desc",
64+
endpoints, cert, nil, time.Now(),
65+
)
66+
require.NoError(t, err, "nil identity CSR must be allowed")
67+
require.NotNil(t, reg)
68+
assert.Nil(t, reg.IdentityCSR, "registration must have nil IdentityCSR")
69+
}
70+
4871
func TestNewRegistration_Validations(t *testing.T) {
4972
validName, _ := NewAnsName(mustSemVer(1, 0, 0), "a.b.com")
5073
validCSR := NewIdentityCSR("c", "x", time.Now())
@@ -68,7 +91,6 @@ func TestNewRegistration_Validations(t *testing.T) {
6891
{"display name too long", "a", "o", validName, strings.Repeat("x", 65), "", validEndpoints, nil, &validCSR, "DISPLAY_NAME_TOO_LONG"},
6992
{"description too long", "a", "o", validName, "", strings.Repeat("x", 151), validEndpoints, nil, &validCSR, "DESCRIPTION_TOO_LONG"},
7093
{"no endpoints", "a", "o", validName, "", "", nil, nil, &validCSR, "MISSING_ENDPOINTS"},
71-
{"missing csr", "a", "o", validName, "", "", validEndpoints, nil, nil, "MISSING_IDENTITY_CSR"},
7294
}
7395
for _, tc := range tests {
7496
t.Run(tc.name, func(t *testing.T) {

‎internal/ra/handler/lifecycle_test.go‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,84 @@ func TestSubmitIdentityCSR_RejectedOnNonActiveAgent(t *testing.T) {
304304
}
305305
}
306306

307+
// registerAgentNoIdentityCSR is the no-identity-CSR analogue of
308+
// registerAgent: it POSTs a V2 registration that omits identityCsrPEM
309+
// (server CSR still supplied) and returns the new agentId.
310+
func (f *handlerFixture) registerAgentNoIdentityCSR(t *testing.T, ownerID, host, version string) string {
311+
t.Helper()
312+
body, _ := json.Marshal(map[string]any{
313+
"agentDisplayName": "No identity CSR",
314+
"version": version,
315+
"agentHost": host,
316+
"endpoints": []map[string]any{
317+
{"agentUrl": "https://" + host + "/mcp", "protocol": "MCP", "transports": []string{"SSE"}},
318+
},
319+
// identityCsrPEM intentionally omitted.
320+
"serverCsrPEM": newTestServerCSR(t, host),
321+
})
322+
rec := f.request(t, http.MethodPost, "/v2/ans/agents", bytes.NewReader(body), f.asOwner(ownerID))
323+
if rec.Code != http.StatusAccepted {
324+
t.Fatalf("register %s without identity CSR: status=%d body=%s", host, rec.Code, rec.Body)
325+
}
326+
var resp struct {
327+
AgentID string `json:"agentId"`
328+
Status string `json:"status"`
329+
}
330+
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
331+
t.Fatalf("parse register response: %v", err)
332+
}
333+
if resp.AgentID == "" {
334+
t.Fatal("register returned empty agentId")
335+
}
336+
if resp.Status != "PENDING_VALIDATION" {
337+
t.Fatalf("status: got %q want PENDING_VALIDATION", resp.Status)
338+
}
339+
return resp.AgentID
340+
}
341+
342+
// TestRegister_NoIdentityCSR_Accepted covers the V2 optional
343+
// identity-CSR path at the HTTP layer: a registration omitting
344+
// identityCsrPEM is accepted with 202 + PENDING_VALIDATION (asserted in
345+
// the helper). The agent simply gets no identity certificate.
346+
func TestRegister_NoIdentityCSR_Accepted(t *testing.T) {
347+
t.Parallel()
348+
fx := newHandlerFixture(t)
349+
if id := fx.registerAgentNoIdentityCSR(t, "alice", "no-id-csr.example.com", "1.0.0"); id == "" {
350+
t.Fatal("expected a non-empty agentId")
351+
}
352+
}
353+
354+
// TestSubmitIdentityCSR_NoIdentityCSR_Rejected covers the no-add-later
355+
// guard at the HTTP layer: an ACTIVE agent that registered without an
356+
// identity CSR cannot obtain one via POST .../certificates/identity. It
357+
// must register a new version instead — the route returns 409 with code
358+
// IDENTITY_CSR_NOT_PERMITTED.
359+
func TestSubmitIdentityCSR_NoIdentityCSR_Rejected(t *testing.T) {
360+
t.Parallel()
361+
fx := newHandlerFixture(t)
362+
host := "no-add-later.example.com"
363+
agentID := fx.registerAgentNoIdentityCSR(t, "alice", host, "1.0.0")
364+
fx.activateAgent(t, "alice", agentID)
365+
366+
csrPEM := newTestCSR(t, "ans://v1.0.0."+host)
367+
body, _ := json.Marshal(map[string]any{"csrPEM": csrPEM})
368+
rec := fx.request(t, http.MethodPost,
369+
"/v2/ans/agents/"+agentID+"/certificates/identity",
370+
bytes.NewReader(body), fx.asOwner("alice"))
371+
if rec.Code != http.StatusConflict {
372+
t.Fatalf("want 409, got %d body=%s", rec.Code, rec.Body)
373+
}
374+
var prob struct {
375+
Code string `json:"code"`
376+
}
377+
if err := json.Unmarshal(rec.Body.Bytes(), &prob); err != nil {
378+
t.Fatalf("parse problem details: %v", err)
379+
}
380+
if prob.Code != "IDENTITY_CSR_NOT_PERMITTED" {
381+
t.Fatalf("code: got %q want IDENTITY_CSR_NOT_PERMITTED", prob.Code)
382+
}
383+
}
384+
307385
func TestSubmitServerCSR_AcceptsRegardlessOfStatus(t *testing.T) {
308386
t.Parallel()
309387
fx := newHandlerFixture(t)

‎internal/ra/handler/v1registration_test.go‎

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -227,25 +227,57 @@ func TestV1Register_BothOrNeither_422(t *testing.T) {
227227
}
228228
}
229229

230-
// TestV1Register_MissingIdentityCSR_422 confirms the handler rejects
231-
// requests without `identityCsrPEM` (required field per the
232-
// reference V1 API spec).
233-
func TestV1Register_MissingIdentityCSR_422(t *testing.T) {
230+
// TestV1Register_NoIdentityCSR_ReachesActive covers the V1 lane: a
231+
// registration that omits `identityCsrPEM` (server CSR still present) is
232+
// accepted with 202 and drives through verify-acme → verify-dns to
233+
// ACTIVE. `identityCsrPEM` is optional on both lanes; the agent simply
234+
// gets no identity certificate.
235+
func TestV1Register_NoIdentityCSR_ReachesActive(t *testing.T) {
234236
t.Parallel()
235237
fx := newHandlerFixture(t)
238+
host := "no-id-csr.example.com"
236239
reqBody, _ := json.Marshal(map[string]any{
237-
"agentDisplayName": "No CSR",
240+
"agentDisplayName": "No identity CSR",
238241
"version": "1.0.0",
239-
"agentHost": "agent.example.com",
242+
"agentHost": host,
240243
"endpoints": []map[string]any{
241-
{"agentUrl": "https://agent.example.com/mcp", "protocol": "MCP"},
244+
{"agentUrl": "https://" + host + "/mcp", "protocol": "MCP"},
242245
},
243-
// identityCsrPEM intentionally omitted.
246+
// identityCsrPEM intentionally omitted; server CSR still supplied.
247+
"serverCsrPEM": newTestServerCSR(t, host),
244248
})
245249
rec := fx.request(t, http.MethodPost, "/v1/agents/register",
246250
bytes.NewReader(reqBody), fx.asOwner("alice"))
247-
if rec.Code != http.StatusUnprocessableEntity {
248-
t.Fatalf("status: got %d want 422; body=%s", rec.Code, rec.Body)
251+
if rec.Code != http.StatusAccepted {
252+
t.Fatalf("register without identity CSR: got %d want 202; body=%s", rec.Code, rec.Body)
253+
}
254+
var reg struct {
255+
AgentID string `json:"agentId"`
256+
}
257+
if err := json.Unmarshal(rec.Body.Bytes(), &reg); err != nil {
258+
t.Fatalf("parse register response: %v", err)
259+
}
260+
261+
// Drive the V1 lifecycle to ACTIVE.
262+
if rec := fx.request(t, http.MethodPost, "/v1/agents/"+reg.AgentID+"/verify-acme", nil, fx.asOwner("alice")); rec.Code != http.StatusAccepted {
263+
t.Fatalf("verify-acme: got %d body=%s", rec.Code, rec.Body)
264+
}
265+
if rec := fx.request(t, http.MethodPost, "/v1/agents/"+reg.AgentID+"/verify-dns", nil, fx.asOwner("alice")); rec.Code != http.StatusAccepted {
266+
t.Fatalf("verify-dns: got %d body=%s", rec.Code, rec.Body)
267+
}
268+
269+
rec = fx.request(t, http.MethodGet, "/v1/agents/"+reg.AgentID, nil, fx.asOwner("alice"))
270+
if rec.Code != http.StatusOK {
271+
t.Fatalf("detail: got %d body=%s", rec.Code, rec.Body)
272+
}
273+
var detail struct {
274+
AgentStatus string `json:"agentStatus"`
275+
}
276+
if err := json.Unmarshal(rec.Body.Bytes(), &detail); err != nil {
277+
t.Fatalf("parse detail: %v", err)
278+
}
279+
if detail.AgentStatus != "ACTIVE" {
280+
t.Fatalf("agentStatus: got %q want ACTIVE", detail.AgentStatus)
249281
}
250282
}
251283

‎internal/ra/service/lifecycle.go‎

Lines changed: 67 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,30 @@ func (s *RegistrationService) SubmitIdentityCSR(ctx context.Context, agentID, cs
155155
if err != nil {
156156
return "", err
157157
}
158+
159+
if reg.Status != domain.StatusActive {
160+
return "", domain.NewInvalidStateError(
161+
"AGENT_NOT_ACTIVE",
162+
fmt.Sprintf("Agent must be ACTIVE to submit identity CSR. Current status: %s", reg.Status),
163+
)
164+
}
165+
166+
// No-add-later guard: an agent that registered without an identity
167+
// CSR can never obtain one via rotation — it must register a new
168+
// version instead. Identity-bearing agents have a signed identity
169+
// certificate by the time they reach ACTIVE (issued at verify-acme);
170+
// non identity-bearing agents never do.
171+
idCerts, cerr := s.certs.FindIdentityCertificatesByAgent(ctx, agentID)
172+
if cerr != nil {
173+
return "", cerr
174+
}
175+
if len(idCerts) == 0 {
176+
return "", domain.NewConflictError(
177+
"IDENTITY_CSR_NOT_PERMITTED",
178+
"agent was registered without an identity CSR; register a new version to obtain an identity certificate",
179+
)
180+
}
181+
158182
if err := s.validator.ValidateIdentityCSR(ctx, csrPEM, reg.AnsName.String()); err != nil {
159183
return "", domain.NewValidationError("INVALID_IDENTITY_CSR", err.Error())
160184
}
@@ -301,37 +325,43 @@ func (s *RegistrationService) VerifyACME(ctx context.Context, agentID string, in
301325
}
302326
}
303327

304-
// 2. Sign the identity CSR. Issuance + signing are CPU-bound and
305-
// do not touch the DB; we run them outside the tx so the
306-
// SQLite write lock isn't held during work that doesn't need
307-
// it. Same pattern below for the server CSR path.
328+
// 2. Sign the identity CSR (when the agent registered with one).
329+
// Issuance + signing are CPU-bound and do not touch the DB; we
330+
// run them outside the tx so the SQLite write lock isn't held
331+
// during work that doesn't need it. Same pattern below for the
332+
// server CSR path.
333+
//
334+
// A nil pending identity CSR is NOT an error: an agent may
335+
// register without an identity CSR (identityCsrPEM optional), in
336+
// which case there is no identity certificate to issue and we
337+
// leave signedID/storedID nil so the tx below skips persisting
338+
// them. The agent still advances to PENDING_DNS / ACTIVE.
308339
identityCSR, err := s.certs.FindLatestPendingCSRByType(ctx, agentID, domain.CSRTypeIdentity)
309340
if err != nil {
310341
return nil, err
311342
}
312-
if identityCSR == nil {
313-
return nil, domain.NewInvalidStateError(
314-
"MISSING_IDENTITY_CSR",
315-
"no pending identity CSR for agent — aggregate in inconsistent state",
316-
)
317-
}
318-
issuedID, err := s.identityCA.IssueIdentityCertificate(ctx, identityCSR.CSRContent, reg.AnsName.String())
319-
if err != nil {
320-
return nil, domain.NewInternalError("CERT_ISSUE_FAILED", "failed to issue identity cert", err)
321-
}
322-
signedID, err := identityCSR.MarkSigned(now)
323-
if err != nil {
324-
return nil, err
325-
}
326-
reg.IdentityCSR = &signedID
327-
storedID := &domain.StoredCertificate{
328-
CSRID: identityCSR.CSRID,
329-
CertificateType: domain.CertTypeIdentity,
330-
CertificatePEM: issuedID.CertPEM,
331-
ChainPEM: issuedID.ChainPEM,
332-
Status: domain.CertStatusValid,
333-
IssueTimestamp: issuedID.IssuedAt,
334-
ExpirationTimestamp: issuedID.ExpiresAt,
343+
var signedID *domain.AgentCSR
344+
var storedID *domain.StoredCertificate
345+
if identityCSR != nil {
346+
issuedID, err := s.identityCA.IssueIdentityCertificate(ctx, identityCSR.CSRContent, reg.AnsName.String())
347+
if err != nil {
348+
return nil, domain.NewInternalError("CERT_ISSUE_FAILED", "failed to issue identity cert", err)
349+
}
350+
signed, err := identityCSR.MarkSigned(now)
351+
if err != nil {
352+
return nil, err
353+
}
354+
reg.IdentityCSR = &signed
355+
signedID = &signed
356+
storedID = &domain.StoredCertificate{
357+
CSRID: identityCSR.CSRID,
358+
CertificateType: domain.CertTypeIdentity,
359+
CertificatePEM: issuedID.CertPEM,
360+
ChainPEM: issuedID.ChainPEM,
361+
Status: domain.CertStatusValid,
362+
IssueTimestamp: issuedID.IssuedAt,
363+
ExpirationTimestamp: issuedID.ExpiresAt,
364+
}
335365
}
336366

337367
// 3. CSR-path server cert: same shape — sign + validate up
@@ -361,13 +391,16 @@ func (s *RegistrationService) VerifyACME(ctx context.Context, agentID string, in
361391
// Pre-tx, agent.Save committed first and a downstream failure
362392
// left a PENDING_DNS agent with no associated cert rows.
363393
if err := s.uow.Run(ctx, func(txCtx context.Context) error {
364-
// SaveCSR upserts on csr_id so the same row flips
365-
// PENDING → SIGNED.
366-
if err := s.certs.SaveCSR(txCtx, reg.AgentID, &signedID); err != nil {
367-
return err
368-
}
369-
if err := s.certs.SaveIdentityCertificate(txCtx, reg.AgentID, storedID); err != nil {
370-
return err
394+
// Identity cert: persisted only when the agent registered with
395+
// an identity CSR. SaveCSR upserts on csr_id so the same row
396+
// flips PENDING → SIGNED.
397+
if signedID != nil {
398+
if err := s.certs.SaveCSR(txCtx, reg.AgentID, signedID); err != nil {
399+
return err
400+
}
401+
if err := s.certs.SaveIdentityCertificate(txCtx, reg.AgentID, storedID); err != nil {
402+
return err
403+
}
371404
}
372405
if byocCert != nil {
373406
if err := s.byoc.Save(txCtx, reg.AgentID, byocCert); err != nil {

0 commit comments

Comments
 (0)