Commit Graph

66 Commits

Author SHA1 Message Date
shankar0123 a0afa7ab6f test(security): TICKET-018 add fuzz tests for command validation and domain parsing
Added Go native fuzz tests (testing/fuzz) for security-critical input validation:

1. FuzzValidateShellCommand in internal/validation/command_fuzz_test.go
   - Tests shell command validation with injection payloads (;, |, &, $, `, etc.)
   - Seed corpus includes valid commands and dangerous metacharacters
   - Ensures function never panics under fuzzing

2. FuzzValidateDomainName in internal/validation/command_fuzz_test.go
   - Tests RFC 1123 domain validation with wildcard support
   - Seed corpus includes SQL injection, path traversal, and malformed domains
   - Ensures function never panics under fuzzing

3. FuzzValidateACMEToken in internal/validation/command_fuzz_test.go
   - Tests base64url token validation
   - Seed corpus includes injection payloads and special characters
   - Ensures function never panics under fuzzing

4. FuzzIsValidRevocationReason in internal/domain/revocation_fuzz_test.go
   - Tests RFC 5280 revocation reason validation
   - Seed corpus includes case variations, injection attempts, and null bytes
   - Ensures function never panics and returns only valid booleans

5. FuzzCRLReasonCode in internal/domain/revocation_fuzz_test.go
   - Tests CRL reason code mapping
   - Validates return codes are within 0-9 range
   - Ensures invalid reasons default to 0 (unspecified)

All fuzz tests follow Go 1.18+ testing/fuzz conventions with seed corpus
for faster discovery of edge cases.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 21:40:49 -04:00
shankar0123 4655f68e87 fix(testing): TICKET-015 replace time.Sleep with channel-based sync in audit tests
The audit middleware records events asynchronously via goroutines. Tests previously
used time.Sleep(50ms) to wait for audit recording, which is unreliable.

Implemented waitableAuditRecorder wrapper that:
- Wraps mockAuditRecorder to intercept RecordAPICall invocations
- Signals via buffered channel when recording completes
- Provides Wait(timeout) method for tests to synchronously wait
- Returns true on successful wait, false on timeout

Replaced all 7 time.Sleep(50ms) calls with recorder.Wait(1*time.Second) calls,
improving test reliability and reducing flakiness.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 21:40:28 -04:00
shankar0123 677c28aeca refactor(api): TICKET-006 replace 18-param RegisterHandlers with HandlerRegistry struct
Replace the 18-parameter RegisterHandlers function signature with a cleaner
HandlerRegistry struct that groups all API handler dependencies. This eliminates
the signature explosion that made the function difficult to read and maintain.

Changes:
- Added HandlerRegistry struct with 18 fields grouping all handler types
- Updated RegisterHandlers to accept a single HandlerRegistry parameter
- Updated all internal handler references to use reg.FieldName syntax
- Updated call sites in cmd/server/main.go and integration tests
- No functional changes, purely structural refactoring

Resolves TICKET-006: RegisterHandlers Signature Explosion
2026-03-27 21:40:21 -04:00
shankar0123 fd6f236a5c fix(security): TICKET-013 filter reserved IP ranges in network scanner
- Added isReservedIP() function to detect loopback, link-local, multicast, broadcast ranges
- Blocks 127.0.0.0/8 (loopback), 169.254.0.0/16 (link-local/cloud metadata), 224.0.0.0/4 (multicast), 255.255.255.255
- Preserves RFC1918 private ranges (10.x, 172.16.x, 192.168.x) for self-hosted scenarios
- Updated expandCIDR() to filter reserved IPs during CIDR expansion
- Updated expandEndpoints() to log warnings when reserved ranges are filtered
- Added 16 comprehensive tests covering loopback, link-local, multicast filtering
- Tests verify private ranges and public IPs are not blocked
- Tests verify single IP filtering and bulk CIDR expansion filtering
2026-03-27 21:36:10 -04:00
shankar0123 200bdf990f fix(quality): TICKET-012 propagate request context instead of context.Background()
- Updated AgentService interface to accept context.Context parameter in all methods
- Replaced context.Background() calls with proper ctx parameter in agent.go
- Updated AgentGroupService interface to accept context.Context parameter
- Replaced context.Background() calls with proper ctx parameter in agent_group.go
- Updated handler methods to pass r.Context() to service methods
- Context now properly propagates through request lifecycle for timeout/cancellation
- Improved request tracing and cancellation behavior
2026-03-27 21:35:22 -04:00
shankar0123 3e5cc86c5a fix(reliability): TICKET-002 add scheduler idempotency guards and graceful shutdown
## Summary

Fixes two critical scheduler reliability issues in certctl:

### TICKET-002 (CRITICAL): Scheduler job idempotency
- Added atomic.Bool guards to all 6 scheduler loops (renewal, job processor, agent health, notifications, short-lived expiry, network scan)
- Uses CompareAndSwap pattern to prevent duplicate execution if previous job is still running
- Logs warning when a tick is skipped due to in-flight work
- Prevents runaway scheduler duplicates and resource exhaustion

### TICKET-011 (MEDIUM): Graceful shutdown
- Added sync.WaitGroup to track in-flight scheduler work
- Each job is wrapped in wg.Add(1)/wg.Done() for lifecycle tracking
- New WaitForCompletion(timeout) method waits for all in-flight work to complete
- Integrates into main.go: after context cancellation, waits up to 30s for jobs to finish before closing DB
- Graceful shutdown ensures no work is lost during server restart/termination

## Changes

**internal/scheduler/scheduler.go:**
- Imports: added "errors", "sync", "sync/atomic"
- Scheduler struct: added 6 atomic.Bool fields (one per loop) + sync.WaitGroup
- All 6 loop functions: spawn goroutines with wg.Add/Done, check atomic guard on each tick, skip tick if already running
- New WaitForCompletion(timeout) method with timeout support
- New ErrSchedulerShutdownTimeout error type

**cmd/server/main.go:**
- After context cancellation and before HTTP shutdown, call sched.WaitForCompletion(30 * time.Second)
- Logs "waiting for scheduler to complete in-flight work" and any errors

**internal/scheduler/scheduler_test.go (new file):**
- Mock services for testing (renewal, job, agent, notification, network scan)
- TestSchedulerIdempotencyGuard: verifies slow job doesn't cause duplicate execution
- TestWaitForCompletionSuccess: verifies graceful shutdown with adequate timeout
- TestWaitForCompletionTimeout: verifies timeout is respected
- TestSchedulerMultipleLoopsIdempotency: verifies all 6 loops respect idempotency
- TestSchedulerGracefulShutdown: end-to-end graceful shutdown flow

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 21:34:07 -04:00
shankar0123 3e3e68fd3a fix(security): TICKET-009 add HTTP timeouts to notifier clients
- Added TestSlack_ClientHasTimeout to verify 10-second timeout
- Added TestTeams_ClientHasTimeout to verify 10-second timeout
- Added TestPagerDuty_ClientHasTimeout to verify 10-second timeout
- Added TestOpsGenie_ClientHasTimeout to verify 10-second timeout
- All notifiers already configured with 10 second timeout in New()
- Tests verify timeout is set and matches expected value
2026-03-27 21:33:31 -04:00
shankar0123 fd6ae98222 fix: resolve M25 compile errors in verification tests
- Fix undefined tls.Listener in verify_test.go (type doesn't exist in
  crypto/tls); use server.Listener.Addr() and server.TLS.Certificates
- Fix mockJobRepository missing Delete/ListByStatus/ListByCertificate/
  UpdateStatus/GetPendingJobs methods required by JobRepository interface
- Fix mockAuditService type mismatch: NewVerificationService expects
  *AuditService (concrete), not a mock; use real AuditService with mock
  repo following existing testutil_test.go patterns
- Fix List() signature mismatch (had extra filter param)
- Add nil-safe logger checks in verify.go to prevent panics in tests
- Remove unused imports (crypto/tls, bytes, repository)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 21:21:24 -04:00
shankar0123 b4ac0cda43 fix: use context.Context instead of interface{} in VerificationService interface
The handler's VerificationService interface used interface{} for the ctx
parameter, but the service implementation uses context.Context. This caused
a compile error: *service.VerificationService does not implement
handler.VerificationService.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 21:13:48 -04:00
shankar0123 a41f271c58 fix: remove unused time import in verification service
Fixes CI build failure from unused import detected by go vet.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 21:11:16 -04:00
shankar0123 be72627aeb feat: M25 post-deployment TLS verification + M26 Traefik/Caddy targets
M25: After deploying a certificate, the agent probes the live TLS
endpoint and compares SHA-256 fingerprints to verify the correct cert
is being served. Best-effort — failures don't block deployments.
New endpoints: POST /jobs/{id}/verify, GET /jobs/{id}/verification.
Migration 000008 adds verification columns to jobs table.

M26: Traefik target connector (file provider, auto-reload) and Caddy
target connector (dual-mode: admin API hot-reload or file-based).
Both wired into agent dispatch.

Also: restructured README to highlight supported integrations (issuers,
targets, notifiers) earlier, moved API/CLI/MCP sections lower. Updated
all docs (features, connectors, architecture, testing guide, why-certctl)
and fixed integration tests for 18-param RegisterHandlers signature.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 21:07:16 -04:00
shankar0123 8308beb5bb fix: Docker Compose missing migrations, network scan []int crash, demo seed data
Three bugs fixed:
- Docker Compose only mounted migration 000001; migrations 000002-000007
  (profiles, agent groups, revocation, discovery, network scans) never ran,
  breaking half the demo features. Now mounts all 7 migrations in order.
- Network Scans page crashed with pq.Array scan error because lib/pq
  doesn't support []int, only []int64. Changed Ports field accordingly.
- Dashboard pie chart displayed "RenewalInProgress" without spaces.
  Added formatStatus() helper for PascalCase → spaced display.

Also adds first-run demo experience improvements:
- 9 discovered certificates (filesystem + network scan mix)
- 3 discovery scans with recent timestamps
- 2 AwaitingApproval renewal jobs for approval workflow demo
- CERTCTL_NETWORK_SCAN_ENABLED=true in Docker Compose
- Network scan targets seeded with last_scan results
- Version badge updated to v2.0.5
- Docs updated (quickstart, advanced demo) to reference seeded data

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 18:33:50 -04:00
shankar0123 03593d4304 feat: wire ACME EAB into account registration + ZeroSSL auto-fetch
EAB credentials (KID + HMAC) were defined in the ACME connector config
but never wired into the acme.Account registration call. This fixes the
dead code and adds automatic EAB credential fetching for ZeroSSL — when
the directory URL is detected as ZeroSSL and no EAB credentials are
provided, certctl calls ZeroSSL's public API to get them automatically.

Changes:
- Wire EABKid/EABHmac into acme.Account.ExternalAccountBinding
- Add isZeroSSL() detection and fetchZeroSSLEAB() auto-fetch
- Add CERTCTL_ACME_EAB_KID/CERTCTL_ACME_EAB_HMAC env vars to main.go
- Add 13 ACME connector tests (config validation, EAB decode, ZeroSSL
  auto-EAB with mock servers, URL detection)
- Update docs: README, architecture, connectors, demo-advanced,
  testing-guide with EAB/auto-EAB documentation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 15:34:48 -04:00
shankar0123 50c520e1ff feat: dashboard theme overhaul — light content area with branded teal sidebar
Complete frontend visual redesign using certctl logo color palette:
- Deep teal sidebar (#0c2e25) with prominent centered logo (64px in white pill)
- Light content area (#f0f4f8) with white cards and visible borders
- Brand colors from logo: teal (#2ea88f), blue (#3b7dd8), orange (#e8873a), green (#4ebe6e)
- Inter + JetBrains Mono typography, colored stat card top borders
- All 17 pages + 7 components updated (25 files, ~700 lines changed)
- 15 new dashboard screenshots replacing old dark theme screenshots
- Prometheus metrics e2e test added, integration test mock fixes
- Docs updated: architecture.md theme description, testing-guide.md DNS-PERSIST-01 coverage

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 23:27:42 -04:00
shankar0123 e19c240a79 feat: add ACME DNS-PERSIST-01 challenge support (IETF draft-ietf-acme-dns-persist)
Standing TXT record at _validation-persist.<domain> eliminates per-renewal
DNS updates. Auto-fallback to dns-01 if CA doesn't offer dns-persist-01.
ScriptDNSSolver extended with PresentPersist method. Configurable via
CERTCTL_ACME_CHALLENGE_TYPE=dns-persist-01 and
CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN env vars.

Also fixes IsExpired edge-case test in discovery_test.go that always failed
due to time.Now() drift between test setup and method invocation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 14:23:46 -04:00
shankar0123 29b55bfd01 fix: resolve flaky TestGetJobStats_WithData timezone issue
CompletedAt was set to Now()-1h which falls on "yesterday" when CI
runs near midnight UTC, causing the date bucket lookup to miss.
Use Now() directly since the test only needs jobs completed "today".

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 20:55:48 -04:00
shankar0123 743dca2fb3 fix: use real X.509 certs in EST handler tests
EST handler tests used fake PEM data (e.g., "MIIBmjCCAUCgAwIBAgIRATest")
which is invalid base64 (25 chars, not divisible by 4). Go's pem.Decode
fails silently, causing pemToDERChain to return "no certificates found"
and tests to get 500 instead of 200.

Added generateTestCertPEM() helper that creates a real self-signed ECDSA
P-256 certificate, used across all EST handler tests that need cert PEM.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 15:55:26 -04:00
shankar0123 92bba64772 fix: add GetCACertPEM to connector-layer mock for go vet
The EST milestone (M23) added GetCACertPEM to the issuer.Connector
interface but missed updating mockConnectorLayerIssuer in the adapter
test file. This caused go vet to fail in CI.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 15:48:49 -04:00
shankar0123 7d14635a72 feat: add EST server (RFC 7030) for device certificate enrollment (M23)
Implement Enrollment over Secure Transport protocol with 4 endpoints under
/.well-known/est/ — cacerts (CA chain distribution), simpleenroll (initial
enrollment), simplereenroll (certificate renewal), and csrattrs (CSR
attributes). PKCS#7 certs-only wire format with hand-rolled ASN.1, accepts
both PEM and base64-encoded DER CSRs, configurable issuer and profile
binding, full audit trail. 28 new tests (18 handler + 10 service).

Also includes:
- GetCACertPEM added to issuer connector interface (all 4 issuers updated)
- EST integration tests wired into e2e test suite (13 test cases)
- QA testing guide Part 26 (15 manual EST test cases)
- All docs updated: README, features, architecture, concepts, connectors,
  quickstart, demo-advanced (endpoint counts, MCP wording, agent IDs,
  issuer interface, resource lists, OpenSSL status)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 15:31:06 -04:00
shankar0123 0f4a1b268b fix: handle 204 No Content in fetchJSON, add FK-aware delete errors, v2 screenshots
Frontend: fetchJSON now returns empty object on 204 instead of failing
to parse empty body — fixes silent delete failures across all entities.
Added onError callbacks to owner/team delete mutations to surface errors.

Backend: owner and issuer delete handlers return 409 Conflict with
descriptive messages when FK constraints block deletion, instead of
generic 500.

Added 15 v2 dashboard screenshots, updated README screenshot section,
logo asset, page count references (18→full), and QA guide with FK
constraint test coverage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 05:03:50 -04:00
shankar0123 52af81537d fix: remove duplicate containsSubstring helper and update README for M21+M22
Removes redeclared containsSubstring from network_scan_test.go (already
defined in profile_test.go in the same package). Updates README with 91
endpoints, 19 tables, network discovery API section, Prometheus endpoint,
and M21/M22 roadmap entries.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 23:43:42 -04:00
shankar0123 4f90be9311 feat: add network certificate discovery (M21) and Prometheus metrics (M22)
M21 adds server-side active TLS scanning of CIDR ranges with concurrent
probing, sentinel agent pattern for pipeline reuse, and full CRUD API for
scan targets. M22 adds Prometheus exposition format endpoint alongside
existing JSON metrics. Comprehensive documentation audit updates all docs
to reflect 91 endpoints, 19 tables, 6 scheduler loops, and 900+ tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 23:37:47 -04:00
shankar0123 d613d98c72 fix: normalize certificate status case in stats service
The stats service compared statuses using exact string match against
PascalCase domain constants, but the database may contain legacy
lowercase values. This caused the dashboard to show duplicate pie chart
segments (green "Active" + gray "active") and incorrect summary counts.

Use strings.ToLower() normalization in both GetCertificatesByStatus and
GetDashboardSummary to handle any case variant from the database.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 12:17:24 -04:00
shankar0123 8054719956 fix: migration runner only executes .up.sql files, skips .down.sql and seeds
The migration runner was collecting all .sql files alphabetically, which
caused .down.sql rollback files (DROP TABLE) to execute before .up.sql
files on restart with a persisted postgres volume. Filter to only .up.sql
files — these are idempotent (IF NOT EXISTS) and safe to re-run.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 12:08:12 -04:00
shankar0123 8028c14356 fix: remove unused import and variable flagged by go vet
Remove unused repository import from discovery_handler_test.go and
unused tests variable from discovery_test.go (replaced by testCases).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 01:07:16 -04:00
shankar0123 cfa6674ac1 fix: use repository.DiscoveryFilter in postgres implementation to satisfy interface
The postgres DiscoveryRepository had a duplicate local DiscoveryFilter struct
instead of using repository.DiscoveryFilter, causing a type mismatch that
broke CI build.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 01:05:14 -04:00
shankar0123 667a30870d feat: M18b Filesystem Certificate Discovery — agent scanning, server dedup, triage API
Agent-side:
- Filesystem scanner walks configured directories (CERTCTL_DISCOVERY_DIRS)
- Parses PEM (.pem, .crt, .cer, .cert) and DER (.der) certificate files
- Extracts CN, SANs, serial, issuer/subject DN, validity, key info, SHA-256 fingerprint
- Reports discoveries to control plane on startup + every 6 hours
- Skips files >1MB and private key files

Server-side:
- Migration 000006: discovered_certificates + discovery_scans tables
- Domain model: DiscoveredCertificate, DiscoveryScan, DiscoveryReport
- Three triage states: Unmanaged, Managed (claimed), Dismissed
- Repository with upsert dedup (fingerprint + agent + path)
- Service layer: process reports, claim, dismiss, list, summary
- 7 new API endpoints (84 total):
  POST /agents/{id}/discoveries, GET /discovered-certificates,
  GET /discovered-certificates/{id}, POST .../claim, POST .../dismiss,
  GET /discovery-scans, GET /discovery-summary
- Audit trail: scan_completed, cert_claimed, cert_dismissed events

Tests: 28 new test functions (domain, handler, service layers)
Docs: README, quickstart, demo-guide, demo-advanced, architecture,
      concepts, connectors, features.md all updated

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 00:25:00 -04:00
shankar0123 e078a686bf feat: M20 Enhanced Query API — sort, time-range filters, cursor pagination, sparse fields, deployments endpoint
V2 (free) query enhancements for certificates:
- `sort` param with direction (`?sort=-notAfter` for descending)
- Time-range filters: `expires_before`, `expires_after`, `created_after`, `updated_after`
- Cursor-based pagination (`?cursor=token&page_size=100`) alongside page-based
- Sparse field selection (`?fields=id,commonName,status`)
- Additional filters: `agent_id`, `profile_id`
- New endpoint: `GET /api/v1/certificates/{id}/deployments`

25 new tests (12 handler + 13 e2e) covering all M20 features.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 18:56:02 -04:00
shankar0123 373346a0ba feat: comprehensive e2e test suite for cross-milestone integration testing
7 test functions with 35+ subtests covering stats/metrics endpoints,
cross-resource workflows (policy→cert→agent→renew→revoke→audit),
job approval workflows, notification endpoints, CRL endpoint,
pagination across 6 endpoints, and issuer/target CRUD lifecycle.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 18:25:43 -04:00
shankar0123 df1aaa37f8 feat: M17 OpenSSL/Custom CA issuer connector + M16b CLI tool with bulk import
M17: Script-based issuer connector delegating sign/revoke/CRL to user-provided
scripts. Compatible with any CA tooling (OpenSSL, cfssl, custom PKI). Configurable
timeout, environment variable passthrough. 14 tests including timeout enforcement.

M16b: certctl-cli wraps all 76 REST API endpoints for terminal workflows. Supports
certs/agents/jobs list/get/renew/revoke/cancel, bulk PEM import with progress
reporting, server health status, table and JSON output formats. Zero external
dependencies (stdlib only). 14 tests with mock HTTP server.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 18:12:40 -04:00
shankar0123 9b0ff37973 feat: M19 API audit log + M16a notifier connectors (Slack, Teams, PagerDuty, OpsGenie)
M19: HTTP middleware records every API call to the immutable audit trail
with method, path, actor, SHA-256 body hash, status, and latency. Best-effort
async recording via goroutine. Health/ready probes excluded.

M16a: Four pluggable notifier connectors — Slack (incoming webhook), Teams
(MessageCard), PagerDuty (Events API v2), OpsGenie (Alert API v2). Each
enabled by config env var. 30 new tests across middleware and connectors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 17:58:14 -04:00
shankar0123 b227502cef fix: tolerate empty body on job rejection endpoint
The reject job handler should accept nil/empty bodies (no reason given)
while still rejecting malformed JSON. Check for io.EOF and http.NoBody
to distinguish missing body from invalid body.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 17:39:16 -04:00
shankar0123 43a03c168c fix: Go 1.25 upgrade, codebase audit fixes, MCP server tests
Upgrade from Go 1.22 to 1.25 (minimum for MCP SDK, actively supported).
CI updated to match.

Codebase audit fixes:
- Local CA parseIP() now uses net.ParseIP — IP SANs no longer silently dropped
- Nil pointer guards in agent.go GetWorkWithTargets for target/cert enrichment
- MCP CreateCertificateInput marks owner_id/team_id as required
- NGINX connector uses CombinedOutput() — captures diagnostic output on failure
- Jobs handler validates JSON decode on rejection body — returns 400 on malformed
- CRL/OCSP handlers propagate requestID for error tracing

MCP server tests (26 tests):
- client_test.go: HTTP client coverage (GET/POST/PUT/DELETE, auth, 204, errors, binary)
- tools_test.go: tool registration, pagination, end-to-end flows with mock API

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 17:36:25 -04:00
shankar0123 956230aec1 feat: M18a — MCP server exposing all 76 API endpoints as AI-native tools
Separate standalone binary (cmd/mcp-server/) using official MCP Go SDK
(modelcontextprotocol/go-sdk v1.4.1) with stdio transport. Stateless HTTP
proxy translates MCP tool calls to certctl REST API requests. 76 tools
across 16 resource domains with typed input structs and jsonschema tags
for automatic LLM-friendly schema generation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:49:39 -04:00
shankar0123 ee75f149ae feat: M14 — Observability (dashboard charts, agent fleet, stats API, metrics, structured logging, rollback)
Backend: StatsService with 5 aggregation methods, JSON metrics endpoint, slog-based
structured logging middleware. Stats API: dashboard summary, certificates-by-status,
expiration timeline, job trends, issuance rate. 23 new backend tests.

Frontend: Recharts-powered dashboard with 4 charts (status pie, expiration heatmap,
job trends line, issuance bar), agent fleet overview page with OS/arch grouping and
version breakdown, deployment rollback buttons on version history. 7 new frontend tests.

78 API endpoints, 744+ total tests (658 Go + 86 Vitest).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 19:46:13 -04:00
shankar0123 28bef63569 fix: handle 'not found' errors as 404 in CRL/OCSP handlers
The error routing only checked for "issuer not found" but not
"certificate not found", causing cert-not-found errors to fall
through to a generic 500. Broadened the check to match any
"not found" error string for both CRL and OCSP handlers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 19:06:37 -04:00
shankar0123 ed989d81fd fix: wire issuer registry in revocation tests, correct CRL/OCSP handler test URLs
Service tests: newRevocationTestService() was missing SetIssuerRegistry(),
causing all 8 CRL/OCSP tests to fail with "issuer registry not configured".

Handler tests: CRL tests used /api/v1/issuers/{id}/crl but handler parses
/api/v1/crl/{id}. OCSP tests used query string ?serial=X but handler
expects path param /api/v1/ocsp/{id}/{serial}. Fixed all 9 test URLs.

All issues pre-date CI on v2-dev — introduced during M15b.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 16:02:36 -04:00
shankar0123 d4fd46155e fix: unused certRepo variable and missing revocation wiring
- revocation_test.go: certRepo unused in TestGenerateDERCRL_Success,
  replaced with blank identifier
- lifecycle_test.go: missing revocationRepo init and setter calls
  (SetRevocationRepo, SetNotificationService, SetIssuerRegistry)
  that negative_test.go already had

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 15:55:44 -04:00
shankar0123 5407fabe1d fix: remove extra context.Context args from CRL/OCSP tests
GenerateDERCRL and GetOCSPResponse don't take a context parameter,
but all 8 test calls passed context.Background() as the first arg.
Pre-existing issue never caught because CI wasn't running on v2-dev.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 15:40:38 -04:00
shankar0123 ed41d21eac fix: use service-layer types in adapter tests
GenerateCRL test was passing []issuer.RevokedCertEntry instead of
[]CRLEntry, causing go vet failure. Also fixed OCSPSignRequest
references to use service-layer type for consistency.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 15:21:03 -04:00
shankar0123 5854d4406d fix: remove unused variable failing go vet in CI
expectedCRL was declared but never used in TestIssuerConnectorAdapter_GenerateCRL_Success.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 15:18:30 -04:00
shankar0123 762c523d59 feat: M15b — OCSP responder, DER CRL, short-lived exemption, revocation GUI
Backend:
- Embedded OCSP responder: GET /api/v1/ocsp/{issuer_id}/{serial} returns
  signed OCSP responses (good/revoked/unknown) using CA key
- DER-encoded X.509 CRL: GET /api/v1/crl/{issuer_id} returns proper DER CRL
  signed by issuing CA with 24h validity window
- Short-lived cert exemption: certs with profile TTL < 1 hour skip CRL/OCSP
  (expiry is sufficient revocation for ephemeral workloads)
- Extended issuer connector interface with GenerateCRL and SignOCSPResponse
- Local CA implements full CRL/OCSP signing; ACME and step-ca return
  appropriate "use native endpoint" errors
- IssuerConnectorAdapter bridges new methods between layers

Frontend:
- Revoke button on certificate detail page with RFC 5280 reason modal
- Revocation banner with reason display and timestamp
- Revocation status indicators in lifecycle section
- "Revoked" filter option in certificates list
- API client: revokeCertificate() function and Certificate type extensions

Tests: ~31 new tests across connector, service, handler, and adapter layers
Docs: milestones renumbered (M13-M14, M16-M18), M15b marked complete

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 14:39:10 -04:00
shankar0123 5d98e373e3 feat: M15a — certificate revocation API, CRL endpoint, and revocation notifications
Implements core revocation infrastructure: POST /api/v1/certificates/{id}/revoke
with all 8 RFC 5280 reason codes, JSON-formatted CRL at GET /api/v1/crl, webhook
and email revocation notifications, best-effort issuer notification, and immutable
revocation audit trail. Includes 48 new tests across service, handler, integration,
and domain layers (600+ total). Fixes 3 pre-existing test bugs (team_test error
matching, agent_group delete status code, team handler per_page validation).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 10:59:18 -04:00
shankar0123 690765b53e test: comprehensive test expansion — 330+ to 525+ tests, close M11b coverage gaps
Add 195+ new tests across service, handler, connector, and integration layers:
- Service tests: team (23), owner (21), agent_group (25), issuer (18), issuer_adapter (6)
- Handler tests: teams (26), owners (21)
- NGINX target connector tests (13): config validation, deployment, reload
- Integration tests: 19 M11b endpoint subtests (teams, owners, agent groups CRUD)
- CI pipeline: add ./internal/connector/target/... to test coverage path
- Docs: update test counts to 525+ across README, architecture, CLAUDE.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 23:43:32 -04:00
shankar0123 f5fed74d6f feat: M12 — sub-CA mode, ACME DNS-01 challenges, step-ca issuer connector
Sub-CA mode: Local CA loads CA cert+key from disk (CERTCTL_CA_CERT_PATH +
CERTCTL_CA_KEY_PATH) to operate as subordinate CA under enterprise root
(e.g., ADCS). Supports RSA, ECDSA, PKCS#8 keys. Validates IsCA and
KeyUsageCertSign. Falls back to self-signed when paths unset.

DNS-01 challenges: Pluggable DNSSolver interface with script-based hook
implementation. User-provided scripts create/cleanup _acme-challenge TXT
records for any DNS provider. Configurable propagation wait. Enables
wildcard certs and non-HTTP-accessible hosts.

step-ca connector: Smallstep private CA via native /sign API with JWK
provisioner auth. Issuance, renewal, revocation. Registered as iss-stepca.

23 new tests across 3 files. CI test path widened to ./internal/connector/issuer/...

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 22:55:50 -04:00
shankar0123 b0549e6f05 feat: M11b — ownership tracking, agent groups, interactive renewal approval
Ownership: owners/teams GUI pages, notification email resolution via
resolveRecipient (owner_id → owner.email lookup). Agent groups: dynamic
device grouping by OS/arch/IP CIDR/version with manual include/exclude
membership, migration 000004, full CRUD stack (domain → repo → service →
handler → frontend). Interactive approval: AwaitingApproval job state,
approve/reject API endpoints with reason tracking. Tests: 12 agent group
handler tests, 8 approve/reject job handler tests, integration tests
updated for 13-param RegisterHandlers. Docs updated across architecture,
concepts, and seed data.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 21:02:35 -04:00
shankar0123 a579a84c7f feat: M11a — certificate profiles, crypto policy enforcement, short-lived cert expiry
Add certificate profiles as named enrollment templates that control allowed
key algorithms, max TTL, permitted EKUs, required SAN patterns, and optional
SPIFFE URI SANs. CSR submissions are validated against profile rules at
signing time (key type + minimum size). Short-lived certs (TTL < 1 hour)
auto-expire via a new scheduler loop — expiry acts as revocation, no
CRL/OCSP needed.

New files:
- Migration 000003: certificate_profiles table, FK columns on
  managed_certificates/renewal_policies, key metadata on certificate_versions
- domain/profile.go: CertificateProfile + KeyAlgorithmRule structs
- repository/postgres/profile.go: full CRUD with JSONB marshaling
- service/profile.go: ProfileService with validation + audit logging
- service/crypto_validation.go: CSR-against-profile validation (RSA/ECDSA/Ed25519)
- handler/profiles.go: 5 HTTP endpoints under /api/v1/profiles
- web/src/pages/ProfilesPage.tsx: profiles management page

Modified:
- renewal.go: CSR validation in CompleteAgentCSRRenewal, ExpireShortLivedCertificates
- scheduler.go: 30s short-lived expiry check loop
- certificate.go (repo): nullable profile FK, key metadata on versions
- main.go: profile repo/service/handler wiring, 8-param NewRenewalService
- router.go: 12-param RegisterHandlers with profile routes
- seed_demo.sql: 4 demo profiles (standard, mtls, short-lived, high-security)
- Frontend: types, API client, routing, sidebar nav

Tests: 40 new tests across handler (15), service (13), crypto validation (12)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 20:39:49 -04:00
shankar0123 07275bf92f feat: M10 — agent metadata collection, Apache httpd + HAProxy target connectors
Agents now report OS, architecture, IP address, hostname, and version
via heartbeat using runtime.GOOS, runtime.GOARCH, and net.Dial. New
migration adds columns to agents table. Heartbeat handler, service,
and repository updated to accept and persist metadata. GUI shows
OS/Arch in agent list and full system info in agent detail page.

Apache httpd connector: separate cert/chain/key files, apachectl
configtest validation, graceful reload. HAProxy connector: combined
PEM file (cert+chain+key), optional config validation, reload.
Both wired into agent binary's target connector switch.

14 tests for new connectors. All existing tests updated for new
Heartbeat/UpdateHeartbeat signatures. Docs updated across README,
architecture, concepts, and connectors guides.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 02:19:28 -04:00
shankar0123 829c7c0064 fix: add operation-level context timeouts to scheduler loops
Prevents runaway operations from blocking scheduler goroutines:
- Renewal check: 5 minute timeout
- Job processor: 2 minute timeout
- Agent health check: 1 minute timeout
- Notification processor: 1 minute timeout

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 01:20:15 -04:00
shankar0123 e03a75ed9a fix: replace fmt.Printf with structured slog logging across all services
All 10 service files now use slog.Error for failure logging instead of
fmt.Printf. Audit event recording errors are checked and logged rather
than silently discarded. Adds consistent structured context (resource IDs,
operation names) to all error log statements.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 01:20:03 -04:00