Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ef92b07448 | |||
| 5b301f9354 | |||
| 2e297b430e | |||
| 7bc6ad9823 | |||
| 6ccdf45179 | |||
| 69483786aa | |||
| 1f5ab16b18 | |||
| a8d04cded4 | |||
| 8308beb5bb | |||
| b9633e5b1a | |||
| d55807947e | |||
| d9fd0a147e | |||
| 03593d4304 | |||
| 87355c3efb | |||
| f92d148881 | |||
| 50c520e1ff | |||
| 8380cb7946 | |||
| 6d8ab54f46 | |||
| e19c240a79 | |||
| 5c38bc3bfe | |||
| b5687aece8 | |||
| cdb6ebdb6a | |||
| bb85f1a56e | |||
| 44c4d89011 | |||
| eaccbcdcf1 | |||
| 4e3cff0729 | |||
| 09c819d424 | |||
| 29b55bfd01 | |||
| 4092bdfb1a | |||
| 743dca2fb3 | |||
| 92bba64772 | |||
| 7d14635a72 | |||
| 58aa217428 | |||
| a05dba49f7 | |||
| 3efe86e29e | |||
| c0320c35f0 | |||
| 0f4a1b268b | |||
| 3eb4749b4d | |||
| 983ab56662 | |||
| 90bdb8c329 | |||
| d185e317df | |||
| 72cda5877a |
@@ -65,8 +65,8 @@ jobs:
|
||||
## Docker Images
|
||||
|
||||
```bash
|
||||
docker pull ghcr.io/shankar0123/certctl-server:${{ steps.version.outputs.VERSION }}
|
||||
docker pull ghcr.io/shankar0123/certctl-agent:${{ steps.version.outputs.VERSION }}
|
||||
docker pull shankar0123.docker.scarf.sh/certctl-server:${{ steps.version.outputs.VERSION }}
|
||||
docker pull shankar0123.docker.scarf.sh/certctl-agent:${{ steps.version.outputs.VERSION }}
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
@@ -1,53 +1,107 @@
|
||||
<p align="center">
|
||||
<img src="docs/screenshots/logo/certctl-logo.png" alt="certctl logo" width="450">
|
||||
</p>
|
||||
|
||||
<img referrerpolicy="no-referrer-when-downgrade" src="https://static.scarf.sh/a.png?x-pxid=89db181e-76e0-45cc-b9c0-790c3dfdfc73" />
|
||||
<img referrerpolicy="no-referrer-when-downgrade" src="https://static.scarf.sh/a.png?x-pxid=b9379aff-9e5c-4d01-8f2d-9e4ffa09d126" />
|
||||
|
||||
# certctl — Self-Hosted Certificate Lifecycle Platform
|
||||
|
||||
TLS certificate lifespans are shrinking. The CA/Browser Forum passed [Ballot SC-081v3](https://cabforum.org/2025/04/11/ballot-sc081v3-introduce-schedule-of-reducing-validity-and-data-reuse-periods/) unanimously in April 2025, setting a phased reduction: **200 days** by March 2026, **100 days** by March 2027, and **47 days** by March 2029. Manual certificate management is no longer viable at any scale.
|
||||
```mermaid
|
||||
timeline
|
||||
title TLS Certificate Maximum Lifespan (CA/Browser Forum Ballot SC-081v3)
|
||||
2015 : 5 years
|
||||
2018 : 825 days
|
||||
2020 : 398 days
|
||||
March 2026 : 200 days
|
||||
March 2027 : 100 days
|
||||
March 2029 : 47 days
|
||||
```
|
||||
|
||||
certctl is a self-hosted platform for **end-to-end certificate lifecycle automation** — from issuance through renewal to deployment — with zero human intervention. Track every certificate in your organization, automatically renew them before they expire, and deploy them to your servers without touching a terminal. Private keys never leave your infrastructure.
|
||||
TLS certificate lifespans are shrinking fast. The CA/Browser Forum passed [Ballot SC-081v3](https://cabforum.org/2025/04/11/ballot-sc081v3-introduce-schedule-of-reducing-validity-and-data-reuse-periods/) unanimously in April 2025, setting a phased reduction: **200 days** by March 2026, **100 days** by March 2027, and **47 days** by March 2029. Organizations managing dozens or hundreds of certificates can no longer rely on spreadsheets, calendar reminders, or manual renewal workflows. The math doesn't work — at 47-day lifespans, a team managing 100 certificates is processing 7+ renewals per week, every week, forever.
|
||||
|
||||
certctl is a self-hosted platform that automates the entire certificate lifecycle — from issuance through renewal to deployment — with zero human intervention. It works with any certificate authority, deploys to any server, and keeps private keys on your infrastructure where they belong.
|
||||
|
||||
[](LICENSE)
|
||||
[](https://goreportcard.com/report/github.com/shankar0123/certctl)
|
||||

|
||||

|
||||
|
||||
## Documentation
|
||||
|
||||
| Guide | Description |
|
||||
|-------|-------------|
|
||||
| [Why certctl?](docs/why-certctl.md) | Competitive positioning — how certctl compares to open-source and enterprise certificate management platforms |
|
||||
| [Concepts](docs/concepts.md) | TLS certificates explained from scratch — for beginners who know nothing about certs |
|
||||
| [Quick Start](docs/quickstart.md) | Get running in 5 minutes — dashboard, API, CLI, discovery, stakeholder demo flow |
|
||||
| [Advanced Demo](docs/demo-advanced.md) | Issue a certificate end-to-end with technical deep-dives |
|
||||
| [Architecture](docs/architecture.md) | System design, data flow diagrams, security model |
|
||||
| [Feature Inventory](docs/features.md) | Complete reference of all V2 capabilities, API endpoints, and configuration |
|
||||
| [Connectors](docs/connectors.md) | Build custom issuer, target, and notifier connectors |
|
||||
| [Compliance Mapping](docs/compliance.md) | SOC 2 Type II, PCI-DSS 4.0, NIST SP 800-57 alignment guides |
|
||||
|
||||
## Why certctl Exists
|
||||
|
||||
Certificate lifecycle tooling today falls into two camps: expensive enterprise platforms (Venafi, Keyfactor, Sectigo) that cost six figures and take months to deploy, or single-purpose tools (cert-manager, certbot) that handle one slice of the problem. If you run a mixed infrastructure — some NGINX, some Apache, a few HAProxy nodes, maybe an F5 — and you need to manage certificates from multiple CAs, there's nothing self-hosted that covers the full lifecycle without vendor lock-in.
|
||||
|
||||
certctl fills that gap. It's **CA-agnostic** — the issuer connector interface means you can plug in any certificate authority: a self-signed local CA for dev, Let's Encrypt via ACME for public certs, Smallstep step-ca for your private PKI, your enterprise ADCS via sub-CA mode, or any custom CA through a shell script adapter. You're never locked to a single CA vendor, and you can run multiple issuers simultaneously for different certificate types.
|
||||
|
||||
It's also **target-agnostic**. Agents deploy certificates to NGINX, Apache, and HAProxy today, with Traefik and Caddy support coming next — all using the same pluggable connector model for any server that accepts cert files. The control plane never initiates outbound connections — agents poll for work, which means certctl works behind firewalls, across network zones, and in air-gapped environments.
|
||||
|
||||
For a detailed comparison with CertKit, KeyTalk, and enterprise platforms (Venafi, Keyfactor), see [Why certctl?](docs/why-certctl.md)
|
||||
|
||||
## What It Does
|
||||
|
||||
certctl gives you a single pane of glass for every TLS certificate in your organization. The **web dashboard** shows your full certificate inventory — what's healthy, what's expiring, what's already expired, and who owns each one. The **REST API** (91 endpoints under `/api/v1/`) lets you automate everything. **Agents** deployed on your infrastructure generate private keys locally, discover existing certificates on disk, and submit CSRs — private keys never leave your servers. The **network scanner** discovers certificates on TLS endpoints across your infrastructure without requiring agents. The background scheduler watches expiration dates and triggers renewals automatically — when certificate lifespans drop to 47 days, certctl handles the constant rotation without human involvement.
|
||||
certctl gives you a single pane of glass for every TLS certificate in your organization:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph "Control Plane"
|
||||
API["REST API + Dashboard\n:8443"]
|
||||
PG[("PostgreSQL")]
|
||||
end
|
||||
- **Web dashboard** — full certificate inventory with status, ownership, expiration heatmaps, and bulk operations
|
||||
- **REST API** — 95 endpoints under `/api/v1/` + `/.well-known/est/` for complete automation
|
||||
- **Agents** — generate private keys locally, discover existing certs on disk, submit CSRs (private keys never leave your servers)
|
||||
- **Network scanner** — discovers certificates on TLS endpoints across CIDR ranges without requiring agents
|
||||
- **EST server** (RFC 7030) — device and WiFi certificate enrollment via industry-standard protocol
|
||||
- **Approval workflows** — require human sign-off on renewals before deployment
|
||||
- **Background scheduler** — watches expiration dates and triggers renewals automatically, handling constant rotation at 47-day lifespans without human involvement
|
||||
|
||||
subgraph "Your Infrastructure"
|
||||
A1["Agent"] --> T1["NGINX"]
|
||||
A2["Agent"] --> T2["Apache / HAProxy"]
|
||||
A3["Agent"] --> T3["F5 · IIS"]
|
||||
end
|
||||
|
||||
API --> PG
|
||||
A1 & A2 & A3 -->|"CSR + status\n(no private keys)"| API
|
||||
API -->|"Signed certs"| A1 & A2 & A3
|
||||
API -->|"Issue/Renew"| CA["Certificate Authorities\nLocal CA · ACME · step-ca · OpenSSL"]
|
||||
```
|
||||
For the full capability breakdown — issuer connectors, revocation infrastructure, policy engine, observability, EST enrollment, and more — see the [Feature Inventory](docs/features.md).
|
||||
|
||||
### Screenshots
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
|  |  |
|
||||
| **Dashboard** — certificate stats, expiry timeline, recent jobs | **Certificates** — full inventory with status, environment, owner filters |
|
||||
|  |  |
|
||||
| **Agents** — fleet health, hostname, heartbeat tracking | **Jobs** — issuance, renewal, deployment job queue |
|
||||
|  |  |
|
||||
| **Notifications** — threshold alerts grouped by certificate | **Policies** — enforcement rules with enable/disable and delete |
|
||||
|  |  |
|
||||
| **Issuers** — CA connectors with test connectivity | **Targets** — deployment targets (NGINX, Apache, HAProxy, F5, IIS) |
|
||||
|  | |
|
||||
| **Audit Trail** — immutable log of every action | |
|
||||
<table>
|
||||
<tr>
|
||||
<td><a href="docs/screenshots/v2-dashboard.png"><img src="docs/screenshots/v2-dashboard.png" width="270" alt="Dashboard"></a><br><b>Dashboard</b><br><sub>Stats, expiration heatmap, renewal trends</sub></td>
|
||||
<td><a href="docs/screenshots/v2-certificates.png"><img src="docs/screenshots/v2-certificates.png" width="270" alt="Certificates"></a><br><b>Certificates</b><br><sub>Inventory with status, owner, team filters</sub></td>
|
||||
<td><a href="docs/screenshots/v2-agents.png"><img src="docs/screenshots/v2-agents.png" width="270" alt="Agents"></a><br><b>Agents</b><br><sub>Fleet health, OS/arch, IP, version</sub></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="docs/screenshots/v2-fleet.png"><img src="docs/screenshots/v2-fleet.png" width="270" alt="Fleet Overview"></a><br><b>Fleet Overview</b><br><sub>OS distribution, status breakdown</sub></td>
|
||||
<td><a href="docs/screenshots/v2-jobs.png"><img src="docs/screenshots/v2-jobs.png" width="270" alt="Jobs"></a><br><b>Jobs</b><br><sub>Issuance, renewal, deployment queue</sub></td>
|
||||
<td><a href="docs/screenshots/v2-notifications.png"><img src="docs/screenshots/v2-notifications.png" width="270" alt="Notifications"></a><br><b>Notifications</b><br><sub>Expiration warnings, renewal results</sub></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="docs/screenshots/v2-policies.png"><img src="docs/screenshots/v2-policies.png" width="270" alt="Policies"></a><br><b>Policies</b><br><sub>Ownership, lifetime, renewal rules</sub></td>
|
||||
<td><a href="docs/screenshots/v2-profiles.png"><img src="docs/screenshots/v2-profiles.png" width="270" alt="Profiles"></a><br><b>Profiles</b><br><sub>Key types, max TTL, crypto constraints</sub></td>
|
||||
<td><a href="docs/screenshots/v2-issuers.png"><img src="docs/screenshots/v2-issuers.png" width="270" alt="Issuers"></a><br><b>Issuers</b><br><sub>Local CA, ACME, step-ca connectors</sub></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="docs/screenshots/v2-targets.png"><img src="docs/screenshots/v2-targets.png" width="270" alt="Targets"></a><br><b>Targets</b><br><sub>NGINX, Apache, HAProxy deployment</sub></td>
|
||||
<td><a href="docs/screenshots/v2-owners.png"><img src="docs/screenshots/v2-owners.png" width="270" alt="Owners"></a><br><b>Owners</b><br><sub>Cert ownership with team assignment</sub></td>
|
||||
<td><a href="docs/screenshots/v2-teams.png"><img src="docs/screenshots/v2-teams.png" width="270" alt="Teams"></a><br><b>Teams</b><br><sub>Org grouping for notification routing</sub></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="docs/screenshots/v2-agent-groups.png"><img src="docs/screenshots/v2-agent-groups.png" width="270" alt="Agent Groups"></a><br><b>Agent Groups</b><br><sub>Dynamic grouping by OS, arch, CIDR</sub></td>
|
||||
<td><a href="docs/screenshots/v2-audit-trail.png"><img src="docs/screenshots/v2-audit-trail.png" width="270" alt="Audit Trail"></a><br><b>Audit Trail</b><br><sub>Immutable log, CSV/JSON export</sub></td>
|
||||
<td><a href="docs/screenshots/v2-short-lived.png"><img src="docs/screenshots/v2-short-lived.png" width="270" alt="Short-Lived"></a><br><b>Short-Lived Creds</b><br><sub>Ephemeral certs with live TTL countdown</sub></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Docker Pull
|
||||
|
||||
```bash
|
||||
docker pull shankar0123.docker.scarf.sh/certctl-server
|
||||
docker pull shankar0123.docker.scarf.sh/certctl-agent
|
||||
```
|
||||
|
||||
### Docker Compose (Recommended)
|
||||
|
||||
```bash
|
||||
@@ -72,7 +126,7 @@ curl -s http://localhost:8443/api/v1/certificates | jq '.total'
|
||||
### Manual Build
|
||||
|
||||
```bash
|
||||
# Prerequisites: Go 1.22+, PostgreSQL 16+
|
||||
# Prerequisites: Go 1.25+, PostgreSQL 16+
|
||||
go mod download
|
||||
make build
|
||||
|
||||
@@ -92,45 +146,9 @@ export CERTCTL_AGENT_ID=agent-local-01
|
||||
./bin/agent --agent-id=agent-local-01
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
| Guide | Description |
|
||||
|-------|-------------|
|
||||
| [Concepts](docs/concepts.md) | TLS certificates explained from scratch — for beginners who know nothing about certs |
|
||||
| [Quick Start](docs/quickstart.md) | Get running in 5 minutes with accurate API examples |
|
||||
| [Demo Walkthrough](docs/demo-guide.md) | 5-7 minute guided stakeholder presentation |
|
||||
| [Advanced Demo](docs/demo-advanced.md) | Issue a certificate end-to-end with technical deep-dives |
|
||||
| [Architecture](docs/architecture.md) | System design, data flow diagrams, security model |
|
||||
| [Connectors](docs/connectors.md) | Build custom issuer, target, and notifier connectors |
|
||||
| [Compliance Mapping](docs/compliance.md) | SOC 2 Type II, PCI-DSS 4.0, NIST SP 800-57 alignment guides |
|
||||
| [Manual Testing Guide](docs/testing-guide.md) | 284 tests across 25 areas — full V2 QA runbook with exact commands and pass/fail criteria |
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph "Control Plane (certctl-server)"
|
||||
DASH["Web Dashboard\nReact SPA"]
|
||||
API["REST API\nGo 1.22 net/http"]
|
||||
SVC["Service Layer"]
|
||||
REPO["Repository Layer\ndatabase/sql + lib/pq"]
|
||||
SCHED["Scheduler\nRenewal · Jobs · Health · Notifications · Short-Lived Expiry · Network Scan"]
|
||||
end
|
||||
|
||||
subgraph "Data Store"
|
||||
PG[("PostgreSQL 16\n21 tables\nTEXT primary keys")]
|
||||
end
|
||||
|
||||
subgraph "Agents"
|
||||
AG["certctl-agent\nKey generation · CSR · Deployment"]
|
||||
end
|
||||
|
||||
DASH --> API
|
||||
API --> SVC --> REPO --> PG
|
||||
SCHED --> SVC
|
||||
AG -->|"Heartbeat + CSR"| API
|
||||
API -->|"Cert + Chain"| AG
|
||||
```
|
||||
**Control plane** (Go 1.25 net/http) → **PostgreSQL 16** (21 tables, TEXT primary keys) → **Agents** (key generation, CSR submission, cert deployment). Background scheduler runs 6 loops: renewal checks (1h), job processing (30s), agent health (2m), notifications (1m), short-lived cert expiry (30s), network scanning (6h). See [Architecture Guide](docs/architecture.md) for full system diagrams and data flow.
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
@@ -139,90 +157,33 @@ flowchart TB
|
||||
- **Handler → Service → Repository layering.** Handlers define their own service interfaces for clean dependency inversion. No global service singletons.
|
||||
- **Idempotent migrations.** All schema uses `IF NOT EXISTS` and seed data uses `ON CONFLICT (id) DO NOTHING`, safe for repeated execution.
|
||||
|
||||
### Database Schema
|
||||
|
||||
| Table | Purpose |
|
||||
|-------|---------|
|
||||
| `managed_certificates` | Certificate records with metadata, status, expiry, tags |
|
||||
| `certificate_versions` | Historical versions with PEM chains and CSRs |
|
||||
| `renewal_policies` | Renewal window, auto-renew settings, retry config, alert thresholds |
|
||||
| `issuers` | CA configurations (Local CA, ACME, etc.) |
|
||||
| `deployment_targets` | Target systems (NGINX, F5, IIS) with agent assignments |
|
||||
| `agents` | Registered agents with heartbeat tracking, OS/arch/IP metadata |
|
||||
| `jobs` | Issuance, renewal, deployment, and validation jobs |
|
||||
| `teams` | Organizational groups for certificate ownership |
|
||||
| `owners` | Individual owners with email for notifications |
|
||||
| `policy_rules` | Enforcement rules (allowed issuers, environments, metadata) |
|
||||
| `policy_violations` | Flagged non-compliance with severity levels |
|
||||
| `audit_events` | Immutable action log (append-only, no update/delete) |
|
||||
| `notification_events` | Email and webhook notification records |
|
||||
| `certificate_target_mappings` | Many-to-many cert ↔ target relationships |
|
||||
| `certificate_profiles` | Named enrollment profiles with allowed key types, max TTL, crypto constraints |
|
||||
| `agent_groups` | Dynamic device grouping by OS, architecture, IP CIDR, version |
|
||||
| `agent_group_members` | Manual include/exclude membership for agent groups |
|
||||
| `certificate_revocations` | Revocation records with RFC 5280 reason codes, serial numbers, issuer notification status |
|
||||
| `discovered_certificates` | Filesystem and network-discovered certificates with fingerprint deduplication |
|
||||
| `discovery_scans` | Discovery scan history with timestamps and agent attribution |
|
||||
| `network_scan_targets` | Network scan target definitions with CIDRs, ports, schedule, and scan metrics |
|
||||
PostgreSQL 16 with 21 tables covering certificates, versions, policies, issuers, targets, agents, jobs, teams, owners, profiles, agent groups, revocations, discovery, network scans, and audit events. See the [Architecture Guide](docs/architecture.md) for the full schema.
|
||||
|
||||
## Configuration
|
||||
|
||||
All server environment variables use the `CERTCTL_` prefix:
|
||||
All environment variables use the `CERTCTL_` prefix. Key settings:
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_SERVER_HOST` | `127.0.0.1` | Server bind address |
|
||||
| `CERTCTL_SERVER_PORT` | `8080` | Server listen port |
|
||||
| `CERTCTL_DATABASE_URL` | `postgres://localhost/certctl` | PostgreSQL connection string |
|
||||
| `CERTCTL_DATABASE_MAX_CONNS` | `25` | Connection pool size |
|
||||
| `CERTCTL_LOG_LEVEL` | `info` | Log level: `debug`, `info`, `warn`, `error` |
|
||||
| `CERTCTL_LOG_FORMAT` | `json` | Log format: `json` or `text` |
|
||||
| `CERTCTL_AUTH_TYPE` | `api-key` | Auth mode: `api-key`, `jwt`, or `none` |
|
||||
| `CERTCTL_AUTH_SECRET` | — | Required for `api-key` and `jwt` auth types |
|
||||
| `CERTCTL_KEYGEN_MODE` | `agent` | Key generation mode: `agent` (production) or `server` (demo only) |
|
||||
| `CERTCTL_ACME_DIRECTORY_URL` | — | ACME directory URL (e.g., Let's Encrypt staging) |
|
||||
| `CERTCTL_KEYGEN_MODE` | `agent` | Key generation: `agent` (production) or `server` (demo only) |
|
||||
| `CERTCTL_SERVER_PORT` | `8080` | Server listen port |
|
||||
| `CERTCTL_ACME_DIRECTORY_URL` | — | ACME directory URL (e.g., Let's Encrypt) |
|
||||
| `CERTCTL_ACME_EMAIL` | — | Contact email for ACME account registration |
|
||||
| `CERTCTL_ACME_CHALLENGE_TYPE` | — | ACME challenge type: `http-01` (default) or `dns-01` |
|
||||
| `CERTCTL_CA_CERT_PATH` | — | Path to CA certificate for sub-CA mode |
|
||||
| `CERTCTL_CA_KEY_PATH` | — | Path to CA private key for sub-CA mode |
|
||||
| `CERTCTL_CORS_ORIGINS` | — | Comma-separated allowed CORS origins (empty = same-origin, `*` = all) |
|
||||
| `CERTCTL_RATE_LIMIT_ENABLED` | `true` | Enable/disable token bucket rate limiting |
|
||||
| `CERTCTL_RATE_LIMIT_RPS` | `50` | Requests per second limit |
|
||||
| `CERTCTL_RATE_LIMIT_BURST` | `100` | Maximum burst size for rate limiter |
|
||||
| `CERTCTL_DATABASE_MIGRATIONS_PATH` | `./migrations` | Path to SQL migration files |
|
||||
| `CERTCTL_SCHEDULER_RENEWAL_CHECK_INTERVAL` | `1h` | How often the scheduler checks for expiring certs |
|
||||
| `CERTCTL_SCHEDULER_JOB_PROCESSOR_INTERVAL` | `30s` | How often the scheduler processes pending jobs |
|
||||
| `CERTCTL_SCHEDULER_AGENT_HEALTH_CHECK_INTERVAL` | `2m` | How often the scheduler checks agent health |
|
||||
| `CERTCTL_SCHEDULER_NOTIFICATION_PROCESS_INTERVAL` | `1m` | How often the scheduler processes pending notifications |
|
||||
| `CERTCTL_ACME_DNS_PRESENT_SCRIPT` | — | Script to create DNS-01 `_acme-challenge` TXT record |
|
||||
| `CERTCTL_ACME_DNS_CLEANUP_SCRIPT` | — | Script to remove DNS-01 `_acme-challenge` TXT record |
|
||||
| `CERTCTL_STEPCA_URL` | — | step-ca server URL |
|
||||
| `CERTCTL_STEPCA_PROVISIONER` | — | step-ca JWK provisioner name |
|
||||
| `CERTCTL_STEPCA_KEY_PATH` | — | Path to step-ca provisioner private key (JWK JSON) |
|
||||
| `CERTCTL_STEPCA_PASSWORD` | — | step-ca provisioner key password |
|
||||
| `CERTCTL_OPENSSL_SIGN_SCRIPT` | — | Script for OpenSSL/Custom CA certificate signing |
|
||||
| `CERTCTL_OPENSSL_REVOKE_SCRIPT` | — | Script for OpenSSL/Custom CA certificate revocation |
|
||||
| `CERTCTL_OPENSSL_CRL_SCRIPT` | — | Script for OpenSSL/Custom CA CRL generation |
|
||||
| `CERTCTL_OPENSSL_TIMEOUT_SECONDS` | `30` | Timeout for OpenSSL script execution |
|
||||
| `CERTCTL_NETWORK_SCAN_ENABLED` | `false` | Enable server-side network certificate discovery (TLS scanning) |
|
||||
| `CERTCTL_NETWORK_SCAN_INTERVAL` | `6h` | How often the scheduler runs network scans |
|
||||
| `CERTCTL_SLACK_WEBHOOK_URL` | — | Slack incoming webhook URL for notifications |
|
||||
| `CERTCTL_TEAMS_WEBHOOK_URL` | — | Microsoft Teams incoming webhook URL |
|
||||
| `CERTCTL_PAGERDUTY_ROUTING_KEY` | — | PagerDuty Events API v2 routing key |
|
||||
| `CERTCTL_OPSGENIE_API_KEY` | — | OpsGenie Alert API key |
|
||||
|
||||
Agent environment variables:
|
||||
Agent settings:
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_SERVER_URL` | `http://localhost:8080` | Control plane URL |
|
||||
| `CERTCTL_API_KEY` | — | Agent API key |
|
||||
| `CERTCTL_AGENT_NAME` | `certctl-agent` | Agent display name |
|
||||
| `CERTCTL_AGENT_ID` | — | Registered agent ID (required) |
|
||||
| `CERTCTL_KEY_DIR` | `/var/lib/certctl/keys` | Directory for storing private keys (agent keygen mode) |
|
||||
| `CERTCTL_DISCOVERY_DIRS` | — | Comma-separated directories to scan for existing certificates (e.g., `/etc/nginx/certs,/etc/ssl/certs`) |
|
||||
| `CERTCTL_KEY_DIR` | `/var/lib/certctl/keys` | Private key storage directory |
|
||||
| `CERTCTL_DISCOVERY_DIRS` | — | Directories to scan for existing certs (comma-separated) |
|
||||
|
||||
Docker Compose overrides these for the demo stack (see `deploy/docker-compose.yml`): port `8443`, auth type `none`, database pointing to the postgres container.
|
||||
For the full configuration reference — including ACME DNS challenges, sub-CA mode, step-ca, OpenSSL/Custom CA, EST enrollment, network scanning, notification connectors (Slack, Teams, PagerDuty, OpsGenie), scheduler intervals, CORS, and rate limiting — see the [Feature Inventory](docs/features.md). Docker Compose overrides for the demo stack are in `deploy/docker-compose.yml`.
|
||||
|
||||
## MCP Server (AI Integration)
|
||||
|
||||
@@ -269,162 +230,65 @@ go install github.com/shankar0123/certctl/cmd/cli@latest
|
||||
export CERTCTL_SERVER_URL=http://localhost:8443
|
||||
export CERTCTL_API_KEY=your-api-key
|
||||
|
||||
# Commands
|
||||
certctl-cli list-certs # List all certificates
|
||||
certctl-cli get-cert --id mc-api-prod # Get certificate details
|
||||
certctl-cli renew-cert --id mc-api-prod # Trigger renewal
|
||||
certctl-cli revoke-cert --id mc-api-prod --reason keyCompromise
|
||||
certctl-cli list-agents # List registered agents
|
||||
certctl-cli list-jobs # List jobs
|
||||
certctl-cli health # Server health check
|
||||
certctl-cli metrics # Server metrics
|
||||
certctl-cli import --file certs.pem # Bulk import from PEM file
|
||||
# Certificate commands
|
||||
certctl-cli certs list # List all certificates
|
||||
certctl-cli certs get mc-api-prod # Get certificate details
|
||||
certctl-cli certs renew mc-api-prod # Trigger renewal
|
||||
certctl-cli certs revoke mc-api-prod --reason keyCompromise
|
||||
|
||||
# Agent and job commands
|
||||
certctl-cli agents list # List registered agents
|
||||
certctl-cli agents get ag-web-prod # Get agent details
|
||||
certctl-cli jobs list # List jobs
|
||||
certctl-cli jobs get job-123 # Get job details
|
||||
certctl-cli jobs cancel job-123 # Cancel a pending job
|
||||
|
||||
# Operations
|
||||
certctl-cli status # Server health + summary stats
|
||||
certctl-cli import certs.pem # Bulk import from PEM file
|
||||
certctl-cli version # Show CLI version
|
||||
|
||||
# Output formats
|
||||
certctl-cli list-certs --format json # JSON output (default: table)
|
||||
certctl-cli certs list --format json # JSON output (default: table)
|
||||
```
|
||||
|
||||
## API Overview
|
||||
|
||||
All endpoints are under `/api/v1/` and return JSON. List endpoints support pagination (`?page=1&per_page=50`). Full request/response schemas are available in the [OpenAPI 3.1 spec](api/openapi.yaml).
|
||||
95 endpoints under `/api/v1/` + `/.well-known/est/`, all returning JSON. List endpoints support pagination, sparse field selection (`?fields=`), sort (`?sort=-notAfter`), time-range filters, and cursor-based pagination. Full request/response schemas in the [OpenAPI 3.1 spec](api/openapi.yaml).
|
||||
|
||||
### Certificates
|
||||
### Key Endpoints
|
||||
```
|
||||
# Certificate lifecycle
|
||||
GET /api/v1/certificates List (filter, sort, cursor, sparse fields)
|
||||
POST /api/v1/certificates Create
|
||||
GET /api/v1/certificates/{id} Get
|
||||
PUT /api/v1/certificates/{id} Update
|
||||
DELETE /api/v1/certificates/{id} Archive (soft delete)
|
||||
GET /api/v1/certificates/{id}/versions Version history
|
||||
GET /api/v1/certificates/{id}/deployments List deployment targets
|
||||
POST /api/v1/certificates/{id}/renew Trigger renewal → 202 Accepted
|
||||
POST /api/v1/certificates/{id}/deploy Trigger deployment → 202 Accepted
|
||||
POST /api/v1/certificates/{id}/revoke Revoke with RFC 5280 reason code
|
||||
GET /api/v1/crl Certificate Revocation List (JSON)
|
||||
GET /api/v1/crl/{issuer_id} DER-encoded X.509 CRL
|
||||
GET /api/v1/ocsp/{issuer_id}/{serial} OCSP responder (good/revoked/unknown)
|
||||
POST /api/v1/certificates/{id}/renew Trigger renewal → 202 Accepted
|
||||
POST /api/v1/certificates/{id}/revoke Revoke with RFC 5280 reason code
|
||||
GET /api/v1/crl/{issuer_id} DER-encoded X.509 CRL
|
||||
GET /api/v1/ocsp/{issuer_id}/{serial} OCSP responder (good/revoked/unknown)
|
||||
|
||||
# Agent operations
|
||||
POST /api/v1/agents/{id}/csr Submit CSR for issuance
|
||||
GET /api/v1/agents/{id}/work Poll for pending deployment jobs
|
||||
POST /api/v1/agents/{id}/discoveries Submit certificate discovery scan results
|
||||
|
||||
# Discovery & network scanning
|
||||
GET /api/v1/discovered-certificates List discovered certs (?agent_id, ?status)
|
||||
POST /api/v1/discovered-certificates/{id}/claim Link to managed cert
|
||||
POST /api/v1/network-scan-targets/{id}/scan Trigger immediate TLS scan
|
||||
|
||||
# Jobs & approval
|
||||
POST /api/v1/jobs/{id}/approve Approve interactive renewal
|
||||
POST /api/v1/jobs/{id}/reject Reject interactive renewal
|
||||
|
||||
# Observability
|
||||
GET /api/v1/metrics/prometheus Prometheus exposition format
|
||||
GET /api/v1/stats/summary Dashboard summary
|
||||
|
||||
# EST enrollment (RFC 7030)
|
||||
POST /.well-known/est/simpleenroll Device certificate enrollment
|
||||
GET /.well-known/est/cacerts CA certificate chain (PKCS#7)
|
||||
```
|
||||
|
||||
### Agents
|
||||
```
|
||||
GET /api/v1/agents List
|
||||
POST /api/v1/agents Register
|
||||
GET /api/v1/agents/{id} Get
|
||||
POST /api/v1/agents/{id}/heartbeat Record heartbeat
|
||||
POST /api/v1/agents/{id}/csr Submit CSR for issuance
|
||||
GET /api/v1/agents/{id}/certificates/{certId} Retrieve signed certificate
|
||||
GET /api/v1/agents/{id}/work Poll for pending deployment jobs
|
||||
POST /api/v1/agents/{id}/jobs/{jobId}/status Report job completion/failure
|
||||
POST /api/v1/agents/{id}/discoveries Submit certificate discovery scan results
|
||||
```
|
||||
|
||||
### Certificate Discovery
|
||||
```
|
||||
GET /api/v1/discovered-certificates List discovered certificates (?agent_id, ?status)
|
||||
GET /api/v1/discovered-certificates/{id} Get discovery detail
|
||||
POST /api/v1/discovered-certificates/{id}/claim Link discovered cert to managed cert
|
||||
POST /api/v1/discovered-certificates/{id}/dismiss Dismiss discovery
|
||||
GET /api/v1/discovery-scans List discovery scan history
|
||||
GET /api/v1/discovery-summary Aggregated discovery status (new, claimed, dismissed counts)
|
||||
```
|
||||
|
||||
### Infrastructure
|
||||
```
|
||||
GET /api/v1/issuers List issuers
|
||||
POST /api/v1/issuers Create
|
||||
GET /api/v1/issuers/{id} Get
|
||||
PUT /api/v1/issuers/{id} Update
|
||||
DELETE /api/v1/issuers/{id} Delete
|
||||
POST /api/v1/issuers/{id}/test Test connectivity
|
||||
|
||||
GET /api/v1/targets List deployment targets
|
||||
POST /api/v1/targets Create
|
||||
GET /api/v1/targets/{id} Get
|
||||
PUT /api/v1/targets/{id} Update
|
||||
DELETE /api/v1/targets/{id} Delete
|
||||
```
|
||||
|
||||
### Organization
|
||||
```
|
||||
GET /api/v1/teams List teams
|
||||
POST /api/v1/teams Create
|
||||
GET /api/v1/teams/{id} Get
|
||||
PUT /api/v1/teams/{id} Update
|
||||
DELETE /api/v1/teams/{id} Delete
|
||||
GET /api/v1/owners List owners
|
||||
POST /api/v1/owners Create
|
||||
GET /api/v1/owners/{id} Get
|
||||
PUT /api/v1/owners/{id} Update
|
||||
DELETE /api/v1/owners/{id} Delete
|
||||
```
|
||||
|
||||
### Operations
|
||||
```
|
||||
GET /api/v1/jobs List (filter: status, type)
|
||||
GET /api/v1/jobs/{id} Get
|
||||
POST /api/v1/jobs/{id}/cancel Cancel
|
||||
POST /api/v1/jobs/{id}/approve Approve (interactive renewal)
|
||||
POST /api/v1/jobs/{id}/reject Reject (interactive renewal)
|
||||
|
||||
GET /api/v1/policies List policy rules
|
||||
POST /api/v1/policies Create
|
||||
GET /api/v1/policies/{id} Get
|
||||
PUT /api/v1/policies/{id} Update (enable/disable)
|
||||
DELETE /api/v1/policies/{id} Delete
|
||||
GET /api/v1/policies/{id}/violations List violations for rule
|
||||
|
||||
GET /api/v1/profiles List certificate profiles
|
||||
POST /api/v1/profiles Create
|
||||
GET /api/v1/profiles/{id} Get
|
||||
PUT /api/v1/profiles/{id} Update
|
||||
DELETE /api/v1/profiles/{id} Delete
|
||||
|
||||
GET /api/v1/agent-groups List agent groups
|
||||
POST /api/v1/agent-groups Create
|
||||
GET /api/v1/agent-groups/{id} Get
|
||||
PUT /api/v1/agent-groups/{id} Update
|
||||
DELETE /api/v1/agent-groups/{id} Delete
|
||||
GET /api/v1/agent-groups/{id}/members List members
|
||||
|
||||
GET /api/v1/audit Query audit trail
|
||||
GET /api/v1/audit/{id} Get audit event
|
||||
GET /api/v1/notifications List notifications
|
||||
GET /api/v1/notifications/{id} Get notification
|
||||
POST /api/v1/notifications/{id}/read Mark as read
|
||||
```
|
||||
|
||||
### Observability
|
||||
```
|
||||
GET /api/v1/stats/summary Dashboard summary (totals, expiring, agents, jobs)
|
||||
GET /api/v1/stats/certificates-by-status Certificate counts grouped by status
|
||||
GET /api/v1/stats/expiration-timeline Expiration buckets (?days=30)
|
||||
GET /api/v1/stats/job-trends Job success/failure over time (?days=7)
|
||||
GET /api/v1/stats/issuance-rate Certificate issuance rate (?days=7)
|
||||
GET /api/v1/metrics JSON metrics (gauges, counters, uptime)
|
||||
GET /api/v1/metrics/prometheus Prometheus exposition format (text/plain)
|
||||
```
|
||||
|
||||
### Network Discovery
|
||||
```
|
||||
GET /api/v1/network-scan-targets List scan targets
|
||||
POST /api/v1/network-scan-targets Create scan target (CIDRs, ports, schedule)
|
||||
GET /api/v1/network-scan-targets/{id} Get scan target
|
||||
PUT /api/v1/network-scan-targets/{id} Update scan target
|
||||
DELETE /api/v1/network-scan-targets/{id} Delete scan target
|
||||
POST /api/v1/network-scan-targets/{id}/scan Trigger immediate scan
|
||||
```
|
||||
|
||||
### Auth
|
||||
```
|
||||
GET /api/v1/auth/info Auth mode info (no auth required)
|
||||
GET /api/v1/auth/check Validate credentials
|
||||
```
|
||||
|
||||
### Health
|
||||
```
|
||||
GET /health Server health check
|
||||
GET /ready Readiness check
|
||||
```
|
||||
Full CRUD is available for certificates, agents, issuers, targets, teams, owners, policies, profiles, agent groups, notifications, and audit events. See the [OpenAPI spec](api/openapi.yaml) or [Feature Inventory](docs/features.md) for the complete endpoint reference.
|
||||
|
||||
## Supported Integrations
|
||||
|
||||
@@ -432,13 +296,13 @@ GET /ready Readiness check
|
||||
| Issuer | Status | Type |
|
||||
|--------|--------|------|
|
||||
| Local CA (self-signed + sub-CA) | Implemented | `GenericCA` |
|
||||
| ACME v2 (Let's Encrypt, Sectigo) | Implemented (HTTP-01 + DNS-01) | `ACME` |
|
||||
| ACME v2 (Let's Encrypt, Sectigo) | Implemented (HTTP-01 + DNS-01 + DNS-PERSIST-01) | `ACME` |
|
||||
| step-ca | Implemented | `StepCA` |
|
||||
| OpenSSL / Custom CA | Implemented | `OpenSSL` |
|
||||
| Vault PKI | Planned | — |
|
||||
| DigiCert | Planned | — |
|
||||
| Vault PKI | Future | — |
|
||||
| DigiCert | Future | — |
|
||||
|
||||
**Note:** ADCS integration is handled via the Local CA's sub-CA mode — certctl operates as a subordinate CA with its signing certificate issued by ADCS.
|
||||
**Note:** ADCS integration is handled via the Local CA's sub-CA mode — certctl operates as a subordinate CA with its signing certificate issued by ADCS. Any CA with a shell-accessible signing interface can be integrated today via the OpenSSL/Custom CA connector.
|
||||
|
||||
### Deployment Targets
|
||||
| Target | Status | Type |
|
||||
@@ -446,9 +310,10 @@ GET /ready Readiness check
|
||||
| NGINX | Implemented | `NGINX` |
|
||||
| Apache httpd | Implemented | `Apache` |
|
||||
| HAProxy | Implemented | `HAProxy` |
|
||||
| Traefik | Planned (v2.1.x) | `Traefik` |
|
||||
| Caddy | Planned (v2.1.x) | `Caddy` |
|
||||
| F5 BIG-IP | Interface only | `F5` |
|
||||
| Microsoft IIS | Interface only | `IIS` |
|
||||
| Kubernetes Secrets | Planned | — |
|
||||
|
||||
### Notifiers
|
||||
| Notifier | Status | Type |
|
||||
@@ -504,37 +369,45 @@ make docker-clean # Stop + remove volumes
|
||||
- Immutable append-only log in PostgreSQL (`audit_events` table)
|
||||
- Every lifecycle action attributed to an actor with timestamp and resource reference
|
||||
- No update or delete operations on audit records
|
||||
- Every API call recorded to audit trail with method, path, actor, SHA-256 body hash, response status, and latency (M19)
|
||||
- Every API call recorded to audit trail with method, path, actor, SHA-256 body hash, response status, and latency
|
||||
|
||||
## Roadmap
|
||||
|
||||
### V1 (v1.0.0 released)
|
||||
All nine development milestones (M1–M9) are complete. The backend covers the full certificate lifecycle: Local CA and ACME v2 issuers, NGINX/Apache/HAProxy/F5/IIS target connectors, threshold-based expiration alerting, agent-side ECDSA P-256 key generation, API auth with rate limiting, and a React dashboard with 19 pages wired to the real API. The CI pipeline runs build, vet, test with coverage gates (service layer 30%+, handler layer 50%+), frontend type checking, Vitest test suite, and Vite production build on every push. Docker images are published to GitHub Container Registry on every version tag via the release workflow.
|
||||
### V1 (v1.0.0)
|
||||
Core lifecycle management — Local CA + ACME v2 issuers, NGINX target connector, agent-side key generation, API auth + rate limiting, React dashboard, CI pipeline with coverage gates, Docker images on GHCR.
|
||||
|
||||
### V2: Operational Maturity
|
||||
- **M10: Agent Metadata + Targets** ✅ — agents report OS, architecture, IP, hostname, version via heartbeat; Apache httpd and HAProxy target connectors
|
||||
- **M11: Crypto Policy + Profiles + Ownership** ✅ — certificate profiles (named enrollment profiles with allowed key types, max TTL, crypto constraints), certificate ownership tracking (owners + teams + notification routing), dynamic agent groups (OS/arch/IP CIDR/version matching), interactive renewal approval (AwaitingApproval state)
|
||||
- **M12: Sub-CA + DNS-01 + step-ca** ✅ — Local CA sub-CA mode (enterprise root chain with RSA/ECDSA/PKCS#8), ACME DNS-01 challenges (script-based DNS hooks for any provider, wildcard cert support), step-ca issuer connector (native /sign API with JWK provisioner auth)
|
||||
- **M15a: Core Revocation** ✅ — revocation API with all RFC 5280 reason codes, JSON CRL endpoint, webhook + email revocation notifications, best-effort issuer notification, `certificate_revocations` table with idempotent recording, 48 new tests
|
||||
- **M15b: OCSP + Revocation GUI** ✅ — embedded OCSP responder (GET /api/v1/ocsp/{issuer_id}/{serial}), DER-encoded X.509 CRL (GET /api/v1/crl/{issuer_id}), short-lived cert exemption (TTL < 1h skip CRL/OCSP), revocation GUI with reason modal, ~31 new tests
|
||||
- **M13: GUI Operations** ✅ — bulk cert operations (multi-select → renew, revoke, reassign owner), deployment status timeline, inline policy/profile editor, target connector configuration wizard, audit trail export (CSV/JSON), short-lived credentials dashboard view
|
||||
- **M14: Observability** ✅ — dashboard charts (expiration heatmap, cert status distribution, job trends, issuance rate), agent fleet overview with OS/arch grouping, JSON metrics endpoint, stats API (5 endpoints), structured logging with request IDs, deployment rollback
|
||||
- **M18a: MCP Server** ✅ (V2.1) — AI-native integration, all 78 REST API endpoints exposed as MCP tools for Claude, Cursor, OpenClaw, and any MCP-compatible client
|
||||
- **M19: Immutable API Audit Log** ✅ — every API call recorded to immutable audit trail (method, path, actor, SHA-256 body hash, status, latency), async recording via goroutine, configurable path exclusions
|
||||
- **M16a: Notifier Connectors** ✅ — Slack (incoming webhook), Microsoft Teams (MessageCard), PagerDuty (Events API v2), OpsGenie (Alert API v2) — config-driven enablement via env vars
|
||||
- **M17: Additional Connectors** ✅ — OpenSSL/Custom CA issuer connector (script-based signing with configurable timeout)
|
||||
- **M16b: CLI + Bulk Import** ✅ — `certctl-cli` with 10 subcommands (list/get/renew/revoke certs, list agents/jobs, health, metrics, PEM bulk import), stdlib-only, JSON/table output
|
||||
- **M20: Enhanced Query API** ✅ — sparse field selection (`?fields=`), sort with direction (`?sort=-notAfter`), time-range filters (`expires_before`, `created_after`, etc.), cursor-based pagination (`?cursor=&page_size=`), `GET /certificates/{id}/deployments`, additional filters (`agent_id`, `profile_id`)
|
||||
- **M18b: Filesystem Cert Discovery** ✅ — agents scan configured directories (PEM/DER), report findings to control plane, deduplication by SHA-256 fingerprint, claim/dismiss/triage workflow via API
|
||||
- **M21: Network Cert Discovery** ✅ — server-side active TLS scanning of CIDR ranges and ports, concurrent probing (50 goroutines), CIDR expansion with /20 safety cap, sentinel agent pattern for discovery pipeline reuse, CRUD API for scan targets, scheduler integration (6h default)
|
||||
- **M22: Prometheus Metrics** ✅ — `GET /api/v1/metrics/prometheus` returns Prometheus exposition format (`text/plain; version=0.0.4`), 11 metrics with `certctl_` prefix, compatible with Prometheus, Grafana Agent, Datadog Agent, Victoria Metrics
|
||||
- **Compliance Mapping** ✅ — SOC 2 Type II, PCI-DSS 4.0, NIST SP 800-57 capability mapping documentation
|
||||
|
||||
### V3: Team & Enterprise
|
||||
18 milestones complete, 950+ tests. See the [Feature Inventory](docs/features.md) for details on every capability.
|
||||
|
||||
**What shipped (all ✅):**
|
||||
|
||||
- **Issuers** — Sub-CA mode (enterprise root chains), ACME DNS-01 + DNS-PERSIST-01 (wildcard certs, any DNS provider), step-ca (native /sign API), OpenSSL/Custom CA (script-based signing)
|
||||
- **Revocation** — RFC 5280 reason codes, DER-encoded X.509 CRL, embedded OCSP responder, short-lived cert exemption
|
||||
- **Profiles + Ownership** — certificate profiles (key types, max TTL, crypto constraints), ownership tracking (owners + teams), dynamic agent groups, interactive renewal approval
|
||||
- **GUI Operations** — bulk renew/revoke/reassign, deployment timeline, inline policy editor, target wizard, audit export (CSV/JSON), short-lived credentials view
|
||||
- **Discovery** — filesystem scanning (PEM/DER) + network TLS scanning (CIDR ranges), triage workflow (claim/dismiss), network scan target management
|
||||
- **Observability** — Prometheus + JSON metrics, 5 stats API endpoints, dashboard charts (heatmap, trends, distribution), agent fleet overview, structured logging
|
||||
- **EST Server** (RFC 7030) — device/WiFi certificate enrollment, PKCS#7 wire format, configurable issuer + profile binding
|
||||
- **MCP Server** — 78 API operations as AI tools for Claude, Cursor, and any MCP-compatible client
|
||||
- **CLI** — 12 subcommands (list/get/renew/revoke certs, agents, jobs, import, status), JSON/table output
|
||||
- **Notifications** — Slack, Microsoft Teams, PagerDuty, OpsGenie connectors
|
||||
- **API Enhancements** — sparse fields, sort, time-range filters, cursor pagination, immutable API audit logging
|
||||
- **Compliance Mapping** — SOC 2 Type II, PCI-DSS 4.0, NIST SP 800-57 alignment guides
|
||||
|
||||
**Coming next:**
|
||||
|
||||
- **Post-Deployment TLS Verification** (v2.0.6) — agent-side TLS probe confirms the target is serving the correct certificate by SHA-256 fingerprint match
|
||||
- **Traefik + Caddy Targets** (v2.1.x) — Traefik (file provider, auto-reload) and Caddy (Admin API, hot-reload)
|
||||
- **Certificate Export** (v2.1.x) — single-cert download in PFX/PKCS12, DER, and PEM formats
|
||||
- **S/MIME Support** (v2.2.x) — profile EKU constraints for S/MIME (emailProtection), code signing, and custom EKUs
|
||||
|
||||
### V3: certctl Pro
|
||||
|
||||
Team access controls, identity provider integration, enterprise deployment targets, compliance and risk scoring, advanced fleet operations, event-driven architecture, advanced search, real-time operational views, and premium CA integrations.
|
||||
|
||||
### V4+: Cloud, Scale & Passive Discovery
|
||||
Passive network discovery (TLS listener), Kubernetes integration, cloud infrastructure targets (AWS ALB/ACM, Azure Key Vault), extended CA support, and platform-scale features.
|
||||
Passive network discovery (TLS listener), Kubernetes integration (cert-manager external issuer, Secrets target), cloud infrastructure targets (AWS ALB/ACM, Azure Key Vault), extended CA support (Vault PKI, Google CAS, EJBCA), and platform-scale features (Terraform provider, multi-tenancy, HSM support).
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -97,14 +97,18 @@ func main() {
|
||||
localCA := local.New(localCAConfig, logger)
|
||||
logger.Info("initialized Local CA issuer connector")
|
||||
|
||||
// Initialize ACME issuer connector (for Let's Encrypt, Sectigo, etc.)
|
||||
// Supports HTTP-01 (default) and DNS-01 (for wildcards) challenge types.
|
||||
// Initialize ACME issuer connector (for Let's Encrypt, ZeroSSL, Sectigo, Google Trust Services, etc.)
|
||||
// Supports HTTP-01 (default), DNS-01 (for wildcards), and DNS-PERSIST-01 (standing record) challenge types.
|
||||
// EAB (External Account Binding) required by ZeroSSL, Google Trust Services, SSL.com.
|
||||
acmeConnector := acmeissuer.New(&acmeissuer.Config{
|
||||
DirectoryURL: os.Getenv("CERTCTL_ACME_DIRECTORY_URL"),
|
||||
Email: os.Getenv("CERTCTL_ACME_EMAIL"),
|
||||
ChallengeType: os.Getenv("CERTCTL_ACME_CHALLENGE_TYPE"),
|
||||
DNSPresentScript: os.Getenv("CERTCTL_ACME_DNS_PRESENT_SCRIPT"),
|
||||
DNSCleanUpScript: os.Getenv("CERTCTL_ACME_DNS_CLEANUP_SCRIPT"),
|
||||
DirectoryURL: os.Getenv("CERTCTL_ACME_DIRECTORY_URL"),
|
||||
Email: os.Getenv("CERTCTL_ACME_EMAIL"),
|
||||
EABKid: os.Getenv("CERTCTL_ACME_EAB_KID"),
|
||||
EABHmac: os.Getenv("CERTCTL_ACME_EAB_HMAC"),
|
||||
ChallengeType: os.Getenv("CERTCTL_ACME_CHALLENGE_TYPE"),
|
||||
DNSPresentScript: os.Getenv("CERTCTL_ACME_DNS_PRESENT_SCRIPT"),
|
||||
DNSCleanUpScript: os.Getenv("CERTCTL_ACME_DNS_CLEANUP_SCRIPT"),
|
||||
DNSPersistIssuerDomain: os.Getenv("CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN"),
|
||||
}, logger)
|
||||
logger.Info("initialized ACME issuer connector")
|
||||
|
||||
@@ -302,6 +306,25 @@ func main() {
|
||||
discoveryHandler,
|
||||
networkScanHandler,
|
||||
)
|
||||
// Register EST (RFC 7030) handlers if enabled
|
||||
if cfg.EST.Enabled {
|
||||
issuerConn, ok := issuerRegistry[cfg.EST.IssuerID]
|
||||
if !ok {
|
||||
logger.Error("EST issuer not found in registry", "issuer_id", cfg.EST.IssuerID)
|
||||
os.Exit(1)
|
||||
}
|
||||
estService := service.NewESTService(cfg.EST.IssuerID, issuerConn, auditService, logger)
|
||||
if cfg.EST.ProfileID != "" {
|
||||
estService.SetProfileID(cfg.EST.ProfileID)
|
||||
}
|
||||
estHandler := handler.NewESTHandler(estService)
|
||||
apiRouter.RegisterESTHandlers(estHandler)
|
||||
logger.Info("EST server enabled",
|
||||
"issuer_id", cfg.EST.IssuerID,
|
||||
"profile_id", cfg.EST.ProfileID,
|
||||
"endpoints", "/.well-known/est/{cacerts,simpleenroll,simplereenroll,csrattrs}")
|
||||
}
|
||||
|
||||
logger.Info("registered all API handlers")
|
||||
|
||||
// Build middleware stack
|
||||
@@ -380,9 +403,10 @@ func main() {
|
||||
fileServer := http.FileServer(http.Dir(webDir))
|
||||
finalHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
// API and health routes go to the API handler
|
||||
// API, health, and EST routes go to the API handler
|
||||
if path == "/health" || path == "/ready" ||
|
||||
(len(path) >= 8 && path[:8] == "/api/v1/") {
|
||||
(len(path) >= 8 && path[:8] == "/api/v1/") ||
|
||||
(len(path) >= 16 && path[:16] == "/.well-known/est") {
|
||||
apiHandler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -12,8 +12,14 @@ services:
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ../migrations/000001_initial_schema.up.sql:/docker-entrypoint-initdb.d/001_schema.sql
|
||||
- ../migrations/seed.sql:/docker-entrypoint-initdb.d/002_seed.sql
|
||||
- ../migrations/seed_demo.sql:/docker-entrypoint-initdb.d/003_seed_demo.sql
|
||||
- ../migrations/000002_agent_metadata.up.sql:/docker-entrypoint-initdb.d/002_agent_metadata.sql
|
||||
- ../migrations/000003_certificate_profiles.up.sql:/docker-entrypoint-initdb.d/003_certificate_profiles.sql
|
||||
- ../migrations/000004_agent_groups.up.sql:/docker-entrypoint-initdb.d/004_agent_groups.sql
|
||||
- ../migrations/000005_revocation.up.sql:/docker-entrypoint-initdb.d/005_revocation.sql
|
||||
- ../migrations/000006_discovery.up.sql:/docker-entrypoint-initdb.d/006_discovery.sql
|
||||
- ../migrations/000007_network_discovery.up.sql:/docker-entrypoint-initdb.d/007_network_discovery.sql
|
||||
- ../migrations/seed.sql:/docker-entrypoint-initdb.d/010_seed.sql
|
||||
- ../migrations/seed_demo.sql:/docker-entrypoint-initdb.d/011_seed_demo.sql
|
||||
networks:
|
||||
- certctl-network
|
||||
healthcheck:
|
||||
@@ -39,6 +45,7 @@ services:
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
CERTCTL_AUTH_TYPE: none
|
||||
CERTCTL_KEYGEN_MODE: server # Demo uses server-side keygen; production should use "agent"
|
||||
CERTCTL_NETWORK_SCAN_ENABLED: "true" # Enable network scan GUI with seeded demo targets
|
||||
ports:
|
||||
- "8443:8443"
|
||||
networks:
|
||||
|
||||
@@ -1,5 +1,41 @@
|
||||
# Architecture Guide
|
||||
|
||||
## Contents
|
||||
|
||||
1. [Overview](#overview)
|
||||
2. [System Components](#system-components)
|
||||
- [Control Plane (Server)](#control-plane-server)
|
||||
- [Agents](#agents)
|
||||
- [Web Dashboard](#web-dashboard)
|
||||
- [PostgreSQL Database](#postgresql-database)
|
||||
3. [Data Flow: Certificate Lifecycle](#data-flow-certificate-lifecycle)
|
||||
- [Create Managed Certificate](#1-create-managed-certificate)
|
||||
- [Certificate Issuance](#2-certificate-issuance)
|
||||
- [Deploy Certificate to Target](#3-deploy-certificate-to-target)
|
||||
- [Revoke a Certificate](#35-revoke-a-certificate)
|
||||
- [Automatic Renewal](#4-automatic-renewal)
|
||||
4. [Connector Architecture](#connector-architecture)
|
||||
- [IssuerConnectorAdapter (Dependency Inversion)](#issuerconnectoradapter-dependency-inversion)
|
||||
- [Issuer Connector](#issuer-connector)
|
||||
- [Target Connector](#target-connector)
|
||||
- [Notifier Connector](#notifier-connector)
|
||||
- [EST Server (RFC 7030)](#est-server-rfc-7030)
|
||||
5. [Security Model](#security-model)
|
||||
- [Private Key Management](#private-key-management)
|
||||
- [Authentication](#authentication)
|
||||
- [Audit Trail](#audit-trail)
|
||||
- [API Audit Log](#api-audit-log)
|
||||
- [Logging](#logging)
|
||||
6. [API Design](#api-design)
|
||||
7. [MCP Server](#mcp-server)
|
||||
8. [CLI Tool](#cli-tool)
|
||||
9. [Deployment Topologies](#deployment-topologies)
|
||||
- [Docker Compose (Development / Small Deployments)](#docker-compose-development--small-deployments)
|
||||
- [Production (Kubernetes)](#production-kubernetes)
|
||||
10. [Discovery Data Flow (M18b + M21)](#discovery-data-flow-m18b--m21)
|
||||
11. [Testing Strategy](#testing-strategy)
|
||||
12. [What's Next](#whats-next)
|
||||
|
||||
## Overview
|
||||
|
||||
Certctl is a certificate management platform with a **decoupled control-plane and agent architecture**. The control plane orchestrates certificate issuance and renewal, while agents deployed across your infrastructure handle key generation, certificate deployment, and local validation — private keys never leave the infrastructure they were generated on.
|
||||
@@ -41,7 +77,7 @@ flowchart TB
|
||||
|
||||
subgraph "Issuer Backends"
|
||||
CA1["Local CA\n(crypto/x509, sub-CA)"]
|
||||
CA2["ACME\n(HTTP-01 + DNS-01)"]
|
||||
CA2["ACME\n(HTTP-01 + DNS-01 + DNS-PERSIST-01)\n(EAB, ZeroSSL auto-EAB)"]
|
||||
CA3["step-ca\n(/sign API)"]
|
||||
CA4["OpenSSL / Custom CA\n(script-based)"]
|
||||
CA6["Vault PKI\n(planned)"]
|
||||
@@ -76,7 +112,7 @@ The control plane is a Go HTTP server backed by PostgreSQL. It manages state (ce
|
||||
|
||||
The server exposes a REST API under `/api/v1/` and optionally serves the web dashboard as static files from the `web/` directory.
|
||||
|
||||
**Key internals**: The server uses Go 1.22's `net/http` stdlib routing (no external router framework), structured logging via `slog`, and a handler → service → repository layered architecture. Handlers define their own service interfaces for clean dependency inversion.
|
||||
**Key internals**: The server uses Go 1.25's `net/http` stdlib routing (no external router framework), structured logging via `slog`, and a handler → service → repository layered architecture. Handlers define their own service interfaces for clean dependency inversion.
|
||||
|
||||
### Agents
|
||||
|
||||
@@ -92,14 +128,14 @@ The agent runs two background loops: a heartbeat (every 60 seconds) to signal it
|
||||
|
||||
The web dashboard is the primary operational interface for certctl. It is built with Vite + React + TypeScript and uses TanStack Query for server state management (caching, background refetching, optimistic updates).
|
||||
|
||||
**Current views (19 pages)**: certificate inventory (list with multi-select bulk operations + "New Certificate" creation modal + detail with deployment status timeline, inline policy/profile editor, version history, deploy, revoke, archive, and trigger renewal actions), agent fleet (list + detail with system info + OS/architecture grouping with charts), job queue (status, retry, cancel, approve/reject), notification inbox (threshold alert grouping, mark-as-read), audit trail (time range, actor, action filters + CSV/JSON export), policy management (rules with enable/disable toggle + delete + violations), issuers (list with test connection + delete), targets (list with 3-step configuration wizard + delete), owners (list with team resolution + delete), teams (list with delete), agent groups (list with dynamic match criteria badges + enable/disable + delete), certificate profiles (list with crypto constraints), short-lived credentials dashboard (TTL countdown, profile filtering, auto-refresh), summary dashboard with charts (expiration heatmap, renewal success rate, status distribution, issuance rate), and login page.
|
||||
**Current views** (21 pages): certificate inventory (list with multi-select bulk operations + "New Certificate" creation modal + detail with deployment status timeline, inline policy/profile editor, version history, deploy, revoke, archive, and trigger renewal actions), agent fleet (list + detail with system info + OS/architecture grouping with charts), job queue (status, retry, cancel, approve/reject for AwaitingApproval jobs), notification inbox (threshold alert grouping, mark-as-read), audit trail (time range, actor, action filters + CSV/JSON export), policy management (rules with enable/disable toggle + delete + violations), issuers (list with test connection + delete), targets (list with 3-step configuration wizard + delete), owners (list with team resolution + delete), teams (list with delete), agent groups (list with dynamic match criteria badges + enable/disable + delete), certificate profiles (list with crypto constraints), short-lived credentials dashboard (TTL countdown, profile filtering, auto-refresh), discovered certificates triage (claim/dismiss unmanaged certs discovered by agents or network scans), network scan targets management (CRUD for network scan targets + Scan Now button), summary dashboard with charts (expiration heatmap, renewal success rate, status distribution, issuance rate), and login page.
|
||||
|
||||
The dashboard includes an **ErrorBoundary component** for graceful error recovery — if a view crashes, the boundary catches the error and displays a user-friendly message instead of breaking the entire dashboard. It also includes a **demo mode** that activates when the API is unreachable — it renders realistic mock data for screenshots and offline presentations.
|
||||
|
||||
**Tech decisions**:
|
||||
- Vite for fast builds and HMR during development
|
||||
- TanStack Query over manual fetch/useEffect for automatic cache invalidation and refetching
|
||||
- Dark theme default (ops teams live in dark mode)
|
||||
- Light content area with branded dark teal sidebar, Inter + JetBrains Mono typography
|
||||
- SSE/WebSocket planned for real-time job status updates
|
||||
|
||||
### PostgreSQL Database
|
||||
@@ -122,8 +158,11 @@ erDiagram
|
||||
managed_certificates ||--o{ policy_violations : "violates"
|
||||
managed_certificates ||--o{ audit_events : "logged in"
|
||||
managed_certificates ||--o{ notification_events : "generates"
|
||||
managed_certificates ||--o{ certificate_revocations : "revoked via"
|
||||
agent_groups ||--o{ agent_group_members : "has members"
|
||||
agents ||--o{ agent_group_members : "belongs to"
|
||||
agents ||--o{ discovered_certificates : "discovers"
|
||||
agents ||--o{ discovery_scans : "performs"
|
||||
|
||||
teams {
|
||||
text id PK
|
||||
@@ -242,6 +281,43 @@ erDiagram
|
||||
text agent_id FK
|
||||
text membership_type
|
||||
}
|
||||
renewal_policies {
|
||||
text id PK
|
||||
text certificate_id FK
|
||||
int renewal_days_before
|
||||
jsonb alert_thresholds_days
|
||||
boolean auto_renew
|
||||
text agent_group_id FK
|
||||
}
|
||||
certificate_revocations {
|
||||
text id PK
|
||||
text certificate_id FK
|
||||
text serial_number
|
||||
text reason
|
||||
timestamp revoked_at
|
||||
boolean issuer_notified
|
||||
}
|
||||
discovered_certificates {
|
||||
text id PK
|
||||
text agent_id FK
|
||||
text fingerprint_sha256
|
||||
text common_name
|
||||
text source_path
|
||||
text status
|
||||
}
|
||||
discovery_scans {
|
||||
text id PK
|
||||
text agent_id FK
|
||||
int certs_found
|
||||
timestamp scanned_at
|
||||
}
|
||||
network_scan_targets {
|
||||
text id PK
|
||||
text name
|
||||
text[] cidrs
|
||||
int[] ports
|
||||
boolean enabled
|
||||
}
|
||||
```
|
||||
|
||||
Migrations are idempotent (`IF NOT EXISTS` on all CREATE statements, `ON CONFLICT (id) DO NOTHING` on all seed data) so they're safe to run multiple times — important for Docker Compose where both initdb and the server may run the same SQL.
|
||||
@@ -481,10 +557,13 @@ type Connector interface {
|
||||
RenewCertificate(ctx context.Context, request RenewalRequest) (*IssuanceResult, error)
|
||||
RevokeCertificate(ctx context.Context, request RevocationRequest) error
|
||||
GetOrderStatus(ctx context.Context, orderID string) (*OrderStatus, error)
|
||||
GenerateCRL(ctx context.Context, revokedCerts []RevokedCertEntry) ([]byte, error)
|
||||
SignOCSPResponse(ctx context.Context, req OCSPSignRequest) ([]byte, error)
|
||||
GetCACertPEM(ctx context.Context) (string, error)
|
||||
}
|
||||
```
|
||||
|
||||
Built-in issuers: **Local CA** (self-signed or sub-CA mode using `crypto/x509`), **ACME v2** (HTTP-01 and DNS-01 challenges, compatible with Let's Encrypt, Sectigo, and any ACME-compliant CA), and **step-ca** (Smallstep private CA via native /sign API with JWK provisioner auth). The ACME connector uses `golang.org/x/crypto/acme`, generates an ECDSA P-256 account key, handles account registration with ToS acceptance, order creation, challenge solving (HTTP-01 via built-in server, DNS-01 via script-based hooks), order finalization, and DER-to-PEM chain conversion.
|
||||
Built-in issuers: **Local CA** (self-signed or sub-CA mode using `crypto/x509`), **ACME v2** (HTTP-01, DNS-01, and DNS-PERSIST-01 challenges, compatible with Let's Encrypt, ZeroSSL, Sectigo, Google Trust Services, and any ACME-compliant CA), **step-ca** (Smallstep private CA via native /sign API with JWK provisioner auth), and **OpenSSL/Custom CA** (script-based signing delegating to user-provided shell scripts). The ACME connector uses `golang.org/x/crypto/acme`, generates an ECDSA P-256 account key, handles account registration with ToS acceptance and optional External Account Binding (EAB) for CAs that require it (ZeroSSL, Google Trust Services, SSL.com), order creation, challenge solving (HTTP-01 via built-in server, DNS-01 via script-based hooks, DNS-PERSIST-01 via standing TXT records with auto-fallback to DNS-01), order finalization, and DER-to-PEM chain conversion. For ZeroSSL, EAB credentials are auto-fetched from ZeroSSL's public API when the directory URL is detected as ZeroSSL and no EAB credentials are provided — zero-friction onboarding with no dashboard visit required. The interface also includes `GetCACertPEM(ctx)` for CA chain distribution (used by the EST server's `/cacerts` endpoint).
|
||||
|
||||
### Target Connector
|
||||
|
||||
@@ -520,6 +599,45 @@ Built-in notifiers: **Email** (SMTP), **Webhook** (HTTP POST), **Slack** (incomi
|
||||
|
||||
See the [Connector Development Guide](connectors.md) for details on building custom connectors.
|
||||
|
||||
### EST Server (RFC 7030)
|
||||
|
||||
The EST (Enrollment over Secure Transport) server provides an industry-standard enrollment interface for devices that need certificates without using the REST API. It runs under `/.well-known/est/` per RFC 7030 and supports four operations: CA certificate distribution (`/cacerts`), initial enrollment (`/simpleenroll`), re-enrollment (`/simplereenroll`), and CSR attributes (`/csrattrs`).
|
||||
|
||||
**Architecture:** EST is a handler-level protocol that delegates certificate issuance to an existing `IssuerConnector`. This means EST is not a new issuer — it's a new *interface* to the existing issuance infrastructure. The `ESTService` bridges the `ESTHandler` to whichever issuer connector is configured via `CERTCTL_EST_ISSUER_ID`.
|
||||
|
||||
```
|
||||
Client (WiFi AP, MDM, IoT)
|
||||
│
|
||||
▼
|
||||
ESTHandler (handler layer)
|
||||
│ CSR parsing, PKCS#7 response encoding
|
||||
▼
|
||||
ESTService (service layer)
|
||||
│ CSR validation, CN/SAN extraction, audit recording
|
||||
▼
|
||||
IssuerConnector (connector layer via IssuerConnectorAdapter)
|
||||
│ Certificate signing (Local CA, step-ca, etc.)
|
||||
▼
|
||||
Signed certificate returned as PKCS#7 certs-only
|
||||
```
|
||||
|
||||
**Wire format:** EST uses PKCS#7 (RFC 2315) certs-only degenerate SignedData for certificate responses and base64-encoded DER for CSR requests. The handler includes a hand-rolled ASN.1 PKCS#7 builder — no external PKCS#7 dependency. The CSR reader accepts both base64-encoded DER (standard EST wire format) and PEM-encoded PKCS#10 (convenience for debugging).
|
||||
|
||||
**Interface:** The `ESTHandler` defines an `ESTService` interface (dependency inversion, same pattern as all other handlers):
|
||||
|
||||
```go
|
||||
type ESTService interface {
|
||||
GetCACerts(ctx context.Context) (string, error)
|
||||
SimpleEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error)
|
||||
SimpleReEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error)
|
||||
GetCSRAttrs(ctx context.Context) ([]byte, error)
|
||||
}
|
||||
```
|
||||
|
||||
**Issuer connector extension:** EST required adding `GetCACertPEM(ctx) (string, error)` to the issuer connector interface so the `/cacerts` endpoint can serve the CA chain. The Local CA connector returns its CA certificate PEM; ACME, step-ca, and OpenSSL connectors return errors (they don't expose a static CA chain — their chains are per-issuance).
|
||||
|
||||
**Audit:** Every EST enrollment is recorded in the audit trail with `protocol: "EST"`, the CN, SANs, issuer ID, serial number, and optional profile ID.
|
||||
|
||||
## Security Model
|
||||
|
||||
### Private Key Management
|
||||
@@ -606,9 +724,9 @@ All endpoints are under `/api/v1/` and follow consistent patterns:
|
||||
- **Delete**: `DELETE /api/v1/{resources}/{id}` — returns `204` (soft delete/archive)
|
||||
- **Actions**: `POST /api/v1/{resources}/{id}/{action}` — returns `202` for async operations
|
||||
|
||||
Resources: certificates, issuers, targets, agents, jobs, policies, profiles, teams, owners, agent-groups, audit, notifications.
|
||||
Resources: certificates, issuers, targets, agents, jobs, policies, profiles, teams, owners, agent-groups, audit, notifications, discovered-certificates, discovery-scans, network-scan-targets, stats, metrics.
|
||||
|
||||
The full API is documented in an OpenAPI 3.1 specification at `api/openapi.yaml` with 91 endpoints across 19 resource domains (including health, readiness, auth, 7 discovery endpoints from M18b, 6 network scan endpoints from M21, and Prometheus metrics from M22), all request/response schemas, and pagination conventions. See the [OpenAPI Guide](openapi.md) for usage with Swagger UI and SDK generation.
|
||||
The full API is documented in an OpenAPI 3.1 specification at `api/openapi.yaml` with 97 endpoints across 20 resource domains (95 under `/api/v1/` + `/.well-known/est/` plus `/health` and `/ready`; includes auth, 7 discovery endpoints from M18b, 6 network scan endpoints from M21, Prometheus metrics from M22, and 4 EST enrollment endpoints from M23), all request/response schemas, and pagination conventions. See the [OpenAPI Guide](openapi.md) for usage with Swagger UI and SDK generation.
|
||||
|
||||
Jobs support additional action endpoints: `POST /api/v1/jobs/{id}/cancel`, `POST /api/v1/jobs/{id}/approve`, `POST /api/v1/jobs/{id}/reject`.
|
||||
|
||||
@@ -654,7 +772,7 @@ The 78 tools are organized across 16 resource domains with typed input structs a
|
||||
|
||||
certctl ships with a command-line tool (`certctl-cli`, built from `cmd/cli/main.go`) that wraps the REST API for terminal workflows. The CLI uses Go's standard library only (`flag` + `text/tabwriter`) — no Cobra or other framework dependencies.
|
||||
|
||||
10 subcommands: `list-certs`, `get-cert`, `renew-cert`, `revoke-cert`, `list-agents`, `list-jobs`, `health`, `metrics`, and `import` (bulk PEM import). Output is available in table (default) or JSON format via `--format`. Connection is configured via `CERTCTL_SERVER_URL` and `CERTCTL_API_KEY` environment variables or CLI flags.
|
||||
12 subcommands organized by resource: `certs list`, `certs get`, `certs renew`, `certs revoke`, `agents list`, `agents get`, `jobs list`, `jobs get`, `jobs cancel`, `import` (bulk PEM import), `status` (health + summary stats), and `version`. Output is available in table (default) or JSON format via `--format`. Connection is configured via `CERTCTL_SERVER_URL` and `CERTCTL_API_KEY` environment variables or CLI flags.
|
||||
|
||||
The bulk import command (`certctl-cli import <file.pem>`) parses multi-certificate PEM files and creates certificate records via the API — useful for bootstrapping certctl with existing certificate inventory.
|
||||
|
||||
@@ -787,7 +905,7 @@ certctl uses a layered testing approach aligned with the handler → service →
|
||||
|
||||
**CI pipeline** (`.github/workflows/ci.yml`) — Two parallel jobs: Go (build, vet, test with coverage, coverage threshold enforcement) and Frontend (TypeScript type check, Vitest test suite, Vite production build). The Go job runs all tests with `-coverprofile`, then enforces coverage thresholds: service layer must be at least 30% (current: ~35%) and handler layer must be at least 50% (current: ~63%). These thresholds act as regression floors — they can only go up. The service layer threshold is deliberately lower because much of the service code depends on postgres repositories and external connectors that require real infrastructure to test meaningfully. Connector tests are included via `./internal/connector/issuer/...` and `./internal/connector/target/...` (covers Local CA, ACME, step-ca, NGINX, Apache, and HAProxy packages with unit tests for certificate signing logic, DNS solver, issuer validation, and deployment flows). The Frontend job runs `npx vitest run` between the TypeScript check and production build steps.
|
||||
|
||||
**Connector tests** (`internal/connector/`) — 57 test functions covering issuer, target, and notifier connectors. The Local CA connector has tests for self-signed and sub-CA modes (RSA, ECDSA, config validation, non-CA cert rejection). The ACME DNS solver has 6 tests for script-based DNS-01 challenges. The step-ca connector has tests with a mock HTTP server for issuance, renewal, revocation, and error paths. The OpenSSL/Custom CA connector has 14 tests covering config validation, issuance success/failure/timeout, renewal, revocation, and CRL generation. The NGINX target connector has 13 tests covering config validation, certificate deployment (file writing, permissions, validate/reload commands), and deployment validation. Apache httpd and HAProxy connectors each have 3 tests covering config validation, deployment, and validation flows. Notifier connector tests span 20 tests across Slack (5), Teams (4), PagerDuty (6), and OpsGenie (5) — verifying channel identity, payload formatting, HTTP error handling, connection failures, auth headers, and configuration defaults.
|
||||
**Connector tests** (`internal/connector/`) — 57 test functions covering issuer, target, and notifier connectors. The Local CA connector has tests for self-signed and sub-CA modes (RSA, ECDSA, config validation, non-CA cert rejection). The ACME DNS solver has 10 tests for script-based DNS-01 and DNS-PERSIST-01 challenges (6 DNS-01 tests + 4 DNS-PERSIST-01 tests covering `PresentPersist` success, no-script error, script failure, and wildcard domain handling). The step-ca connector has tests with a mock HTTP server for issuance, renewal, revocation, and error paths. The OpenSSL/Custom CA connector has 14 tests covering config validation, issuance success/failure/timeout, renewal, revocation, and CRL generation. The NGINX target connector has 13 tests covering config validation, certificate deployment (file writing, permissions, validate/reload commands), and deployment validation. Apache httpd and HAProxy connectors each have 3 tests covering config validation, deployment, and validation flows. Notifier connector tests span 20 tests across Slack (5), Teams (4), PagerDuty (6), and OpsGenie (5) — verifying channel identity, payload formatting, HTTP error handling, connection failures, auth headers, and configuration defaults.
|
||||
|
||||
**What's not tested and why:** Postgres repository implementations (`internal/repository/postgres/`) require a real database and are tested only through integration tests, not unit tests. Target connectors for F5 BIG-IP and IIS are interface stubs (implementation planned for a future release). Scheduler loops are time-dependent and tested manually during development. The ACME connector requires a real ACME server (tested manually against Let's Encrypt staging). These are all candidates for future expansion as the test infrastructure matures.
|
||||
|
||||
|
||||
@@ -2,6 +2,24 @@
|
||||
|
||||
NIST SP 800-57 Part 1 Rev 5 (May 2020) is the authoritative US government guidance on cryptographic key management. This document maps certctl's implementation to its recommendations. certctl follows NIST guidance where applicable; this guide documents the alignment and identifies gaps for future roadmap planning.
|
||||
|
||||
## Contents
|
||||
|
||||
1. [Key Generation (Section 6.1)](#key-generation-section-61)
|
||||
2. [Key Storage and Protection (Sections 6.3, 6.4)](#key-storage-and-protection-sections-63-64)
|
||||
3. [Cryptoperiods (Section 5.3, Table 1)](#cryptoperiods-section-53-table-1)
|
||||
4. [Key States and Transitions (Section 5.2)](#key-states-and-transitions-section-52)
|
||||
5. [Algorithm Recommendations (Section 5.1, SP 800-131A)](#algorithm-recommendations-section-51-sp-800-131a)
|
||||
6. [Key Distribution and Transport (Section 6.2)](#key-distribution-and-transport-section-62)
|
||||
7. [Revocation and Compromise (NIST SP 800-57 Part 3)](#revocation-and-compromise-nist-sp-800-57-part-3)
|
||||
8. [Alignment Summary Table](#alignment-summary-table)
|
||||
9. [Gaps and Remediation Roadmap](#gaps-and-remediation-roadmap)
|
||||
- [V2 (Current)](#v2-current)
|
||||
- [V3 (Planned: 2026)](#v3-planned-2026)
|
||||
- [V5 (Planned: 2027+)](#v5-planned-2027)
|
||||
- [Post-Quantum (2027+)](#post-quantum-2027)
|
||||
10. [References](#references)
|
||||
11. [Questions or Corrections?](#questions-or-corrections)
|
||||
|
||||
## Key Generation (Section 6.1)
|
||||
|
||||
certctl generates certificate keys on agent infrastructure using Go's `crypto/rand` for entropy, backed by `/dev/urandom` on Linux and `CryptGenRandom` on Windows. Key generation happens as follows:
|
||||
@@ -15,7 +33,7 @@ certctl generates certificate keys on agent infrastructure using Go's `crypto/ra
|
||||
|
||||
**Server-Side Key Generation (Demo Only)**
|
||||
- Available for development and testing via `CERTCTL_KEYGEN_MODE=server`
|
||||
- Explicitly logged as a warning at startup: "server-side keygen enabled (production deployments must use agent mode)"
|
||||
- Explicitly logged as a warning at startup: "server-side key generation enabled (CERTCTL_KEYGEN_MODE=server) — private keys touch control plane, demo only"
|
||||
- Docker Compose demo uses server mode for backward compatibility
|
||||
- Not recommended for production; agent mode is the secure default
|
||||
|
||||
|
||||
@@ -4,6 +4,34 @@ This guide maps certctl's existing capabilities to PCI-DSS 4.0 requirements rele
|
||||
|
||||
Organizations subject to PCI-DSS typically need to demonstrate control over certificate issuance, renewal, rotation, revocation, and key management. Certctl automates the technical controls for certificate lifecycle; compliance depends on how you deploy, monitor, and audit it.
|
||||
|
||||
## Contents
|
||||
|
||||
1. [How to Use This Guide](#how-to-use-this-guide)
|
||||
2. [Requirement 4: Protect Data in Transit](#requirement-4-protect-data-in-transit)
|
||||
- [4.2.1 — Strong Cryptography for Transmission](#421--strong-cryptography-for-transmission)
|
||||
- [4.2.2 — Certificate Inventory and Validation](#422--certificate-inventory-and-validation)
|
||||
3. [Requirement 3: Protect Stored Cardholder Data (Key Management)](#requirement-3-protect-stored-cardholder-data-key-management)
|
||||
- [3.6 — Cryptographic Key Documentation](#36--cryptographic-key-documentation)
|
||||
- [3.7 — Key Lifecycle Procedures](#37--key-lifecycle-procedures)
|
||||
4. [Requirement 8: Identify and Authenticate](#requirement-8-identify-and-authenticate)
|
||||
- [8.3 — Strong Authentication](#83--strong-authentication)
|
||||
- [8.6 — Application Account Management](#86--application-account-management)
|
||||
5. [Requirement 10: Log and Monitor](#requirement-10-log-and-monitor)
|
||||
- [10.2 — Implement Automated Audit Logging](#102--implement-automated-audit-logging)
|
||||
- [10.3 — Protect Audit Trail](#103--protect-audit-trail)
|
||||
- [10.4 — Promptly Review and Address Audit Trail Exceptions](#104--promptly-review-and-address-audit-trail-exceptions)
|
||||
- [10.7 — Retain and Protect Audit Trail History](#107--retain-and-protect-audit-trail-history)
|
||||
6. [Requirement 6: Develop and Maintain Secure Systems and Applications](#requirement-6-develop-and-maintain-secure-systems-and-applications)
|
||||
- [6.3.1 — Security Coding Practices](#631--security-coding-practices)
|
||||
- [6.5.10 — Broken Authentication and Cryptography Prevention](#6510--broken-authentication-and-cryptography-prevention)
|
||||
7. [Requirement 7: Restrict Access by Business Need-to-Know](#requirement-7-restrict-access-by-business-need-to-know)
|
||||
- [7.2 — Implement Access Control](#72--implement-access-control)
|
||||
8. [Evidence Summary Table](#evidence-summary-table)
|
||||
9. [Operator Responsibilities](#operator-responsibilities)
|
||||
10. [V3 Enhancements for PCI-DSS](#v3-enhancements-for-pci-dss)
|
||||
11. [Next Steps for Compliance](#next-steps-for-compliance)
|
||||
12. [Questions?](#questions)
|
||||
|
||||
## How to Use This Guide
|
||||
|
||||
Your QSA will request evidence that your certificate and key management systems meet specific PCI-DSS 4.0 requirements. For each applicable requirement, this guide identifies:
|
||||
@@ -168,7 +196,7 @@ This requirement covers key generation, storage, rotation, and destruction. Cert
|
||||
- **Server-Side Fallback** (demo/development only) — `CERTCTL_KEYGEN_MODE=server`:
|
||||
- Control plane generates RSA 2048-bit or ECDSA P-256 keys using `crypto/rand` + `crypto/rsa`.
|
||||
- Server signs CSR and stores the private key in the certificate version record for agent deployment. **Security note:** In server keygen mode, the control plane holds private keys — this is why agent keygen mode is the recommended default for production.
|
||||
- **Must not be used in production.** Explicit warning logged: `Key generation mode is server; this should only be used for testing.`
|
||||
- **Must not be used in production.** Explicit warning logged: `server-side key generation enabled (CERTCTL_KEYGEN_MODE=server) — private keys touch control plane, demo only`
|
||||
|
||||
- **Issuer-Specific Key Negotiation**:
|
||||
- **ACME (Let's Encrypt, ZeroSSL)**: Let's Encrypt controls key types; certctl requests ECDSA P-256 by default.
|
||||
@@ -178,7 +206,7 @@ This requirement covers key generation, storage, rotation, and destruction. Cert
|
||||
|
||||
**Evidence You Can Provide**:
|
||||
- Deployment configuration: `CERTCTL_KEYGEN_MODE=agent` in production (verify in `docker-compose.yml`, Kubernetes manifests, or systemd units).
|
||||
- Agent log excerpt showing key generation: `openssl genrsa...` or agent process logs with CSR submission timestamp.
|
||||
- Agent log excerpt showing key generation: Go `crypto/ecdsa.GenerateKey(elliptic.P256())` via agent process logs with CSR submission timestamp.
|
||||
- Certificate CSR audit: `GET /api/v1/audit?type=certificate_issued` showing CSR fingerprint (SHA-256 hash of CSR PEM).
|
||||
- Renewal job logs showing agent-submitted CSR, not server-generated key.
|
||||
|
||||
@@ -205,7 +233,7 @@ This requirement covers key generation, storage, rotation, and destruction. Cert
|
||||
- **Control Plane Key Storage** — Sensitive credentials managed via environment variables or `.env` files:
|
||||
- CA private key path: `CERTCTL_CA_CERT_PATH` + `CERTCTL_CA_KEY_PATH` (for Local CA sub-CA mode).
|
||||
- ACME account key: embedded in ACME issuer config (not stored separately; ACME library handles in memory).
|
||||
- step-ca provisioner key: `CERTCTL_STEPCA_PROVISIONER_KEY` env var (JWK, in memory during runtime).
|
||||
- step-ca provisioner key: `CERTCTL_STEPCA_KEY_PATH` env var (path to JWK private key file, loaded into memory during runtime).
|
||||
- API keys: `CERTCTL_API_KEY` (SHA-256 hashed in database, plaintext never stored).
|
||||
- Database credentials: `CERTCTL_DATABASE_URL` in `.env` file, not in source code.
|
||||
|
||||
@@ -785,7 +813,7 @@ Certctl v3 (Pro) adds paid features that strengthen PCI-DSS compliance posture:
|
||||
For additional guidance on certctl features and PCI-DSS mapping:
|
||||
- Review the [Architecture Guide](architecture.md) for system design.
|
||||
- Check [Connectors Documentation](connectors.md) for issuer/target/notifier capabilities.
|
||||
- Run the [Demo Guide](demo-guide.md) to see features in action.
|
||||
- Run the [Quick Start Guide](quickstart.md) to see features in action.
|
||||
- Consult your QSA for final compliance determination.
|
||||
|
||||
**Last Updated**: March 24, 2026 (certctl v1.0 with M18b discovery and M19 audit logging)
|
||||
|
||||
@@ -14,6 +14,28 @@ Each section includes:
|
||||
- **V2 vs V3 status** — whether feature is in the free community edition (V2) or paid Pro edition (V3)
|
||||
- **Operator responsibility** — aspects your organization must handle outside of certctl
|
||||
|
||||
## Contents
|
||||
|
||||
1. [How to Use This Guide](#how-to-use-this-guide)
|
||||
2. [CC6: Logical and Physical Access Controls](#cc6-logical-and-physical-access-controls)
|
||||
- [CC6.1 — Logical Access Security](#cc61--logical-access-security)
|
||||
- [CC6.2 — Prior to Issuing System Credentials](#cc62--prior-to-issuing-system-credentials)
|
||||
- [CC6.3 — Authentication Policies](#cc63--authentication-policies)
|
||||
- [CC6.7 — Information Transmission Protection](#cc67--information-transmission-protection)
|
||||
3. [CC7: System Operations](#cc7-system-operations)
|
||||
- [CC7.1 — System Monitoring](#cc71--system-monitoring)
|
||||
- [CC7.2 — Anomaly Detection](#cc72--anomaly-detection)
|
||||
- [CC7.3 — Incident Response](#cc73--incident-response)
|
||||
- [CC7.4 — Identify and Develop Risk Mitigation Activities](#cc74--identify-and-develop-risk-mitigation-activities)
|
||||
4. [A1: Availability](#a1-availability)
|
||||
- [A1.1/A1.2 — Availability and Recovery](#a11a12--availability-and-recovery)
|
||||
5. [CC8: Change Management](#cc8-change-management)
|
||||
- [CC8.1 — Change Control](#cc81--change-control)
|
||||
6. [Evidence Summary Table](#evidence-summary-table)
|
||||
7. [What Requires Operator Action](#what-requires-operator-action)
|
||||
8. [V3 Enhancements](#v3-enhancements)
|
||||
9. [Conclusion](#conclusion)
|
||||
|
||||
## CC6: Logical and Physical Access Controls
|
||||
|
||||
### CC6.1 — Logical Access Security
|
||||
@@ -89,7 +111,7 @@ Each section includes:
|
||||
|
||||
- **API Key Policy** — All API access requires an API key or explicit opt-out. Opt-out (`CERTCTL_AUTH_TYPE=none`) logs a warning: "WARNING: Auth disabled (CERTCTL_AUTH_TYPE=none) — this is insecure and only for development". Configuration choice is logged at startup.
|
||||
- **Agent Authentication** — Agents authenticate to the server via API keys (same mechanism as users). Agent credentials are separate from user API keys.
|
||||
- **Private Key Policy** — Agent-side key generation is the default (`CERTCTL_KEYGEN_MODE=agent`). Server-side keygen (`CERTCTL_KEYGEN_MODE=server`) requires explicit configuration and logs a warning: "Server-side keygen enabled — private keys will be stored in PostgreSQL (development only)".
|
||||
- **Private Key Policy** — Agent-side key generation is the default (`CERTCTL_KEYGEN_MODE=agent`). Server-side keygen (`CERTCTL_KEYGEN_MODE=server`) requires explicit configuration and logs a warning: "server-side key generation enabled (CERTCTL_KEYGEN_MODE=server) — private keys touch control plane, demo only".
|
||||
- **Password Policy** — Not applicable; certctl uses API keys exclusively. Password management is delegated to your organization's IAM system if you integrate OIDC/SSO (V3).
|
||||
|
||||
**Evidence Locations**:
|
||||
@@ -119,7 +141,7 @@ Each section includes:
|
||||
|
||||
**certctl Implementation** (V2):
|
||||
|
||||
- **TLS for Control Plane** — All API communication occurs over HTTPS (TLS 1.2+). Server uses `tls.Dial()` for outbound connections to issuers and targets. Configuration: `CERTCTL_SERVER_ADDR` (default `:8443`).
|
||||
- **TLS for Control Plane** — All API communication occurs over HTTPS (TLS 1.2+). Server uses `tls.Dial()` for outbound connections to issuers and targets. Configuration: `CERTCTL_SERVER_HOST` (default `127.0.0.1`) + `CERTCTL_SERVER_PORT` (default `8080`; Docker Compose maps to `8443`).
|
||||
- **Agent-to-Server Communication** — Agents submit CSRs and heartbeats over HTTPS to the server using the same TLS stack.
|
||||
- **Private Key Isolation** — Agents generate ECDSA P-256 private keys locally (`crypto/ecdsa` + `crypto/elliptic`). Private keys are never transmitted to the server — agents submit CSRs only. Private keys are stored on agent filesystem (`CERTCTL_KEY_DIR`, default `/var/lib/certctl/keys`) with 0600 (owner read/write only) permissions. Server-side keygen mode logs a development warning; production must use agent-side keygen.
|
||||
- **Certificate Storage** — Signed certificates are stored in PostgreSQL as PEM text (along with metadata). Certificates are not secrets and may be transmitted plaintext. Private keys are never stored on the control plane in production (agent-side keygen mode).
|
||||
|
||||
@@ -2,6 +2,41 @@
|
||||
|
||||
If you've never worked with TLS certificates before, this guide will get you up to speed. By the end, you'll understand what certificates are, why they matter, and why the industry's move toward shorter certificate lifespans — down to 47 days by 2029 — makes automated lifecycle management essential.
|
||||
|
||||
## Contents
|
||||
|
||||
1. [What Is a TLS Certificate?](#what-is-a-tls-certificate)
|
||||
2. [Why Do Certificates Expire?](#why-do-certificates-expire)
|
||||
3. [The Cast of Characters](#the-cast-of-characters)
|
||||
- [Certificate Authority (CA)](#certificate-authority-ca)
|
||||
- [ACME Protocol](#acme-protocol)
|
||||
- [EST Protocol (Enrollment over Secure Transport)](#est-protocol-enrollment-over-secure-transport)
|
||||
- [Private Key](#private-key)
|
||||
- [Subject Alternative Names (SANs)](#subject-alternative-names-sans)
|
||||
- [Certificate Chain](#certificate-chain)
|
||||
4. [How certctl Works](#how-certctl-works)
|
||||
- [The Control Plane (Server)](#the-control-plane-server)
|
||||
- [Agents](#agents)
|
||||
- [Deployment Targets](#deployment-targets)
|
||||
5. [The Certificate Lifecycle](#the-certificate-lifecycle)
|
||||
6. [Why Not Just Use Certbot?](#why-not-just-use-certbot)
|
||||
7. [Key Concepts in certctl](#key-concepts-in-certctl)
|
||||
- [Teams and Owners](#teams-and-owners)
|
||||
- [Agent Groups](#agent-groups)
|
||||
- [Certificate Profiles](#certificate-profiles)
|
||||
- [Interactive Renewal Approval](#interactive-renewal-approval)
|
||||
- [Certificate Revocation](#certificate-revocation)
|
||||
- [Short-Lived Certificates](#short-lived-certificates)
|
||||
- [Policies](#policies)
|
||||
- [Jobs](#jobs)
|
||||
- [Audit Trail](#audit-trail)
|
||||
- [Notifications](#notifications)
|
||||
- [CLI](#cli)
|
||||
- [MCP Server (AI Integration)](#mcp-server-ai-integration)
|
||||
- [EST Enrollment (Device Certificates)](#est-enrollment-device-certificates)
|
||||
- [Certificate Discovery](#certificate-discovery)
|
||||
- [Observability](#observability)
|
||||
8. [What's Next](#whats-next)
|
||||
|
||||
## What Is a TLS Certificate?
|
||||
|
||||
When you visit `https://yourbank.com`, your browser checks a digital document called a **TLS certificate** before sending any data. That certificate proves two things: (1) you're really talking to yourbank.com and not an imposter, and (2) everything sent between you and the server is encrypted.
|
||||
@@ -34,9 +69,17 @@ certctl includes a built-in **Local CA** that can operate in two modes: self-sig
|
||||
|
||||
### ACME Protocol
|
||||
|
||||
ACME (Automatic Certificate Management Environment) is the protocol Let's Encrypt created for automated certificate issuance. Instead of filling out forms and waiting for emails, ACME lets software request, validate, and receive certificates programmatically. The server proves domain ownership by responding to challenges — placing a specific file on the web server (HTTP-01) or creating a DNS record (DNS-01).
|
||||
ACME (Automatic Certificate Management Environment) is the protocol Let's Encrypt created for automated certificate issuance. Instead of filling out forms and waiting for emails, ACME lets software request, validate, and receive certificates programmatically. The server proves domain ownership by responding to challenges — placing a specific file on the web server (HTTP-01), creating a DNS record (DNS-01), or maintaining a standing DNS record that persists across renewals (DNS-PERSIST-01).
|
||||
|
||||
certctl speaks ACME natively with both HTTP-01 and DNS-01 challenges, so it can request certificates — including wildcard certificates — from Let's Encrypt or any ACME-compatible CA without manual intervention. HTTP-01 uses a built-in temporary HTTP server for domain validation; DNS-01 uses pluggable script-based hooks to create TXT records with any DNS provider (Cloudflare, Route53, Azure DNS, etc.).
|
||||
certctl speaks ACME natively with HTTP-01, DNS-01, and DNS-PERSIST-01 challenges, so it can request certificates — including wildcard certificates — from Let's Encrypt or any ACME-compatible CA without manual intervention. HTTP-01 uses a built-in temporary HTTP server for domain validation; DNS-01 uses pluggable script-based hooks to create TXT records with any DNS provider (Cloudflare, Route53, Azure DNS, etc.); DNS-PERSIST-01 creates a standing `_validation-persist` TXT record once (containing the CA domain and account URI) that the CA revalidates on every renewal — no per-renewal DNS updates needed. If the CA doesn't yet support DNS-PERSIST-01, certctl automatically falls back to DNS-01.
|
||||
|
||||
### EST Protocol (Enrollment over Secure Transport)
|
||||
|
||||
EST (RFC 7030) is a standard protocol for devices to request certificates from a CA. While ACME was designed for web servers proving domain ownership, EST was designed for devices that need certificates without domain validation — think WiFi access points, corporate laptops connecting to 802.1X networks, IoT devices, and mobile devices managed by MDM platforms.
|
||||
|
||||
The workflow is straightforward: a device generates a key pair and a Certificate Signing Request (CSR), sends the CSR to the EST server, and gets back a signed certificate. The EST server also distributes its CA certificate chain so devices can build a complete trust path.
|
||||
|
||||
certctl includes a built-in EST server at `/.well-known/est/` with four operations: distributing the CA certificate chain (`/cacerts`), enrolling new devices (`/simpleenroll`), renewing existing certificates (`/simplereenroll`), and advertising CSR requirements (`/csrattrs`). EST enrollment uses the same issuer connectors as the REST API — so a certificate issued via EST and a certificate issued via the dashboard go through the same CA, appear in the same inventory, and follow the same policies.
|
||||
|
||||
### Private Key
|
||||
|
||||
@@ -180,16 +223,22 @@ certctl can alert you when certificates are expiring, when renewals fail, when d
|
||||
|
||||
### CLI
|
||||
|
||||
certctl ships with a command-line tool (`certctl-cli`) for operators who prefer terminal workflows or need to integrate certctl into shell scripts and CI/CD pipelines. The CLI wraps the REST API with 10 subcommands: `list-certs`, `get-cert`, `renew-cert`, `revoke-cert`, `list-agents`, `list-jobs`, `health`, `metrics`, and `import` (for bulk PEM import).
|
||||
certctl ships with a command-line tool (`certctl-cli`) for operators who prefer terminal workflows or need to integrate certctl into shell scripts and CI/CD pipelines. The CLI wraps the REST API with 12 subcommands organized by resource: `certs list`, `certs get`, `certs renew`, `certs revoke`, `agents list`, `agents get`, `jobs list`, `jobs get`, `jobs cancel`, `import` (bulk PEM import), `status` (health + summary stats), and `version`.
|
||||
|
||||
The CLI supports both table and JSON output formats (`--format table` or `--format json`), connects to the server via `CERTCTL_SERVER_URL` and authenticates with `CERTCTL_API_KEY`. It's built with Go's standard library only — no external dependencies.
|
||||
|
||||
### MCP Server (AI Integration)
|
||||
|
||||
certctl includes an MCP (Model Context Protocol) server that exposes all 78 API endpoints as MCP tools. This enables AI assistants like Claude, Cursor, and other MCP-compatible tools to interact with your certificate infrastructure using natural language — "show me all expiring certificates," "revoke the VPN cert," or "what agents are offline?"
|
||||
certctl includes an MCP (Model Context Protocol) server that exposes 78 MCP tools covering the REST API. This enables AI assistants like Claude, Cursor, and other MCP-compatible tools to interact with your certificate infrastructure using natural language — "show me all expiring certificates," "revoke the VPN cert," or "what agents are offline?"
|
||||
|
||||
The MCP server is a separate binary (`cmd/mcp-server/`) that communicates via stdio transport and acts as a stateless HTTP proxy to the certctl REST API. It requires no additional infrastructure — just point it at your certctl server URL and API key.
|
||||
|
||||
### EST Enrollment (Device Certificates)
|
||||
|
||||
certctl's EST server enables device certificate enrollment for use cases that don't fit the traditional "ops team requests a cert via API" model. When a RADIUS server is configured to use certctl for 802.1X WiFi authentication, or an MDM platform enrolls corporate devices, they use the EST protocol at `/.well-known/est/`. The EST server validates the CSR, issues a certificate via the configured issuer connector, and returns it in PKCS#7 format — the standard wire format that every EST client understands. Each enrollment is recorded in the audit trail with the protocol, common name, SANs, issuer, and serial number.
|
||||
|
||||
Enable it with `CERTCTL_EST_ENABLED=true`. Optionally bind enrollments to a specific issuer (`CERTCTL_EST_ISSUER_ID`) or certificate profile (`CERTCTL_EST_PROFILE_ID`) to constrain what EST clients can request.
|
||||
|
||||
### Certificate Discovery
|
||||
|
||||
Certificate discovery is the process of automatically finding existing certificates in your infrastructure — certificates you didn't issue through certctl, possibly issued by other CAs or tools. This is essential for building a complete inventory before you can manage everything.
|
||||
@@ -197,10 +246,12 @@ Certificate discovery is the process of automatically finding existing certifica
|
||||
**How it works:** There are two discovery modes. *Filesystem discovery* — agents scan configured directories (configured via `CERTCTL_DISCOVERY_DIRS`) for certificate files. On startup and every 6 hours, the agent walks directories recursively, parses PEM and DER files, extracts metadata, and reports findings to the control plane. *Network discovery* — the control plane itself probes TLS endpoints across configured CIDR ranges and ports (enabled via `CERTCTL_NETWORK_SCAN_ENABLED=true`). It connects to each endpoint, extracts certificates from the TLS handshake, and feeds results into the same discovery pipeline. This finds certificates on services you may not have agents on. In both cases, the server deduplicates by fingerprint and stores discovered certs with a status: **Unmanaged** (discovered but not yet managed), **Managed** (linked to a control plane cert), or **Dismissed** (operator decided not to manage it).
|
||||
|
||||
This gives you a three-step triage workflow:
|
||||
1. **Discover** — Agents find all existing certs on your infrastructure
|
||||
2. **Triage** — Operators review discoveries and decide: claim it (enroll for management), or dismiss it (not worth managing)
|
||||
1. **Discover** — Agents scan filesystems and the server probes network endpoints to find all existing certs
|
||||
2. **Triage** — Operators review discoveries in the **Discovery** dashboard page and decide: claim it (link to a managed certificate) or dismiss it (not worth managing). The dashboard shows a summary stats bar (Unmanaged/Managed/Dismissed counts), filters by status and agent, and provides one-click claim and dismiss actions.
|
||||
3. **Baseline** — Once triaged, you have a complete baseline of what's deployed, what you're managing, and what's unmanaged
|
||||
|
||||
Network scan targets are managed from the **Network Scans** dashboard page — create CIDR ranges and ports to probe, enable/disable targets, trigger on-demand scans, and view results. Discovered certificates from network scans appear in the same Discovery triage page alongside filesystem discoveries.
|
||||
|
||||
This is a prerequisite for multi-CA migration, compliance audits, and building confidence that you've found all the certificates that matter.
|
||||
|
||||
### Observability
|
||||
|
||||
@@ -2,11 +2,54 @@
|
||||
|
||||
Connectors extend certctl to integrate with external systems for certificate issuance, deployment, and notifications. This guide covers the connector interfaces, built-in implementations, and how to build your own.
|
||||
|
||||
## Contents
|
||||
|
||||
1. [Overview](#overview)
|
||||
2. [Issuer Connector](#issuer-connector)
|
||||
- [Interface](#interface)
|
||||
- [Built-in: Local CA](#built-in-local-ca)
|
||||
- [Built-in: ACME v2 (Let's Encrypt, Sectigo, ZeroSSL)](#built-in-acme-v2-lets-encrypt-sectigo-zerossl)
|
||||
- [Built-in: step-ca (Smallstep Private CA)](#built-in-step-ca-smallstep-private-ca)
|
||||
- [OpenSSL / Custom CA](#openssl--custom-ca)
|
||||
- [Revocation Across Issuers](#revocation-across-issuers)
|
||||
- [EST Integration (GetCACertPEM)](#est-integration-getcacertpem)
|
||||
- [Planned Issuers](#planned-issuers)
|
||||
- [Building a Custom Issuer](#building-a-custom-issuer)
|
||||
3. [Target Connector](#target-connector)
|
||||
- [Interface](#interface-1)
|
||||
- [Built-in: NGINX](#built-in-nginx)
|
||||
- [Built-in: Apache httpd](#built-in-apache-httpd)
|
||||
- [Built-in: HAProxy](#built-in-haproxy)
|
||||
- [F5 BIG-IP (Interface Only)](#f5-big-ip-interface-only)
|
||||
- [IIS (Interface Only, Dual-Mode)](#iis-interface-only-dual-mode)
|
||||
4. [Notifier Connector](#notifier-connector)
|
||||
- [Interface](#interface-2)
|
||||
5. [Registering a Connector](#registering-a-connector)
|
||||
- [IssuerConnectorAdapter](#issuerconnectoradapter)
|
||||
- [Notifier Registration](#notifier-registration)
|
||||
6. [Testing Connectors](#testing-connectors)
|
||||
- [Unit Tests](#unit-tests)
|
||||
- [Integration Tests](#integration-tests)
|
||||
7. [Best Practices](#best-practices)
|
||||
8. [Agent Discovery Scanner](#agent-discovery-scanner)
|
||||
- [Configuration](#configuration)
|
||||
- [How It Works](#how-it-works)
|
||||
- [API Endpoints](#api-endpoints)
|
||||
- [Use Cases](#use-cases)
|
||||
9. [Network Certificate Scanner (M21)](#network-certificate-scanner-m21)
|
||||
- [Configuration](#configuration-1)
|
||||
- [Creating Scan Targets](#creating-scan-targets)
|
||||
- [How It Works](#how-it-works-1)
|
||||
- [API Endpoints](#api-endpoints-1)
|
||||
- [Scheduler Integration](#scheduler-integration)
|
||||
- [Use Cases](#use-cases-1)
|
||||
10. [What's Next](#whats-next)
|
||||
|
||||
## Overview
|
||||
|
||||
Three types of connectors:
|
||||
|
||||
1. **Issuer Connector** — Obtains certificates from CAs (Local CA with sub-CA support, ACME with HTTP-01 + DNS-01, step-ca, OpenSSL/Custom CA implemented; additional CA integrations planned)
|
||||
1. **Issuer Connector** — Obtains certificates from CAs (Local CA with sub-CA support, ACME with HTTP-01 + DNS-01 + DNS-PERSIST-01, step-ca, OpenSSL/Custom CA implemented; additional CA integrations planned)
|
||||
2. **Target Connector** — Deploys certificates to infrastructure (NGINX, Apache httpd, HAProxy implemented; F5 via proxy agent, IIS dual-mode interface only; additional cloud and network targets planned)
|
||||
3. **Notifier Connector** — Sends alerts about certificate events (Email, Webhooks, Slack, Microsoft Teams, PagerDuty, OpsGenie implemented)
|
||||
|
||||
@@ -37,6 +80,19 @@ type Connector interface {
|
||||
|
||||
// GetOrderStatus checks the status of an async issuance order
|
||||
GetOrderStatus(ctx context.Context, orderID string) (*OrderStatus, error)
|
||||
|
||||
// GenerateCRL generates a DER-encoded X.509 CRL signed by this issuer.
|
||||
// Returns nil if the issuer does not support CRL generation (e.g., ACME).
|
||||
GenerateCRL(ctx context.Context, revokedCerts []RevokedCertEntry) ([]byte, error)
|
||||
|
||||
// SignOCSPResponse signs an OCSP response for the given certificate serial.
|
||||
// Returns nil if the issuer does not support OCSP (e.g., ACME).
|
||||
SignOCSPResponse(ctx context.Context, req OCSPSignRequest) ([]byte, error)
|
||||
|
||||
// GetCACertPEM returns the PEM-encoded CA certificate chain for this issuer.
|
||||
// Used by the EST server's /cacerts endpoint (RFC 7030).
|
||||
// Returns error if the issuer doesn't provide a static CA chain (e.g., ACME, step-ca).
|
||||
GetCACertPEM(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
type IssuanceRequest struct {
|
||||
@@ -103,12 +159,14 @@ Location: `internal/connector/issuer/local/local.go`
|
||||
|
||||
### Built-in: ACME v2 (Let's Encrypt, Sectigo, ZeroSSL)
|
||||
|
||||
The ACME connector implements the full ACME v2 protocol using Go's `golang.org/x/crypto/acme` package. It supports two challenge methods:
|
||||
The ACME connector implements the full ACME v2 protocol using Go's `golang.org/x/crypto/acme` package. It supports three challenge methods:
|
||||
|
||||
**HTTP-01 (default):** A built-in temporary HTTP server starts on demand during certificate issuance. The domain being validated must resolve to the machine running the connector, and the configured HTTP port must be reachable from the internet.
|
||||
|
||||
**DNS-01 (for wildcards):** Creates DNS TXT records via user-provided scripts. Required for wildcard certificates (`*.example.com`) and hosts that can't serve HTTP on port 80. The connector invokes external scripts to create and clean up `_acme-challenge` TXT records, making it compatible with any DNS provider (Cloudflare, Route53, Azure DNS, etc.).
|
||||
|
||||
**DNS-PERSIST-01 (standing record):** Creates a one-time persistent TXT record at `_validation-persist.<domain>` containing the CA's issuer domain and your ACME account URI. Once set, this record authorizes unlimited future certificate issuances without per-renewal DNS updates. Based on [draft-ietf-acme-dns-persist](https://datatracker.ietf.org/doc/draft-ietf-acme-dns-persist/) and CA/Browser Forum ballot SC-088v3. If the CA doesn't offer dns-persist-01 yet, the connector falls back to dns-01 automatically.
|
||||
|
||||
HTTP-01 configuration:
|
||||
```json
|
||||
{
|
||||
@@ -130,14 +188,53 @@ DNS-01 configuration:
|
||||
}
|
||||
```
|
||||
|
||||
DNS hook scripts receive these environment variables: `CERTCTL_DNS_DOMAIN` (domain being validated), `CERTCTL_DNS_FQDN` (full record name, e.g., `_acme-challenge.example.com`), `CERTCTL_DNS_VALUE` (TXT record value), `CERTCTL_DNS_TOKEN` (ACME challenge token). The present script must create the TXT record and exit 0; the cleanup script removes it.
|
||||
DNS-PERSIST-01 configuration:
|
||||
```json
|
||||
{
|
||||
"directory_url": "https://acme-v02.api.letsencrypt.org/directory",
|
||||
"email": "admin@example.com",
|
||||
"challenge_type": "dns-persist-01",
|
||||
"dns_present_script": "/etc/certctl/dns/create-record.sh",
|
||||
"dns_persist_issuer_domain": "letsencrypt.org",
|
||||
"dns_propagation_wait": 30
|
||||
}
|
||||
```
|
||||
|
||||
The present script creates a TXT record at `_validation-persist.<domain>` with the value `letsencrypt.org; accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/<your-id>`. This record is permanent — no cleanup script is needed.
|
||||
|
||||
ZeroSSL configuration (requires External Account Binding):
|
||||
```json
|
||||
{
|
||||
"directory_url": "https://acme.zerossl.com/v2/DV90",
|
||||
"email": "admin@example.com",
|
||||
"eab_kid": "your-zerossl-eab-kid",
|
||||
"eab_hmac": "your-zerossl-eab-hmac-base64url"
|
||||
}
|
||||
```
|
||||
|
||||
ZeroSSL, Google Trust Services, and SSL.com require External Account Binding (EAB) for ACME account registration. For most CAs, get your EAB credentials from the CA's dashboard and provide them via `eab_kid` and `eab_hmac`. The HMAC key must be base64url-encoded (no padding). CAs that don't require EAB (Let's Encrypt, Buypass) ignore these fields.
|
||||
|
||||
**ZeroSSL auto-EAB:** When the directory URL points to ZeroSSL and no EAB credentials are provided, certctl automatically fetches them from ZeroSSL's public API (`api.zerossl.com/acme/eab-credentials-email`) using your configured email address. No dashboard visit required — just set the directory URL and email, and it works. This is the same approach used by Caddy and acme.sh.
|
||||
|
||||
Minimal ZeroSSL configuration (auto-EAB):
|
||||
```json
|
||||
{
|
||||
"directory_url": "https://acme.zerossl.com/v2/DV90",
|
||||
"email": "admin@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
DNS hook scripts receive these environment variables: `CERTCTL_DNS_DOMAIN` (domain being validated), `CERTCTL_DNS_FQDN` (full record name — `_acme-challenge.<domain>` for dns-01, `_validation-persist.<domain>` for dns-persist-01), `CERTCTL_DNS_VALUE` (TXT record value), `CERTCTL_DNS_TOKEN` (ACME challenge token). The present script must create the TXT record and exit 0; the cleanup script removes it (dns-01 only).
|
||||
|
||||
Environment variables for the default ACME connector:
|
||||
- `CERTCTL_ACME_DIRECTORY_URL` — ACME directory URL
|
||||
- `CERTCTL_ACME_EMAIL` — Contact email for account registration
|
||||
- `CERTCTL_ACME_CHALLENGE_TYPE` — `http-01` (default) or `dns-01`
|
||||
- `CERTCTL_ACME_DNS_PRESENT_SCRIPT` — Path to DNS record creation script (dns-01 only)
|
||||
- `CERTCTL_ACME_DNS_CLEANUP_SCRIPT` — Path to DNS record cleanup script (dns-01 only)
|
||||
- `CERTCTL_ACME_EAB_KID` — External Account Binding Key ID (required by ZeroSSL, Google Trust Services, SSL.com)
|
||||
- `CERTCTL_ACME_EAB_HMAC` — External Account Binding HMAC key (base64url-encoded)
|
||||
- `CERTCTL_ACME_CHALLENGE_TYPE` — `http-01` (default), `dns-01`, or `dns-persist-01`
|
||||
- `CERTCTL_ACME_DNS_PRESENT_SCRIPT` — Path to DNS record creation script (dns-01 and dns-persist-01)
|
||||
- `CERTCTL_ACME_DNS_CLEANUP_SCRIPT` — Path to DNS record cleanup script (dns-01 only, not used by dns-persist-01)
|
||||
- `CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN` — CA issuer domain for persistent record (dns-persist-01 only, e.g., `letsencrypt.org`)
|
||||
|
||||
The connector is registered in the issuer registry under `iss-acme-staging` and `iss-acme-prod`. Use `iss-acme-staging` for Let's Encrypt staging (rate-limit-friendly testing) and `iss-acme-prod` for production certificates.
|
||||
|
||||
@@ -198,12 +295,23 @@ Each issuer handles revocation differently:
|
||||
- **step-ca**: Calls step-ca's `/revoke` API endpoint. Clients should check step-ca's own CRL/OCSP for authoritative status.
|
||||
- **OpenSSL/Custom CA**: Invokes the configured revoke script (`CERTCTL_OPENSSL_REVOKE_SCRIPT`) with the serial number as an argument.
|
||||
|
||||
### EST Integration (GetCACertPEM)
|
||||
|
||||
The `GetCACertPEM()` method returns the PEM-encoded CA certificate chain, used by the EST server's `/.well-known/est/cacerts` endpoint (RFC 7030) to distribute the CA chain to enrolling devices. Each issuer handles this differently:
|
||||
|
||||
- **Local CA**: Returns the CA certificate PEM (self-signed or sub-CA cert). This is the primary EST issuer.
|
||||
- **ACME**: Returns error — ACME CAs provide chains per-issuance, not statically.
|
||||
- **step-ca**: Returns error — step-ca serves its own `/root` endpoint for CA distribution.
|
||||
- **OpenSSL/Custom CA**: Returns error — custom script-based CAs have no CA cert access through certctl.
|
||||
|
||||
Note: EST (Enrollment over Secure Transport) is not a connector — it's a protocol handler (`internal/api/handler/est.go`) that delegates certificate issuance to whichever issuer connector is configured via `CERTCTL_EST_ISSUER_ID`. See the [Architecture Guide](architecture.md#est-server-rfc-7030) for details.
|
||||
|
||||
### Planned Issuers
|
||||
|
||||
The following issuer connectors are planned for future milestones:
|
||||
|
||||
- **Vault PKI** — HashiCorp Vault's PKI secrets engine for organizations using Vault as their internal CA (planned for V4.0+).
|
||||
- **DigiCert** — Commercial CA integration via DigiCert's REST API (planned for V3 paid release).
|
||||
- **DigiCert** — Commercial CA integration via DigiCert's REST API (planned).
|
||||
|
||||
Note: ADCS (Active Directory Certificate Services) integration is handled via the **sub-CA mode** of the Local CA issuer, not as a separate connector. certctl operates as a subordinate CA with its signing certificate issued by ADCS, so all certctl-issued certs chain to the enterprise ADCS root. See the Local CA section above.
|
||||
|
||||
@@ -393,11 +501,11 @@ The combined PEM is built in this order: server certificate, intermediate/chain
|
||||
|
||||
Location: `internal/connector/target/haproxy/haproxy.go`
|
||||
|
||||
### V3 (Paid): F5 BIG-IP (Interface Only)
|
||||
### F5 BIG-IP (Interface Only)
|
||||
|
||||
The F5 BIG-IP target connector interface is built with the iControl REST flow mapped out, but the actual API calls are not yet implemented. F5 appliances can't run agents directly, so this connector uses the **proxy agent pattern**: a designated agent in the same network zone picks up F5 deployment jobs and calls the iControl REST API. The server assigns the work; the proxy agent executes it. Implementation is planned for the paid V3 release.
|
||||
The F5 BIG-IP target connector interface is defined with the iControl REST flow mapped out, but the actual API calls are not yet implemented. F5 appliances can't run agents directly, so this connector uses the **proxy agent pattern**: a designated agent in the same network zone picks up F5 deployment jobs and calls the iControl REST API. The server assigns the work; the proxy agent executes it.
|
||||
|
||||
The planned flow is: authenticate via `POST /mgmt/shared/authn/login`, upload cert PEM via `POST /mgmt/tm/ltm/certificate`, update the SSL profile via `PATCH /mgmt/tm/ltm/profile/client-ssl/{profile}`, and validate deployment by checking profile status. Implementation is planned for a future release.
|
||||
The planned flow is: authenticate via `POST /mgmt/shared/authn/login`, upload cert PEM via `POST /mgmt/tm/ltm/certificate`, update the SSL profile via `PATCH /mgmt/tm/ltm/profile/client-ssl/{profile}`, and validate deployment by checking profile status.
|
||||
|
||||
Configuration (defined, not yet functional):
|
||||
```json
|
||||
@@ -414,9 +522,9 @@ Note: F5 credentials are stored on the proxy agent, not on the control plane ser
|
||||
|
||||
Location: `internal/connector/target/f5/f5.go`
|
||||
|
||||
### V3 (Paid): IIS (Interface Only, Dual-Mode)
|
||||
### IIS (Interface Only, Dual-Mode)
|
||||
|
||||
The IIS target connector supports two deployment modes planned for the paid V3 release:
|
||||
The IIS target connector supports two planned deployment modes:
|
||||
|
||||
**Agent-local (recommended):** A Windows agent runs directly on the IIS server and deploys certificates using PowerShell — `Import-PfxCertificate` to install into the certificate store and `Set-WebBinding` to bind to the IIS site. This is the preferred approach: no remote access needed, no credential management, same pull-based model as NGINX/Apache/HAProxy.
|
||||
|
||||
@@ -474,6 +582,8 @@ Each notifier is enabled by its configuration env var:
|
||||
|
||||
| Notifier | Env Var | Description |
|
||||
|----------|---------|-------------|
|
||||
| Email | `CERTCTL_EMAIL_SMTP_HOST`, `CERTCTL_EMAIL_SMTP_PORT`, `CERTCTL_EMAIL_FROM` | SMTP email delivery. Optional: `CERTCTL_EMAIL_SMTP_USERNAME`, `CERTCTL_EMAIL_SMTP_PASSWORD` |
|
||||
| Webhook | `CERTCTL_WEBHOOK_URL` | HTTP POST to any endpoint. Optional: `CERTCTL_WEBHOOK_SECRET` for HMAC signing |
|
||||
| Slack | `CERTCTL_SLACK_WEBHOOK_URL` | Incoming webhook URL. Optional: `CERTCTL_SLACK_CHANNEL`, `CERTCTL_SLACK_USERNAME` |
|
||||
| Teams | `CERTCTL_TEAMS_WEBHOOK_URL` | Incoming webhook URL (MessageCard format) |
|
||||
| PagerDuty | `CERTCTL_PAGERDUTY_ROUTING_KEY` | Events API v2 routing key. Optional: `CERTCTL_PAGERDUTY_SEVERITY` (default: "warning") |
|
||||
@@ -606,7 +716,7 @@ The agent scans these directories on startup and every 6 hours, looking for cert
|
||||
1. **Scan**: Agent recursively walks directories, extracts certificates
|
||||
2. **Deduplicate**: Control plane deduplicates by SHA-256 fingerprint (same cert in multiple locations is one discovery)
|
||||
3. **Store**: Discovered certificates stored with metadata (agent ID, file path, found date, fingerprint)
|
||||
4. **Triage**: Operators query discovered certs via API, claim to link to managed certificates, or dismiss false positives
|
||||
4. **Triage**: Operators review discovered certs in the **Discovery** dashboard page (or via API) — claim to link to managed certificates, or dismiss false positives. The dashboard shows summary stats, filters by status and agent, and provides one-click claim/dismiss actions.
|
||||
|
||||
### API Endpoints
|
||||
|
||||
@@ -654,10 +764,10 @@ export CERTCTL_NETWORK_SCAN_INTERVAL=6h # default
|
||||
|
||||
### Creating Scan Targets
|
||||
|
||||
Network scan targets define which CIDR ranges and ports to probe:
|
||||
Network scan targets can be managed from the **Network Scans** dashboard page (create, edit, enable/disable, trigger on-demand scans) or via the API. Targets define which CIDR ranges and ports to probe:
|
||||
|
||||
```bash
|
||||
# Create a scan target for your internal network
|
||||
# Create a scan target for your internal network (or use the dashboard's "+ New Target" button)
|
||||
curl -s -X POST http://localhost:8443/api/v1/network-scan-targets \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
@@ -677,7 +787,7 @@ curl -s -X POST http://localhost:8443/api/v1/network-scan-targets \
|
||||
3. **Extract**: Certificate metadata extracted from TLS handshake (CN, SANs, serial, issuer, key info, fingerprint)
|
||||
4. **Pipeline**: Results fed into the same `DiscoveryService.ProcessDiscoveryReport()` as filesystem discovery
|
||||
5. **Deduplicate**: Sentinel agent ID (`server-scanner`) with source_path as `ip:port` ensures proper dedup
|
||||
6. **Triage**: Discovered certs appear in `GET /api/v1/discovered-certificates` with `agent_id=server-scanner`
|
||||
6. **Triage**: Discovered certs appear in the **Discovery** dashboard page (and via `GET /api/v1/discovered-certificates`) with `agent_id=server-scanner`
|
||||
|
||||
### API Endpoints
|
||||
|
||||
|
||||
@@ -5,6 +5,41 @@ This demo goes beyond browsing pre-loaded data. You'll create a team, register a
|
||||
**Time**: 15-20 minutes
|
||||
**Prerequisites**: certctl running via Docker Compose (see [Quick Start](quickstart.md))
|
||||
|
||||
## Contents
|
||||
|
||||
1. [Setup](#setup)
|
||||
2. [How the pieces fit together](#how-the-pieces-fit-together)
|
||||
3. [Alternative Issuers Reference](#alternative-issuers-reference)
|
||||
- [Sub-CA Mode](#sub-ca-mode-local-ca-chained-to-enterprise-root)
|
||||
- [ACME with ZeroSSL](#acme-with-zerossl-auto-eab)
|
||||
- [ACME with DNS-01 Challenges](#acme-with-dns-01-challenges-wildcard-certificates)
|
||||
- [ACME with DNS-PERSIST-01](#acme-with-dns-persist-01-zero-touch-renewals)
|
||||
- [step-ca (Smallstep Private CA)](#step-ca-smallstep-private-ca)
|
||||
- [OpenSSL / Custom CA](#openssl--custom-ca-script-based)
|
||||
4. [Part 1: Build the Organization Structure](#part-1-build-the-organization-structure)
|
||||
5. [Part 2: Verify the Issuer](#part-2-verify-the-issuer)
|
||||
6. [Part 3: Create a Managed Certificate](#part-3-create-a-managed-certificate)
|
||||
7. [Part 4: Trigger Certificate Renewal](#part-4-trigger-certificate-renewal)
|
||||
8. [Part 4.5: Manage Deployment Targets](#part-45-manage-deployment-targets)
|
||||
9. [Part 5: Deploy the Certificate](#part-5-deploy-the-certificate)
|
||||
10. [Part 6: View the Audit Trail](#part-6-view-the-audit-trail-immutable-api-audit-log)
|
||||
11. [Part 7: Check Notifications](#part-7-check-notifications)
|
||||
12. [Part 8: Create a Second Certificate and Compare](#part-8-create-a-second-certificate-and-compare)
|
||||
13. [Part 8.5: Revoke a Certificate](#part-85-revoke-a-certificate)
|
||||
14. [Part 9: Policy Violations](#part-9-policy-violations)
|
||||
15. [Part 9.5: Dashboard Stats and Metrics](#part-95-dashboard-stats-and-metrics)
|
||||
16. [Part 10: Certificate Profiles](#part-10-certificate-profiles)
|
||||
17. [Part 11: Agent Groups](#part-11-agent-groups)
|
||||
18. [Part 12: Interactive Approval Workflow](#part-12-interactive-approval-workflow)
|
||||
19. [Part 13: Advanced Query Features](#part-13-advanced-query-features)
|
||||
20. [Part 14: CLI Tool](#part-14-cli-tool-m16b)
|
||||
21. [Part 15: MCP Server for AI Integration](#part-15-mcp-server-for-ai-integration-m18a)
|
||||
22. [Part 16: Certificate Discovery](#part-16-certificate-discovery-m18b--m21)
|
||||
23. [End-to-End Architecture Summary](#end-to-end-architecture-summary)
|
||||
24. [Full Automated Script](#full-automated-script)
|
||||
25. [What to Show Stakeholders](#what-to-show-stakeholders)
|
||||
26. [Teardown](#teardown)
|
||||
|
||||
## Setup
|
||||
|
||||
Make sure certctl is running:
|
||||
@@ -62,6 +97,27 @@ docker compose -f deploy/docker-compose.yml restart server
|
||||
|
||||
The CA key can be RSA, ECDSA, or PKCS#8 format. The connector validates that the certificate has `IsCA=true` and `KeyUsageCertSign`.
|
||||
|
||||
### ACME with ZeroSSL (Auto-EAB)
|
||||
|
||||
ZeroSSL is a free ACME CA that requires External Account Binding (EAB) for account registration. certctl auto-fetches EAB credentials from ZeroSSL's public API when the directory URL is detected as ZeroSSL and no EAB credentials are provided — you just need an email address:
|
||||
|
||||
```bash
|
||||
# Minimal config — certctl auto-fetches EAB credentials from ZeroSSL
|
||||
export CERTCTL_ACME_DIRECTORY_URL="https://acme.zerossl.com/v2/DV90"
|
||||
export CERTCTL_ACME_EMAIL="ops@example.com"
|
||||
```
|
||||
|
||||
No dashboard visit, no manual EAB credential copy-paste. certctl calls `api.zerossl.com/acme/eab-credentials-email` with your email, gets back a KID + HMAC key, and uses them for ACME account registration automatically.
|
||||
|
||||
If you already have EAB credentials (e.g., from the ZeroSSL dashboard or for other CAs like Google Trust Services or SSL.com), you can provide them explicitly:
|
||||
|
||||
```bash
|
||||
export CERTCTL_ACME_DIRECTORY_URL="https://acme.zerossl.com/v2/DV90"
|
||||
export CERTCTL_ACME_EMAIL="ops@example.com"
|
||||
export CERTCTL_ACME_EAB_KID="your-key-id"
|
||||
export CERTCTL_ACME_EAB_HMAC="your-base64url-hmac-key"
|
||||
```
|
||||
|
||||
### ACME with DNS-01 Challenges (Wildcard Certificates)
|
||||
|
||||
For Let's Encrypt or other ACME providers with wildcard support:
|
||||
@@ -97,6 +153,21 @@ curl -s -X POST $API/api/v1/certificates \
|
||||
}' | jq .
|
||||
```
|
||||
|
||||
### ACME with DNS-PERSIST-01 (Zero-Touch Renewals)
|
||||
|
||||
DNS-PERSIST-01 uses a standing `_validation-persist` TXT record that you set once. The CA revalidates it on every renewal — no per-renewal DNS updates, no cleanup scripts, no propagation waits. If the CA doesn't support DNS-PERSIST-01 yet, certctl falls back to DNS-01 automatically.
|
||||
|
||||
```bash
|
||||
# Configure ACME DNS-PERSIST-01
|
||||
export CERTCTL_ACME_CHALLENGE_TYPE="dns-persist-01"
|
||||
export CERTCTL_ACME_DNS_PRESENT_SCRIPT="/usr/local/bin/dns-present.sh"
|
||||
export CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN="letsencrypt.org"
|
||||
|
||||
# The present script creates a _validation-persist.<domain> TXT record with value:
|
||||
# "letsencrypt.org; accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/12345"
|
||||
# This record is set once and never touched again.
|
||||
```
|
||||
|
||||
### step-ca (Smallstep Private CA)
|
||||
|
||||
For organizations running step-ca as their private CA:
|
||||
@@ -221,7 +292,7 @@ You should see:
|
||||
|
||||
The result is a structurally valid X.509 certificate — browsers won't trust it (no root CA in their trust store), but it exercises the exact same code paths that a production ACME or Vault issuer would.
|
||||
|
||||
**Why pluggable issuers:** Different organizations use different CAs. Some use Let's Encrypt (ACME protocol), some use step-ca or internal PKI (Vault), some use commercial CAs (DigiCert, Entrust, GlobalSign), and some have custom OpenSSL-based workflows. For enterprises with ADCS, certctl can operate as a sub-CA — all issued certs chain to the enterprise root. The connector interface means certctl doesn't care — it calls `IssueCertificate()` and gets back a signed cert regardless of the backend. V1 ships with Local CA (self-signed or sub-CA), ACME (HTTP-01 + DNS-01 for wildcards), and step-ca (Smallstep private CA via native /sign API). OpenSSL/Custom CA is planned for V2; DigiCert, Vault PKI, Entrust, GlobalSign, Google CAS, and EJBCA are planned for V3.
|
||||
**Why pluggable issuers:** Different organizations use different CAs. Some use Let's Encrypt (ACME protocol), some use step-ca or internal PKI (Vault), some use commercial CAs (DigiCert, Entrust, GlobalSign), and some have custom OpenSSL-based workflows. For enterprises with ADCS, certctl can operate as a sub-CA — all issued certs chain to the enterprise root. The connector interface means certctl doesn't care — it calls `IssueCertificate()` and gets back a signed cert regardless of the backend. V1 ships with Local CA (self-signed or sub-CA), ACME (HTTP-01 + DNS-01 + DNS-PERSIST-01 for wildcards), and step-ca (Smallstep private CA via native /sign API). V2 adds the OpenSSL/Custom CA connector (script-based signing). DigiCert, Vault PKI, Entrust, GlobalSign, Google CAS, and EJBCA are planned for V3+.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
@@ -472,14 +543,14 @@ In production, agents poll for work and report results. You can simulate this ma
|
||||
|
||||
```bash
|
||||
# Poll for pending deployment work (as an agent)
|
||||
curl -s "$API/api/v1/agents/agent-nginx-prod/work" | jq .
|
||||
curl -s "$API/api/v1/agents/ag-web-prod/work" | jq .
|
||||
```
|
||||
|
||||
This returns pending deployment jobs assigned to the agent. The agent would then fetch the certificate, deploy it, and report back:
|
||||
|
||||
```bash
|
||||
# Report job completion (replace JOB_ID with an actual job ID from the work response)
|
||||
curl -s -X POST "$API/api/v1/agents/agent-nginx-prod/jobs/JOB_ID/status" \
|
||||
curl -s -X POST "$API/api/v1/agents/ag-web-prod/jobs/JOB_ID/status" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"status": "Completed",
|
||||
@@ -805,14 +876,14 @@ curl -s -X POST $API/api/v1/agent-groups \
|
||||
|
||||
## Part 12: Interactive Approval Workflow
|
||||
|
||||
For high-value certificates, you may want human oversight before renewal proceeds. Create a policy that requires approval:
|
||||
For high-value certificates, you may want human oversight before renewal proceeds. The demo includes 2 pre-seeded `AwaitingApproval` renewal jobs (for `auth-production` and `payments-production`). Open **Jobs** in the sidebar — you'll see the amber "Pending Approval" banner and Approve/Reject buttons immediately.
|
||||
|
||||
```bash
|
||||
# Check jobs that need approval
|
||||
# Check jobs that need approval (demo includes 2)
|
||||
curl -s "$API/api/v1/jobs?status=AwaitingApproval" | jq '.data[] | {id, type, certificate_id, status}'
|
||||
```
|
||||
|
||||
If there are jobs awaiting approval, approve or reject them:
|
||||
Approve or reject them:
|
||||
|
||||
```bash
|
||||
# Approve a job
|
||||
@@ -830,6 +901,8 @@ curl -s -X POST $API/api/v1/jobs/JOB_ID/reject \
|
||||
|
||||
**Why interactive approval:** Not every certificate renewal should be automatic. PCI-scoped certificates, certs with specific compliance requirements, or certificates being migrated between issuers benefit from a human checkpoint. The AwaitingApproval state creates that checkpoint without blocking the entire job pipeline.
|
||||
|
||||
**In the dashboard:** Click "Jobs" in the sidebar, filter by status "AwaitingApproval", and you'll see a list of renewal jobs waiting for approval. Each job shows the certificate, issuer, and requested validity period. Click a job to open its detail view and see the Approve / Reject buttons with a reason text field. After approval or rejection, the job status updates in real-time and the audit trail records the decision.
|
||||
|
||||
---
|
||||
|
||||
## Part 13: Advanced Query Features
|
||||
@@ -875,28 +948,28 @@ export CERTCTL_SERVER_URL="http://localhost:8443"
|
||||
export CERTCTL_API_KEY="test-key-123"
|
||||
|
||||
# List certificates (JSON or table format)
|
||||
./certctl-cli list-certs --format table
|
||||
./certctl-cli certs list
|
||||
|
||||
# Get certificate details
|
||||
./certctl-cli get-cert mc-demo-api
|
||||
./certctl-cli certs get mc-demo-api
|
||||
|
||||
# Trigger renewal
|
||||
./certctl-cli renew-cert mc-demo-api
|
||||
./certctl-cli certs renew mc-demo-api
|
||||
|
||||
# Revoke a certificate with RFC 5280 reason
|
||||
./certctl-cli revoke-cert mc-demo-payments --reason keyCompromise
|
||||
./certctl-cli certs revoke mc-demo-payments --reason keyCompromise
|
||||
|
||||
# List agents
|
||||
./certctl-cli list-agents
|
||||
./certctl-cli agents list
|
||||
|
||||
# List pending jobs
|
||||
./certctl-cli list-jobs
|
||||
./certctl-cli jobs list
|
||||
|
||||
# Check system health
|
||||
./certctl-cli health
|
||||
# Check system health and stats
|
||||
./certctl-cli status
|
||||
|
||||
# Export metrics
|
||||
./certctl-cli metrics --format json
|
||||
# JSON output format
|
||||
./certctl-cli --format json status
|
||||
|
||||
# Bulk import certificates from a PEM file
|
||||
./certctl-cli import /path/to/certificates.pem
|
||||
@@ -908,7 +981,7 @@ export CERTCTL_API_KEY="test-key-123"
|
||||
|
||||
## Part 15: MCP Server for AI Integration (M18a)
|
||||
|
||||
certctl exposes all 78 API endpoints as tools via the Model Context Protocol (MCP), enabling seamless integration with Claude, Cursor, and other AI assistants:
|
||||
certctl exposes 78 MCP tools covering the REST API via the Model Context Protocol (MCP), enabling seamless integration with Claude, Cursor, and other AI assistants:
|
||||
|
||||
```bash
|
||||
# Build the MCP server
|
||||
@@ -922,7 +995,7 @@ export CERTCTL_API_KEY="test-key-123"
|
||||
./mcp-server
|
||||
```
|
||||
|
||||
**How it works:** The MCP server uses the official Model Context Protocol Go SDK to expose stateless HTTP proxies to all 78 API endpoints. Each MCP tool corresponds to one or more REST endpoints and includes:
|
||||
**How it works:** The MCP server uses the official Model Context Protocol Go SDK to expose 78 stateless HTTP proxy tools covering the REST API. Each MCP tool corresponds to one or more REST endpoints and includes:
|
||||
|
||||
- **Input schema** — typed arguments with JSON schema hints for LLM-friendly introspection
|
||||
- **Binary support** — handles DER-encoded CRL and OCSP responses without mangling
|
||||
@@ -956,6 +1029,8 @@ The MCP server is perfect for:
|
||||
|
||||
certctl discovers existing certificates two ways: **filesystem scanning** (agents scan local directories) and **network scanning** (the server probes TLS endpoints). Both feed into the same triage pipeline.
|
||||
|
||||
**The demo comes pre-loaded with discovery data:** 9 discovered certificates (3 Unmanaged from filesystem scans, 3 Unmanaged from network scans, 2 Managed, 1 Dismissed), 3 discovery scans, and 3 network scan targets with recent scan results. Open **Discovery** in the sidebar to see the triage workflow immediately. The steps below show how to configure discovery from scratch.
|
||||
|
||||
### Filesystem Discovery (Agent-Side)
|
||||
|
||||
Configure the demo agent to scan for certificates. In the Docker Compose setup, agents have a `/tmp/certs` directory (created by the seed script). Restart the agent with discovery enabled:
|
||||
@@ -976,7 +1051,7 @@ certctl-agent --agent-id a-demo-1 --key-dir /tmp/keys --discovery-dirs /tmp/cert
|
||||
|
||||
### Network Discovery (Server-Side)
|
||||
|
||||
The server can also discover certificates by actively probing TLS endpoints — no agent required. Create a scan target and trigger a scan:
|
||||
The server can also discover certificates by actively probing TLS endpoints — no agent required. Network scanning is enabled by default in the Docker Compose demo (`CERTCTL_NETWORK_SCAN_ENABLED=true`), with 3 pre-configured scan targets. You can create additional targets:
|
||||
|
||||
```bash
|
||||
# Create a network scan target
|
||||
@@ -1030,6 +1105,28 @@ curl -s -X POST "$API/api/v1/discovered-certificates/$DISCOVERED_ID/dismiss" \
|
||||
|
||||
**How it works:** Filesystem discovery: the agent scans `CERTCTL_DISCOVERY_DIRS` on startup and every 6 hours, extracts metadata (common name, SANs, issuer, expiration, key type, fingerprint) from all PEM and DER files, and POSTs findings to `POST /api/v1/agents/{id}/discoveries`. Network discovery: the server expands CIDR ranges (capped at /20 = 4096 IPs), connects to each IP:port via TLS, extracts the peer certificate chain, and stores results using `server-scanner` as a sentinel agent ID. Both sources deduplicate by fingerprint and store results with a status: **Unmanaged** (discovered, not yet managed), **Managed** (linked to a control plane cert), or **Dismissed** (operator decided not to manage). This gives you a triage workflow: discover → review → claim or dismiss.
|
||||
|
||||
### Discovery & Network Scans in the Dashboard
|
||||
|
||||
**Discovered Certificates Page:** Click "Discovery" in the sidebar to see a triage workflow. The page lists all discovered certificates grouped by status (Unmanaged, Managed, Dismissed). For each Unmanaged certificate, you see:
|
||||
- Common name and SANs
|
||||
- Issuer and subject DN
|
||||
- Expiration date
|
||||
- Fingerprint (helps dedup)
|
||||
- Source (agent ID or `server-scanner` for network scans)
|
||||
- Action buttons: Claim (manage this cert), Dismiss (ignore it)
|
||||
|
||||
Click "Claim" to bring an unmanaged certificate under certctl's control. Click "Dismiss" to remove it from the triage queue.
|
||||
|
||||
**Network Scans Page:** Click "Network Scans" in the sidebar to manage network scan targets. The page shows all configured scan targets with:
|
||||
- Target name and description
|
||||
- CIDR ranges and ports scanned
|
||||
- Enabled/disabled toggle
|
||||
- Scan interval and connection timeout
|
||||
- Last scan timestamp and result summary
|
||||
- Action buttons: Edit, Delete, Scan Now (immediate)
|
||||
|
||||
Click "Scan Now" to trigger an immediate TLS probe of the target's IP ranges. Results appear within seconds in the Discovered Certificates page as entries with `agent_id=server-scanner`.
|
||||
|
||||
**In the dashboard**, click "Discovered Certificates" in the sidebar to see what agents and network scans found — claim unmanaged certs to bring them under certctl's management, or dismiss them.
|
||||
|
||||
---
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
# certctl Demo Guide
|
||||
|
||||
A 5-10 minute guided walkthrough of certctl's dashboard and API. Perfect for stakeholder presentations and team demos.
|
||||
|
||||
New to certificates? Read the [Concepts Guide](concepts.md) first. Want a hands-on demo where you issue certificates yourself? See the [Advanced Demo](demo-advanced.md).
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
git clone https://github.com/shankar0123/certctl.git
|
||||
cd certctl
|
||||
docker compose -f deploy/docker-compose.yml up -d --build
|
||||
```
|
||||
|
||||
Wait ~30 seconds for PostgreSQL to initialize and the server to start, then open:
|
||||
|
||||
**http://localhost:8443**
|
||||
|
||||
You'll see the dashboard pre-loaded with 15 demo certificates across multiple teams, environments, and statuses — including expiring, expired, active, failed, wildcard, and in-progress renewals.
|
||||
|
||||
## What You'll See
|
||||
|
||||
### Dashboard Overview
|
||||
The main dashboard shows at a glance:
|
||||
- **Total certificates** managed across your infrastructure
|
||||
- **Expiring soon** — certificates within 30 days of expiration (yellow/red)
|
||||
- **Expired** — certificates past their expiration date
|
||||
- **Active** — healthy certificates with time remaining
|
||||
- **Renewal success rate** — percentage of automated renewals that succeeded
|
||||
|
||||
Below the stats, interactive charts provide deeper visibility: an **expiration heatmap** (90-day weekly buckets), **renewal success rate trends** (30-day line chart), **certificate status distribution** (donut chart), and **issuance rate** (30-day bar chart).
|
||||
|
||||
### Certificates View
|
||||
Click "Certificates" in the sidebar to see the full inventory:
|
||||
- Search by name or domain
|
||||
- Filter by status (Active, Expiring, Expired, Failed) or environment (Production, Staging)
|
||||
- Sort by any column
|
||||
- Click any row to see full details: metadata, version history, deployment targets, and audit trail
|
||||
|
||||
### Demo Scenarios to Walk Through
|
||||
|
||||
**1. "We're about to have an outage"**
|
||||
Filter by status → Expiring. You'll see `auth-production` (12 days), `cdn-production` (8 days), and `mail-production` (5 days). These are real alerts the platform would catch automatically.
|
||||
|
||||
**2. "A renewal failed"**
|
||||
Look at `vpn-production` — status: Failed. Click it to see the audit trail showing the ACME challenge failure after 3 retry attempts. The system sent a webhook notification to the ops channel.
|
||||
|
||||
**3. "Who owns this cert?"**
|
||||
Click any certificate to see the owner, team, environment, and tags. Every cert has clear accountability.
|
||||
|
||||
**4. "What happened to the legacy app?"**
|
||||
Filter by status → Expired. `legacy-app` expired 3 days ago, `old-api-v1` expired 15 days ago. Both have policy violations flagged.
|
||||
|
||||
**5. "Show me the agent fleet"**
|
||||
Click "Agents" in the sidebar. Four agents are online, one (`iis-prod-agent`) went offline 3 hours ago — you'd want to investigate that.
|
||||
|
||||
**6. "What policies are enforced?"**
|
||||
Click "Policies" to see the active rules: required owner metadata, allowed environments, max certificate lifetime, minimum renewal window. Check the violations list to see which certs are non-compliant.
|
||||
|
||||
**7. "Can I revoke a compromised cert?"**
|
||||
Click any active certificate, then click the "Revoke" button. A modal appears with RFC 5280 reason codes (Key Compromise, Superseded, Cessation of Operation, etc.). After revocation, the cert shows a revocation banner with the reason and timestamp.
|
||||
|
||||
**8. "Show me short-lived credentials"**
|
||||
Click "Short-Lived" in the sidebar. This view shows certificates with TTL under 1 hour — live countdown timers, auto-refresh every 10 seconds, and profile-based filtering. These are for service-to-service auth where rapid expiry replaces revocation.
|
||||
|
||||
**9. "What about bulk operations?"**
|
||||
On the Certificates page, select multiple certificates using the checkboxes. A bulk action bar appears with options to trigger renewal, revoke (with reason codes), or reassign ownership — all with progress tracking.
|
||||
|
||||
**10. "How do I see the deployment history?"**
|
||||
Click any certificate, then scroll to the deployment timeline. A visual 4-step timeline shows the lifecycle: Requested → Issued → Deploying → Active. Previous versions show a rollback button.
|
||||
|
||||
**11. "What about certificates already running in production?"**
|
||||
Enable discovery on agents by setting `CERTCTL_DISCOVERY_DIRS` to directories containing certificates (e.g., `/etc/nginx/certs`). Agents scan on startup and every 6 hours, report findings to the control plane. For network-based discovery without agents, enable `CERTCTL_NETWORK_SCAN_ENABLED=true` and configure scan targets via the API — the server probes TLS endpoints on configured CIDR ranges and ports. Click "Discovered Certificates" to see what agents and network scans found — claim unmanaged certs to bring them under certctl's management, or dismiss them.
|
||||
|
||||
## REST API Walkthrough
|
||||
|
||||
The dashboard is backed by a real REST API (91 endpoints). Try these while the demo is running:
|
||||
|
||||
```bash
|
||||
# List all certificates
|
||||
curl -s http://localhost:8443/api/v1/certificates | jq .
|
||||
|
||||
# Get expiring certs
|
||||
curl -s "http://localhost:8443/api/v1/certificates?status=expiring" | jq .
|
||||
|
||||
# Advanced query: sort by expiration, sparse fields, cursor pagination
|
||||
curl -s "http://localhost:8443/api/v1/certificates?sort=-expires_at&fields=id,common_name,expires_at" | jq .
|
||||
|
||||
# Time-range filter: certs expiring before June 2026
|
||||
curl -s "http://localhost:8443/api/v1/certificates?expires_before=2026-06-01T00:00:00Z" | jq .
|
||||
|
||||
# Get a specific certificate
|
||||
curl -s http://localhost:8443/api/v1/certificates/mc-api-prod | jq .
|
||||
|
||||
# Get deployment targets for a certificate
|
||||
curl -s http://localhost:8443/api/v1/certificates/mc-api-prod/deployments | jq .
|
||||
|
||||
# List agents
|
||||
curl -s http://localhost:8443/api/v1/agents | jq .
|
||||
|
||||
# View audit trail (immutable API audit log of all actions)
|
||||
curl -s http://localhost:8443/api/v1/audit | jq .
|
||||
|
||||
# View policy violations (replace POLICY_ID with a real policy ID, e.g. pr-require-owner)
|
||||
curl -s http://localhost:8443/api/v1/policies/pr-require-owner/violations | jq .
|
||||
|
||||
# Check system health
|
||||
curl -s http://localhost:8443/health | jq .
|
||||
|
||||
# Dashboard stats and metrics
|
||||
curl -s http://localhost:8443/api/v1/stats/summary | jq .
|
||||
curl -s http://localhost:8443/api/v1/stats/certificates-by-status | jq .
|
||||
curl -s http://localhost:8443/api/v1/stats/expiration-timeline | jq .
|
||||
curl -s http://localhost:8443/api/v1/stats/job-trends | jq .
|
||||
curl -s http://localhost:8443/api/v1/stats/issuance-rate | jq .
|
||||
curl -s http://localhost:8443/api/v1/metrics | jq .
|
||||
curl -s http://localhost:8443/api/v1/metrics/prometheus # Prometheus format
|
||||
|
||||
# Certificate profiles
|
||||
curl -s http://localhost:8443/api/v1/profiles | jq .
|
||||
|
||||
# Agent groups
|
||||
curl -s http://localhost:8443/api/v1/agent-groups | jq .
|
||||
|
||||
# Revoke a certificate
|
||||
curl -s -X POST http://localhost:8443/api/v1/certificates/mc-api-prod/revoke \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"reason": "superseded"}' | jq .
|
||||
|
||||
# CRL and OCSP endpoints
|
||||
curl -s http://localhost:8443/api/v1/crl | jq .
|
||||
curl -s http://localhost:8443/api/v1/crl/iss-local -o /tmp/crl.der
|
||||
|
||||
# List discovered certificates
|
||||
curl -s http://localhost:8443/api/v1/discovered-certificates | jq .
|
||||
|
||||
# Discovery summary (counts by status)
|
||||
curl -s http://localhost:8443/api/v1/discovery-summary | jq .
|
||||
|
||||
# Network scan targets (active TLS scanning)
|
||||
curl -s http://localhost:8443/api/v1/network-scan-targets | jq .
|
||||
```
|
||||
|
||||
## CLI Tool
|
||||
|
||||
certctl ships with a command-line tool (`certctl-cli`) for terminal users:
|
||||
|
||||
```bash
|
||||
# Build the CLI
|
||||
cd cmd/cli && go build -o certctl-cli .
|
||||
|
||||
# Set credentials
|
||||
export CERTCTL_SERVER_URL="http://localhost:8443"
|
||||
export CERTCTL_API_KEY="test-key-123"
|
||||
|
||||
# List certificates (JSON or table format)
|
||||
./certctl-cli list-certs --format json
|
||||
./certctl-cli list-certs --format table
|
||||
|
||||
# Get certificate details
|
||||
./certctl-cli get-cert mc-api-prod
|
||||
|
||||
# Trigger renewal
|
||||
./certctl-cli renew-cert mc-api-prod
|
||||
|
||||
# Revoke a certificate (with RFC 5280 reason)
|
||||
./certctl-cli revoke-cert mc-api-prod --reason keyCompromise
|
||||
|
||||
# List agents
|
||||
./certctl-cli list-agents
|
||||
|
||||
# List pending jobs
|
||||
./certctl-cli list-jobs
|
||||
|
||||
# Bulk import certificates from PEM files
|
||||
./certctl-cli import /path/to/certs.pem
|
||||
|
||||
# Check health and metrics
|
||||
./certctl-cli health
|
||||
./certctl-cli metrics
|
||||
```
|
||||
|
||||
## MCP Server for AI Integration
|
||||
|
||||
certctl exposes its 78 API endpoints as tools via the Model Context Protocol (MCP), enabling integration with Claude, Cursor, and other AI assistants:
|
||||
|
||||
```bash
|
||||
# Build and run the MCP server
|
||||
cd cmd/mcp-server && go build -o mcp-server .
|
||||
|
||||
export CERTCTL_SERVER_URL="http://localhost:8443"
|
||||
export CERTCTL_API_KEY="test-key-123"
|
||||
|
||||
./mcp-server
|
||||
```
|
||||
|
||||
The MCP server:
|
||||
- Exposes all 78 API endpoints as MCP tools with typed schemas
|
||||
- Handles binary responses (DER CRL, OCSP responses)
|
||||
- Uses stdio transport for Claude/Cursor/OpenClaw integration
|
||||
- Zero external dependencies — pure Go with official MCP SDK
|
||||
|
||||
You can then ask Claude questions like:
|
||||
- "What certificates are expiring in the next 30 days?"
|
||||
- "Revoke the payments certificate due to key compromise"
|
||||
- "Show me the audit trail for the last 10 actions"
|
||||
- "List all certificates with PCI compliance tags"
|
||||
|
||||
## Dashboard Demo Mode
|
||||
|
||||
The dashboard includes a **Demo Mode** that works without any backend. Build and serve the frontend with Vite:
|
||||
|
||||
```bash
|
||||
cd web
|
||||
npm install
|
||||
npm run dev
|
||||
# Dashboard available at http://localhost:5173
|
||||
```
|
||||
|
||||
When the API is unreachable, the dashboard automatically loads realistic mock data and shows a subtle "Demo Mode" badge. This is perfect for screenshots, presentations, or quick demos without any infrastructure.
|
||||
|
||||
## Teardown
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/docker-compose.yml down -v
|
||||
```
|
||||
|
||||
The `-v` flag removes the PostgreSQL data volume so you get a clean slate next time.
|
||||
|
||||
## Presenting to Stakeholders
|
||||
|
||||
If you're demoing to a team or customer, here's a suggested flow:
|
||||
|
||||
1. **Start with the dashboard** — "This is your certificate inventory at a glance, with real-time charts showing expiration trends and renewal health"
|
||||
2. **Show the expiring certs** — "These three would have caused outages without this platform"
|
||||
3. **Click into auth-production** — "Here's the full lifecycle: who owns it, where it's deployed, deployment timeline, when it was last renewed"
|
||||
4. **Show revocation** — "If a key is compromised, one click revokes the cert with an RFC 5280 reason code. CRL and OCSP are served automatically"
|
||||
5. **Show the failed VPN cert** — "The system tried 3 times, then alerted the team via Slack, Teams, PagerDuty, or OpsGenie"
|
||||
6. **Show agents and fleet overview** — "Agents run on your infrastructure, handle key generation locally (ECDSA P-256). Fleet view shows OS, architecture, and version distribution"
|
||||
7. **Show profiles** — "Certificate profiles enforce crypto constraints — key types, max TTL, compliance requirements"
|
||||
8. **Show policies** — "Guardrails prevent teams from going outside approved scope"
|
||||
9. **Show bulk operations** — "Select multiple certs, trigger renewal or revoke in bulk with progress tracking"
|
||||
10. **Show certificate discovery** — "We discover certificates two ways: agents scan local filesystems, and the server actively probes TLS endpoints on your network. We deduplicate by fingerprint, show you what we found, and let you claim them or dismiss them"
|
||||
11. **Show the immutable audit trail** — "Every action in the system is recorded: who did it, what they did, when, what changed. Export to CSV/JSON for compliance"
|
||||
12. **Show advanced query features** — "Sort by any field, filter by date range, paginate efficiently with cursor-based pagination, select just the fields you need"
|
||||
13. **Show the CLI and MCP server** — "Terminal users get `certctl-cli` with 10 subcommands. AI assistants get MCP integration with 78 tools. Everything is API-first"
|
||||
|
||||
The whole walkthrough takes 5-10 minutes.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- **[Advanced Demo](demo-advanced.md)** — Go hands-on: create a team, issue a certificate via API, trigger renewal, and watch it appear in the dashboard
|
||||
- **[Concepts Guide](concepts.md)** — Understand TLS certificates, CAs, and private keys from scratch
|
||||
- **[Architecture](architecture.md)** — Deep dive into the control plane, agent model, and connector architecture
|
||||
@@ -7,7 +7,7 @@ Complete reference of all features shipped in the V2 release (as of March 2026).
|
||||
## API Surface
|
||||
|
||||
### Overview
|
||||
- **91 endpoints** across 19 resource domains under `/api/v1/`
|
||||
- **95 endpoints** across 20 resource domains under `/api/v1/` + `/.well-known/est/`
|
||||
- REST API with HTTP semantics (GET, POST, PUT, DELETE)
|
||||
- All endpoints require authentication by default (configurable)
|
||||
- OpenAPI 3.1 spec with full schema documentation
|
||||
@@ -94,6 +94,7 @@ curl -H "$AUTH" "$SERVER/api/v1/certificates?expires_before=2026-04-24T00:00:00Z
|
||||
| **Notifications** | 3 | List, get, mark as read |
|
||||
| **Stats** | 5 | Dashboard summary, certificates by status, expiration timeline, job trends, issuance rate |
|
||||
| **Metrics** | 2 | JSON metrics (gauges, counters, uptime), Prometheus exposition format |
|
||||
| **EST (RFC 7030)** | 4 | CA certs (PKCS#7), simple enrollment, re-enrollment, CSR attributes |
|
||||
| **Health** | 4 | Health check, readiness check, auth info, auth check |
|
||||
|
||||
---
|
||||
@@ -287,16 +288,17 @@ curl -H "$AUTH" "$SERVER/api/v1/policies/rp-standard/violations"
|
||||
- **Use Case** — Internal PKI, enterprise trust chains
|
||||
|
||||
### ACME v2
|
||||
- **Challenge Types** — HTTP-01 (default) and DNS-01 (wildcard support)
|
||||
- **Challenge Types** — HTTP-01 (default), DNS-01 (wildcard support), and DNS-PERSIST-01 (standing record, no per-renewal DNS updates)
|
||||
- **DNS-01 Script Hooks** — Pluggable DNS solver for any provider (Cloudflare, Route53, Azure DNS, etc.)
|
||||
- **Configuration** — `CERTCTL_ACME_DIRECTORY_URL`, `CERTCTL_ACME_EMAIL`, `CERTCTL_ACME_CHALLENGE_TYPE=dns-01`, `CERTCTL_ACME_DNS_PRESENT_SCRIPT`, `CERTCTL_ACME_DNS_CLEANUP_SCRIPT`
|
||||
- **DNS-PERSIST-01** — Standing `_validation-persist` TXT record set once, reused forever. Auto-fallback to DNS-01 if CA doesn't support it yet.
|
||||
- **Configuration** — `CERTCTL_ACME_DIRECTORY_URL`, `CERTCTL_ACME_EMAIL`, `CERTCTL_ACME_CHALLENGE_TYPE`, `CERTCTL_ACME_DNS_PRESENT_SCRIPT`, `CERTCTL_ACME_DNS_CLEANUP_SCRIPT`, `CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN`
|
||||
- **DNS Propagation Wait** — Configurable timeout before validation
|
||||
- **Use Case** — Public CAs (LetsEncrypt), wildcard certs
|
||||
|
||||
### step-ca
|
||||
- **Protocol** — Native `/sign` and `/revoke` API (not ACME)
|
||||
- **Authentication** — JWK provisioner with key file + password
|
||||
- **Configuration** — `CERTCTL_STEPCA_URL`, `CERTCTL_STEPCA_PROVISIONER_NAME`, `CERTCTL_STEPCA_PROVISIONER_KEY_PATH`, `CERTCTL_STEPCA_PROVISIONER_PASSWORD`
|
||||
- **Configuration** — `CERTCTL_STEPCA_URL`, `CERTCTL_STEPCA_PROVISIONER`, `CERTCTL_STEPCA_KEY_PATH`, `CERTCTL_STEPCA_PASSWORD`
|
||||
- **Operations** — Issue, renew, revoke
|
||||
- **Use Case** — Smallstep private CA, internal PKI with strong auth
|
||||
|
||||
@@ -818,7 +820,7 @@ All loops have configurable intervals via environment variables (`CERTCTL_SCHEDU
|
||||
|
||||
---
|
||||
|
||||
## Web Dashboard (19 Pages)
|
||||
## Web Dashboard
|
||||
|
||||
### Overview
|
||||
The web dashboard is the primary operational interface for certctl. Built with **Vite + React 18 + TypeScript + TanStack Query v5 + Tailwind CSS 3 + Recharts**.
|
||||
@@ -903,16 +905,18 @@ The web dashboard is the primary operational interface for certctl. Built with *
|
||||
|
||||
| Subcommand | Usage | Output Format |
|
||||
|------------|-------|----------------|
|
||||
| **list-certs** | `certctl-cli list-certs [--filter]` | Table or JSON (--format=json) |
|
||||
| **get-cert** | `certctl-cli get-cert <id>` | JSON cert details |
|
||||
| **renew-cert** | `certctl-cli renew-cert <id>` | Job ID confirmation |
|
||||
| **revoke-cert** | `certctl-cli revoke-cert <id> [--reason]` | Revocation confirmation |
|
||||
| **list-agents** | `certctl-cli list-agents` | Table or JSON |
|
||||
| **list-jobs** | `certctl-cli list-jobs [--filter]` | Table or JSON |
|
||||
| **health** | `certctl-cli health` | Server status |
|
||||
| **metrics** | `certctl-cli metrics` | JSON metrics |
|
||||
| **certs list** | `certctl-cli certs list` | Table or JSON (--format=json) |
|
||||
| **certs get** | `certctl-cli certs get <id>` | JSON cert details |
|
||||
| **certs renew** | `certctl-cli certs renew <id>` | Job ID confirmation |
|
||||
| **certs revoke** | `certctl-cli certs revoke <id> [--reason]` | Revocation confirmation |
|
||||
| **agents list** | `certctl-cli agents list` | Table or JSON |
|
||||
| **agents get** | `certctl-cli agents get <id>` | Agent details |
|
||||
| **jobs list** | `certctl-cli jobs list` | Table or JSON |
|
||||
| **jobs get** | `certctl-cli jobs get <id>` | Job details |
|
||||
| **jobs cancel** | `certctl-cli jobs cancel <id>` | Cancellation confirmation |
|
||||
| **status** | `certctl-cli status` | Health + summary stats |
|
||||
| **import** | `certctl-cli import <pem-file>` | Bulk import cert count |
|
||||
| **help** | `certctl-cli help [command]` | Command documentation |
|
||||
| **version** | `certctl-cli version` | Version string |
|
||||
|
||||
**Implementation Details:**
|
||||
- Stdlib-only (flag + text/tabwriter); no Cobra dependency
|
||||
@@ -922,9 +926,39 @@ The web dashboard is the primary operational interface for certctl. Built with *
|
||||
- CLI flags: `--server`, `--api-key`, `--format` (json/table)
|
||||
- Tested with httptest mock server; all commands covered
|
||||
|
||||
### EST Server (RFC 7030, M23)
|
||||
**Enrollment over Secure Transport** — industry-standard protocol for device certificate enrollment. Enables WiFi/802.1X, MDM, IoT, and BYOD use cases where devices need certificates without direct API access.
|
||||
|
||||
**Endpoints** (under `/.well-known/est/` per RFC 7030):
|
||||
|
||||
| Endpoint | Method | Description | Wire Format |
|
||||
|----------|--------|-------------|-------------|
|
||||
| `/cacerts` | GET | CA certificate chain distribution | Base64 PKCS#7 certs-only (application/pkcs7-mime) |
|
||||
| `/simpleenroll` | POST | Initial certificate enrollment | Request: PEM or base64-DER PKCS#10; Response: PKCS#7 |
|
||||
| `/simplereenroll` | POST | Certificate re-enrollment (renewal) | Same as simpleenroll |
|
||||
| `/csrattrs` | GET | CSR attributes the server requires | ASN.1 DER (application/csrattrs) |
|
||||
|
||||
**Architecture:**
|
||||
- **ESTService** bridges handler to existing `IssuerConnector` — no new issuance logic, reuses existing CA connectors
|
||||
- **CSR input handling** — accepts both base64-encoded DER (EST wire standard) and PEM-encoded PKCS#10 (convenience)
|
||||
- **PKCS#7 output** — hand-rolled ASN.1 degenerate SignedData builder (no external PKCS#7 dependency)
|
||||
- **CSR validation** — signature verification, Common Name extraction, SAN extraction (DNS, IP, email, URI)
|
||||
- **Configurable issuer binding** — `CERTCTL_EST_ISSUER_ID` selects which issuer connector processes enrollment
|
||||
- **Optional profile binding** — `CERTCTL_EST_PROFILE_ID` constrains enrollments to a specific certificate profile
|
||||
- **Audit trail** — all EST enrollments recorded with protocol=EST, CN, SANs, issuer ID, serial, profile ID
|
||||
|
||||
**Configuration:**
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_EST_ENABLED` | `false` | Enable EST enrollment endpoints |
|
||||
| `CERTCTL_EST_ISSUER_ID` | `iss-local` | Issuer connector for EST enrollments |
|
||||
| `CERTCTL_EST_PROFILE_ID` | — | Optional profile ID to constrain enrollments |
|
||||
|
||||
**Note:** EST endpoints currently use the same middleware stack as the REST API (API key auth). TLS client certificate authentication for EST is planned for V3.
|
||||
|
||||
### OpenAPI 3.1 Specification
|
||||
- **File** — `api/openapi.yaml`
|
||||
- **Scope** — 93 operations (91 API + /health + /ready), all request/response schemas, enums, pagination
|
||||
- **Scope** — 97 operations (95 API + /health + /ready), all request/response schemas, enums, pagination
|
||||
- **Schemas** — Complete domain models with examples
|
||||
- **Enums** — Job types, states, policy rule types, notification types
|
||||
- **Pagination** — Standard envelope (data, total, page, per_page)
|
||||
@@ -1002,8 +1036,8 @@ The web dashboard is the primary operational interface for certctl. Built with *
|
||||
- **GitHub Actions** — `.github/workflows/ci.yml`
|
||||
- **Parallel Jobs** — Go (build, vet, test+coverage, gates) and Frontend (tsc, vitest, vite build)
|
||||
- **Coverage Gates** — Service layer ≥30%, handler layer ≥50%
|
||||
- **Release Workflow** — Tag push → build → publish Docker images to `ghcr.io`
|
||||
- **Docker Tags** — `:latest`, `:v{version}` (ghcr.io/shankar0123/certctl)
|
||||
- **Release Workflow** — Tag push → build → publish Docker images to GitHub Container Registry
|
||||
- **Docker Tags** — `:latest`, `:v{version}` (`shankar0123.docker.scarf.sh/certctl-server`, `shankar0123.docker.scarf.sh/certctl-agent`)
|
||||
|
||||
### Test Suite
|
||||
- **Unit Tests** — 625+ test functions across service, handler, middleware, domain layers
|
||||
@@ -1084,17 +1118,18 @@ The web dashboard is the primary operational interface for certctl. Built with *
|
||||
|----------|------|---------|---------|
|
||||
| `CERTCTL_ACME_DIRECTORY_URL` | string | (empty) | ACME server directory URL |
|
||||
| `CERTCTL_ACME_EMAIL` | string | (empty) | Account email for ACME registration |
|
||||
| `CERTCTL_ACME_CHALLENGE_TYPE` | string | http-01 | http-01 or dns-01 |
|
||||
| `CERTCTL_ACME_DNS_PRESENT_SCRIPT` | string | (empty) | Script path for DNS-01 present hook |
|
||||
| `CERTCTL_ACME_DNS_CLEANUP_SCRIPT` | string | (empty) | Script path for DNS-01 cleanup hook |
|
||||
| `CERTCTL_ACME_CHALLENGE_TYPE` | string | http-01 | http-01, dns-01, or dns-persist-01 |
|
||||
| `CERTCTL_ACME_DNS_PRESENT_SCRIPT` | string | (empty) | Script path for DNS present hook (dns-01 and dns-persist-01) |
|
||||
| `CERTCTL_ACME_DNS_CLEANUP_SCRIPT` | string | (empty) | Script path for DNS cleanup hook (dns-01 only) |
|
||||
| `CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN` | string | (empty) | CA issuer domain for dns-persist-01 (e.g., letsencrypt.org) |
|
||||
|
||||
#### step-ca Issuer
|
||||
| Variable | Type | Default | Purpose |
|
||||
|----------|------|---------|---------|
|
||||
| `CERTCTL_STEPCA_URL` | string | (empty) | step-ca server URL |
|
||||
| `CERTCTL_STEPCA_PROVISIONER_NAME` | string | (empty) | JWK provisioner name |
|
||||
| `CERTCTL_STEPCA_PROVISIONER_KEY_PATH` | string | (empty) | Path to provisioner JWK private key |
|
||||
| `CERTCTL_STEPCA_PROVISIONER_PASSWORD` | string | (empty) | Provisioner key password (if encrypted) |
|
||||
| `CERTCTL_STEPCA_PROVISIONER` | string | (empty) | JWK provisioner name |
|
||||
| `CERTCTL_STEPCA_KEY_PATH` | string | (empty) | Path to provisioner JWK private key |
|
||||
| `CERTCTL_STEPCA_PASSWORD` | string | (empty) | Provisioner key password (if encrypted) |
|
||||
|
||||
#### OpenSSL/Custom CA Issuer
|
||||
| Variable | Type | Default | Purpose |
|
||||
@@ -1166,11 +1201,11 @@ Each guide includes an evidence summary table mapping specific criteria to certc
|
||||
| Policies + violations | ✓ | ✓ | Shipped |
|
||||
| Profiles + crypto constraints | ✓ | ✓ | Shipped |
|
||||
| Revocation (RFC 5280, CRL, OCSP) | ✓ | ✓ | Shipped |
|
||||
| Dashboard + 19 pages | ✓ | ✓ | Shipped |
|
||||
| Full web dashboard | ✓ | ✓ | Shipped |
|
||||
| Observability (charts, metrics, stats) | ✓ | ✓ | Shipped |
|
||||
| REST API (91 endpoints) | ✓ | ✓ | Shipped |
|
||||
| MCP server (78 tools) | ✓ | ✓ | Shipped v2.1 |
|
||||
| CLI tool (10 subcommands) | ✓ | ✓ | Shipped |
|
||||
| CLI tool (12 subcommands) | ✓ | ✓ | Shipped |
|
||||
| Compliance mapping docs (SOC 2, PCI-DSS, NIST) | ✓ | ✓ | Shipped |
|
||||
| Filesystem cert discovery (M18b) | ✓ | ✓ | Shipped |
|
||||
| Network cert discovery (M21) | ✓ | ✓ | Shipped |
|
||||
@@ -1197,8 +1232,8 @@ Each guide includes an evidence summary table mapping specific criteria to certc
|
||||
|
||||
| Category | Count |
|
||||
|----------|-------|
|
||||
| **API Endpoints** | 91 (under /api/v1/) |
|
||||
| **Dashboard Pages** | 19 |
|
||||
| **API Endpoints** | 95 (under /api/v1/ + /.well-known/est/) |
|
||||
| **Dashboard** | Full web GUI |
|
||||
| **Issuer Connectors** | 4 (Local CA, ACME, step-ca, OpenSSL) |
|
||||
| **Target Connectors** | 5 (3 impl: NGINX, Apache, HAProxy; 2 stubs: F5, IIS) |
|
||||
| **Notifier Channels** | 6 (Email, Webhook, Slack, Teams, PagerDuty, OpsGenie) |
|
||||
|
||||
@@ -1,9 +1,35 @@
|
||||
# Quick Start Guide
|
||||
|
||||
Get certctl running locally and managing certificates in under 5 minutes. With TLS certificate lifespans dropping to 47 days by 2029, automated lifecycle management isn't optional — it's infrastructure. This guide gets you hands-on with certctl's automation loop: tracking, renewing, and deploying certificates without manual intervention.
|
||||
Certificate lifespans are dropping to **47 days by 2029**. At that cadence, a team managing 100 certificates is processing 7+ renewals per week — every week, forever. Manual processes break. certctl automates the entire lifecycle: issuance, renewal, deployment, revocation, and audit — with zero human intervention.
|
||||
|
||||
This guide gets you running in 5 minutes and walks you through everything certctl does.
|
||||
|
||||
New to certificates? Read the [Concepts Guide](concepts.md) first — it explains TLS, CAs, and private keys in plain language.
|
||||
|
||||
## Contents
|
||||
|
||||
1. [Prerequisites](#prerequisites)
|
||||
2. [Start Everything](#start-everything)
|
||||
3. [Open the Dashboard](#open-the-dashboard)
|
||||
4. [Explore the API](#explore-the-api)
|
||||
- [Core operations](#core-operations)
|
||||
- [Sorting, filtering, and pagination](#sorting-filtering-and-pagination)
|
||||
- [Stats and metrics](#stats-and-metrics)
|
||||
5. [Create Your First Certificate](#create-your-first-certificate)
|
||||
- [Revoke a certificate](#revoke-a-certificate)
|
||||
- [Interactive approval workflow](#interactive-approval-workflow)
|
||||
6. [Certificate Discovery](#certificate-discovery)
|
||||
- [Filesystem discovery (agent-based)](#filesystem-discovery-agent-based)
|
||||
- [Network discovery (agentless)](#network-discovery-agentless)
|
||||
- [Triage discovered certificates](#triage-discovered-certificates)
|
||||
7. [CLI Tool](#cli-tool)
|
||||
8. [MCP Server (AI Integration)](#mcp-server-ai-integration)
|
||||
9. [Demo Data Reference](#demo-data-reference)
|
||||
10. [Dashboard Demo Mode](#dashboard-demo-mode)
|
||||
11. [Presenting to Stakeholders](#presenting-to-stakeholders)
|
||||
12. [Tear Down](#tear-down)
|
||||
13. [What's Next](#whats-next)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
You need **Docker** and **Docker Compose** installed. That's it.
|
||||
@@ -23,7 +49,7 @@ cd certctl
|
||||
docker compose -f deploy/docker-compose.yml up -d --build
|
||||
```
|
||||
|
||||
The `--build` flag is important — it builds the server image including the React frontend. Without it, Docker may use a stale cached image that doesn't include the dashboard.
|
||||
The `--build` flag builds the server image including the React frontend. Without it, Docker may use a stale cached image.
|
||||
|
||||
**For production deployments**, copy `deploy/.env.example` to `deploy/.env` and customize the credentials:
|
||||
```bash
|
||||
@@ -32,7 +58,7 @@ cp deploy/.env.example deploy/.env
|
||||
docker compose -f deploy/docker-compose.yml up -d --build
|
||||
```
|
||||
|
||||
Wait about 30 seconds for PostgreSQL to initialize and the server to boot. Check that everything is healthy:
|
||||
Wait about 30 seconds for PostgreSQL to initialize, then verify:
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/docker-compose.yml ps
|
||||
@@ -46,7 +72,6 @@ certctl-server Up (healthy)
|
||||
certctl-agent Up
|
||||
```
|
||||
|
||||
Verify the server responds:
|
||||
```bash
|
||||
curl http://localhost:8443/health
|
||||
```
|
||||
@@ -58,98 +83,125 @@ curl http://localhost:8443/health
|
||||
|
||||
Open **http://localhost:8443** in your browser.
|
||||
|
||||
The dashboard comes pre-loaded with 15 demo certificates across multiple teams, environments, and statuses. You'll see expiring certs, expired certs, active certs, failed renewals — a realistic snapshot of what a certificate inventory looks like in a real organization.
|
||||
The dashboard comes pre-loaded with 15 demo certificates across multiple teams, environments, and statuses — expiring certs, expired certs, active certs, failed renewals. A realistic snapshot of what certificate management looks like in a real organization.
|
||||
|
||||
Explore the sidebar: Certificates, Agents, Policies, Jobs, Audit Trail, Notifications. Everything you see in the dashboard is backed by the REST API.
|
||||
### What you're looking at
|
||||
|
||||
The main dashboard shows total certificates, how many are expiring soon, how many have expired, the renewal success rate, and four charts: an **expiration heatmap** (90-day weekly buckets), **renewal success rate trends** (30-day line chart), **certificate status distribution** (donut chart), and **issuance rate** (30-day bar chart).
|
||||
|
||||
Explore the sidebar: Certificates, Agents, Policies, Jobs, Audit Trail, Notifications, Profiles, Teams, Owners, Agent Groups, Fleet Overview, Short-Lived Credentials, Discovery, and Network Scans.
|
||||
|
||||
### Scenarios to walk through
|
||||
|
||||
**"We're about to have an outage"** — Filter certificates by status → Expiring. You'll see `auth-production` (12 days), `cdn-production` (8 days), and `mail-production` (5 days). At 47-day lifespans, this is every other week. certctl catches these automatically and triggers renewal before they expire.
|
||||
|
||||
**"A renewal failed"** — Look at `vpn-production` — status: Failed. Click it to see the audit trail showing the ACME challenge failure after 3 retry attempts. The system sent a webhook notification to the ops channel. No one had to notice manually.
|
||||
|
||||
**"Who owns this cert?"** — Click any certificate. Owner, team, environment, tags. Clear accountability. Notifications route to the owner's email automatically.
|
||||
|
||||
**"Can I revoke a compromised cert?"** — Click any active certificate, then "Revoke." A modal with RFC 5280 reason codes (Key Compromise, Superseded, Cessation of Operation). After revocation, CRL and OCSP are served automatically — clients stop trusting the cert immediately.
|
||||
|
||||
**"What about certificates already in production?"** — Click "Discovery" in the sidebar. The demo comes pre-loaded with 9 discovered certificates — some found by agents scanning filesystems, some found by the server probing TLS endpoints on the network. You'll see Unmanaged certs waiting for triage (including an expired printer cert and an expiring switch management cert), certs already linked to managed inventory, and one that was dismissed. Claim unmanaged certs to bring them under automation, or dismiss them. Click "Network Scans" to see the 3 configured scan targets with recent scan results.
|
||||
|
||||
**"I need to approve a renewal before it proceeds"** — Click "Jobs" in the sidebar. You'll see an amber banner: "2 jobs awaiting approval." These are renewal jobs for `auth-production` and `payments-production` that require human sign-off before proceeding. Click Approve or Reject with a reason — the decision is recorded in the audit trail.
|
||||
|
||||
**"Show me the agent fleet"** — Click "Agents." Four agents online, one offline. Click "Fleet Overview" for OS/architecture grouping, version distribution, and per-platform listing. Agents generate ECDSA P-256 keys locally — private keys never leave your infrastructure.
|
||||
|
||||
**"What about bulk operations?"** — On the Certificates page, select multiple certificates with checkboxes. A bulk action bar appears: trigger renewal, revoke with reason codes, or reassign ownership — all with progress tracking. At 47-day lifespans with hundreds of certs, bulk operations aren't optional.
|
||||
|
||||
**"Short-lived credentials?"** — Click "Short-Lived" in the sidebar. Live countdown timers for certificates with TTL under 1 hour. Auto-refresh every 10 seconds. These are for service-to-service auth where rapid expiry replaces revocation.
|
||||
|
||||
## Explore the API
|
||||
|
||||
The dashboard reads from the same REST API you can call directly. All endpoints live under `/api/v1/` and return JSON.
|
||||
Everything you see in the dashboard is backed by the REST API. All endpoints live under `/api/v1/` and return JSON.
|
||||
|
||||
### List all certificates
|
||||
### Core operations
|
||||
|
||||
```bash
|
||||
# List all certificates
|
||||
curl -s http://localhost:8443/api/v1/certificates | jq .
|
||||
```
|
||||
|
||||
The response has this shape:
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "mc-api-prod",
|
||||
"name": "API Production",
|
||||
"common_name": "api.example.com",
|
||||
"sans": ["api.example.com", "api-v2.example.com"],
|
||||
"environment": "production",
|
||||
"owner_id": "o-alice",
|
||||
"team_id": "t-platform",
|
||||
"issuer_id": "iss-local",
|
||||
"status": "Active",
|
||||
"expires_at": "2026-05-28T00:00:00Z",
|
||||
"tags": {"service": "api-gateway", "tier": "critical"},
|
||||
"created_at": "2026-03-14T00:00:00Z",
|
||||
"updated_at": "2026-03-14T00:00:00Z"
|
||||
}
|
||||
],
|
||||
"total": 15,
|
||||
"page": 1,
|
||||
"per_page": 50
|
||||
}
|
||||
```
|
||||
|
||||
### Filter by status
|
||||
|
||||
```bash
|
||||
# Get only expiring certificates
|
||||
# Filter by status
|
||||
curl -s "http://localhost:8443/api/v1/certificates?status=Expiring" | jq .
|
||||
|
||||
# Get only production certificates
|
||||
# Filter by environment
|
||||
curl -s "http://localhost:8443/api/v1/certificates?environment=production" | jq .
|
||||
```
|
||||
|
||||
### Get a specific certificate
|
||||
|
||||
```bash
|
||||
# Get a specific certificate
|
||||
curl -s http://localhost:8443/api/v1/certificates/mc-api-prod | jq .
|
||||
```
|
||||
|
||||
### List agents
|
||||
# Get deployment targets for a certificate
|
||||
curl -s http://localhost:8443/api/v1/certificates/mc-api-prod/deployments | jq .
|
||||
|
||||
```bash
|
||||
# List agents
|
||||
curl -s http://localhost:8443/api/v1/agents | jq .
|
||||
```
|
||||
|
||||
### Check agent pending work
|
||||
# Check agent pending work
|
||||
curl -s http://localhost:8443/api/v1/agents/ag-web-prod/work | jq .
|
||||
|
||||
```bash
|
||||
# Replace with an actual agent ID from the list above
|
||||
curl -s http://localhost:8443/api/v1/agents/agent-nginx-prod/work | jq .
|
||||
```
|
||||
|
||||
### View audit trail
|
||||
|
||||
```bash
|
||||
# View audit trail
|
||||
curl -s http://localhost:8443/api/v1/audit | jq .
|
||||
```
|
||||
|
||||
### View policy rules
|
||||
|
||||
```bash
|
||||
# View policies and violations
|
||||
curl -s http://localhost:8443/api/v1/policies | jq .
|
||||
curl -s http://localhost:8443/api/v1/policies/pr-require-owner/violations | jq .
|
||||
|
||||
# Notifications
|
||||
curl -s http://localhost:8443/api/v1/notifications | jq .
|
||||
|
||||
# Profiles and agent groups
|
||||
curl -s http://localhost:8443/api/v1/profiles | jq .
|
||||
curl -s http://localhost:8443/api/v1/agent-groups | jq .
|
||||
```
|
||||
|
||||
### View notifications
|
||||
### Sorting, filtering, and pagination
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:8443/api/v1/notifications | jq .
|
||||
# Sort by expiration date (ascending)
|
||||
curl -s "http://localhost:8443/api/v1/certificates?sort=notAfter" | jq .
|
||||
|
||||
# Sort descending (prefix with -)
|
||||
curl -s "http://localhost:8443/api/v1/certificates?sort=-createdAt" | jq .
|
||||
|
||||
# Time-range filters (RFC3339)
|
||||
curl -s "http://localhost:8443/api/v1/certificates?expires_before=2026-05-01T00:00:00Z" | jq .
|
||||
curl -s "http://localhost:8443/api/v1/certificates?created_after=2026-03-01T00:00:00Z" | jq .
|
||||
|
||||
# Sparse fields — request only what you need
|
||||
curl -s "http://localhost:8443/api/v1/certificates?fields=id,common_name,status,expires_at" | jq .
|
||||
|
||||
# Cursor pagination — efficient for large inventories
|
||||
curl -s "http://localhost:8443/api/v1/certificates?page_size=5" | jq '{next_cursor: .next_cursor, count: (.data | length)}'
|
||||
curl -s "http://localhost:8443/api/v1/certificates?cursor=<next_cursor_value>&page_size=5" | jq .
|
||||
```
|
||||
|
||||
Supported sort fields: `notAfter`, `expiresAt`, `createdAt`, `updatedAt`, `commonName`, `name`, `status`, `environment`.
|
||||
|
||||
### Stats and metrics
|
||||
|
||||
```bash
|
||||
# Dashboard summary
|
||||
curl -s http://localhost:8443/api/v1/stats/summary | jq .
|
||||
|
||||
# Certificates by status
|
||||
curl -s http://localhost:8443/api/v1/stats/certificates-by-status | jq .
|
||||
|
||||
# Expiration timeline (next 90 days)
|
||||
curl -s "http://localhost:8443/api/v1/stats/expiration-timeline?days=90" | jq .
|
||||
|
||||
# Job trends (last 30 days)
|
||||
curl -s "http://localhost:8443/api/v1/stats/job-trends?days=30" | jq .
|
||||
|
||||
# JSON metrics
|
||||
curl -s http://localhost:8443/api/v1/metrics | jq .
|
||||
|
||||
# Prometheus format (for Prometheus, Grafana Agent, Datadog)
|
||||
curl -s http://localhost:8443/api/v1/metrics/prometheus
|
||||
```
|
||||
|
||||
## Create Your First Certificate
|
||||
|
||||
Let's create a new managed certificate from scratch using the API. This will create a certificate record that certctl will track, renew, and deploy.
|
||||
|
||||
### Step 1: Create a certificate
|
||||
Create a certificate record that certctl will track, renew, and deploy automatically.
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:8443/api/v1/certificates \
|
||||
@@ -168,47 +220,26 @@ curl -s -X POST http://localhost:8443/api/v1/certificates \
|
||||
}' | jq .
|
||||
```
|
||||
|
||||
The server returns the created certificate. Since we didn't include an `id` field, the server auto-generates one using the name and a timestamp:
|
||||
```json
|
||||
{
|
||||
"id": "My First Certificate-1710403200000000000",
|
||||
"name": "My First Certificate",
|
||||
"common_name": "myapp.example.com",
|
||||
"status": "Pending",
|
||||
"created_at": "2026-03-14T..."
|
||||
}
|
||||
```
|
||||
|
||||
Save the certificate ID (or provide your own `id` in the request body, e.g. `"id": "mc-my-first"`):
|
||||
```bash
|
||||
CERT_ID="<paste the id from the response>"
|
||||
```
|
||||
|
||||
### Step 2: Trigger renewal
|
||||
|
||||
Trigger renewal:
|
||||
```bash
|
||||
curl -s -X POST http://localhost:8443/api/v1/certificates/$CERT_ID/renew | jq .
|
||||
```
|
||||
|
||||
This creates a renewal job that will be processed by the scheduler.
|
||||
|
||||
### Step 3: Check the certificate
|
||||
|
||||
Check the result:
|
||||
```bash
|
||||
curl -s http://localhost:8443/api/v1/certificates/$CERT_ID | jq .
|
||||
```
|
||||
|
||||
### Step 4: Check the audit trail
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:8443/api/v1/audit | jq '.data[0:3]'
|
||||
```
|
||||
|
||||
Refresh the dashboard at http://localhost:8443 — your new certificate appears in the inventory.
|
||||
|
||||
### Step 5: Revoke a certificate
|
||||
### Revoke a certificate
|
||||
|
||||
If a certificate's private key is compromised or the service is decommissioned, revoke it:
|
||||
When a private key is compromised or a service is decommissioned:
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://localhost:8443/api/v1/certificates/$CERT_ID/revoke \
|
||||
@@ -216,112 +247,21 @@ curl -s -X POST http://localhost:8443/api/v1/certificates/$CERT_ID/revoke \
|
||||
-d '{"reason": "superseded"}' | jq .
|
||||
```
|
||||
|
||||
Supported RFC 5280 reason codes: `unspecified`, `keyCompromise`, `caCompromise`, `affiliationChanged`, `superseded`, `cessationOfOperation`, `certificateHold`, `privilegeWithdrawn`. If you omit the reason, it defaults to `unspecified`.
|
||||
|
||||
Check the CRL to confirm:
|
||||
Supported RFC 5280 reason codes: `unspecified`, `keyCompromise`, `caCompromise`, `affiliationChanged`, `superseded`, `cessationOfOperation`, `certificateHold`, `privilegeWithdrawn`.
|
||||
|
||||
Confirm via CRL:
|
||||
```bash
|
||||
curl -s http://localhost:8443/api/v1/crl | jq .
|
||||
```
|
||||
|
||||
## Understanding the Demo Data
|
||||
|
||||
The demo comes pre-loaded with realistic data so you can explore certctl's features immediately:
|
||||
|
||||
| Resource | Count | Examples |
|
||||
|----------|-------|---------|
|
||||
| Teams | 5 | Platform, Security, Payments, Frontend, Data |
|
||||
| Owners | 5 | Alice, Bob, Carol, Dave, Eve |
|
||||
| Issuers | 4 | Local Dev CA, Let's Encrypt Staging, step-ca Internal, DigiCert (disabled) |
|
||||
| Agents | 5 | nginx-prod, nginx-staging, f5-prod, iis-prod, data-agent |
|
||||
| Targets | 5 | NGINX (prod/staging/data), F5 LB, IIS |
|
||||
| Certificates | 15 | Various statuses: Active, Expiring, Expired, Failed, Wildcard |
|
||||
| Policies | 4 | Required owner, allowed environments, max lifetime, min renewal window |
|
||||
| Profiles | 3 | Default TLS, Short-Lived, High-Security |
|
||||
| Agent Groups | 5 | Linux agents, ARM agents, Production subnet, etc. |
|
||||
|
||||
Certificates have varied statuses so you can see what each state looks like in the dashboard: healthy certs with 45+ days remaining, certs about to expire (5-12 days), certs that already expired, and a failed renewal.
|
||||
|
||||
## Advanced API Features
|
||||
|
||||
### Sorting and filtering
|
||||
|
||||
```bash
|
||||
# Sort certificates by expiration date (ascending)
|
||||
curl -s "http://localhost:8443/api/v1/certificates?sort=notAfter" | jq .
|
||||
|
||||
# Sort descending (prefix with -)
|
||||
curl -s "http://localhost:8443/api/v1/certificates?sort=-createdAt" | jq .
|
||||
|
||||
# Time-range filters (RFC3339 format)
|
||||
curl -s "http://localhost:8443/api/v1/certificates?expires_before=2026-05-01T00:00:00Z" | jq .
|
||||
curl -s "http://localhost:8443/api/v1/certificates?created_after=2026-03-01T00:00:00Z" | jq .
|
||||
```
|
||||
|
||||
Supported sort fields: `notAfter`, `expiresAt`, `createdAt`, `updatedAt`, `commonName`, `name`, `status`, `environment`.
|
||||
|
||||
### Sparse field selection
|
||||
|
||||
Request only the fields you need to reduce response size:
|
||||
|
||||
```bash
|
||||
curl -s "http://localhost:8443/api/v1/certificates?fields=id,common_name,status,expires_at" | jq .
|
||||
```
|
||||
|
||||
### Cursor-based pagination
|
||||
|
||||
For large datasets, cursor pagination is more efficient than page-based:
|
||||
|
||||
```bash
|
||||
# First page
|
||||
curl -s "http://localhost:8443/api/v1/certificates?page_size=5" | jq '{next_cursor: .next_cursor, count: (.data | length)}'
|
||||
|
||||
# Next page (use the next_cursor from the previous response)
|
||||
curl -s "http://localhost:8443/api/v1/certificates?cursor=<next_cursor_value>&page_size=5" | jq .
|
||||
```
|
||||
|
||||
### Stats and metrics
|
||||
|
||||
```bash
|
||||
# Dashboard summary
|
||||
curl -s http://localhost:8443/api/v1/stats/summary | jq .
|
||||
|
||||
# Certificates by status
|
||||
curl -s http://localhost:8443/api/v1/stats/certificates-by-status | jq .
|
||||
|
||||
# Expiration timeline (next 90 days)
|
||||
curl -s "http://localhost:8443/api/v1/stats/expiration-timeline?days=90" | jq .
|
||||
|
||||
# Job trends (last 30 days)
|
||||
curl -s "http://localhost:8443/api/v1/stats/job-trends?days=30" | jq .
|
||||
|
||||
# System metrics (JSON)
|
||||
curl -s http://localhost:8443/api/v1/metrics | jq .
|
||||
|
||||
# System metrics (Prometheus format — for scraping by Prometheus, Grafana Agent, Datadog)
|
||||
curl -s http://localhost:8443/api/v1/metrics/prometheus
|
||||
```
|
||||
|
||||
### Certificate profiles
|
||||
|
||||
```bash
|
||||
# List all profiles
|
||||
curl -s http://localhost:8443/api/v1/profiles | jq .
|
||||
|
||||
# Get a specific profile
|
||||
curl -s http://localhost:8443/api/v1/profiles/prof-default | jq .
|
||||
```
|
||||
|
||||
### Certificate deployments
|
||||
|
||||
```bash
|
||||
# View deployment targets for a certificate
|
||||
curl -s http://localhost:8443/api/v1/certificates/mc-api-prod/deployments | jq .
|
||||
```
|
||||
|
||||
### Interactive approval workflow
|
||||
|
||||
For high-value certificates where you want human oversight. The demo includes 2 pre-seeded jobs in `AwaitingApproval` status (for `auth-production` and `payments-production`). Open **Jobs** in the sidebar and you'll see the amber "Pending Approval" banner immediately.
|
||||
|
||||
```bash
|
||||
# List jobs awaiting approval (demo includes 2)
|
||||
curl -s "http://localhost:8443/api/v1/jobs?status=AwaitingApproval" | jq '.data[] | {id, certificate_id, status}'
|
||||
|
||||
# Approve a pending job
|
||||
curl -s -X POST http://localhost:8443/api/v1/jobs/JOB_ID/approve \
|
||||
-H "Content-Type: application/json" \
|
||||
@@ -333,49 +273,27 @@ curl -s -X POST http://localhost:8443/api/v1/jobs/JOB_ID/reject \
|
||||
-d '{"reason": "Key type does not meet compliance requirements"}' | jq .
|
||||
```
|
||||
|
||||
## Tear Down
|
||||
## Certificate Discovery
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/docker-compose.yml down -v
|
||||
```
|
||||
Find certificates already running in your infrastructure — ones you didn't issue through certctl.
|
||||
|
||||
The `-v` flag removes the PostgreSQL data volume so you get a clean slate next time.
|
||||
The demo environment comes pre-loaded with 9 discovered certificates (from agent filesystem scans and server-side network scans), 3 network scan targets, and recent scan history. Open **Discovery** and **Network Scans** in the sidebar to see the triage workflow immediately.
|
||||
|
||||
### Certificate Discovery
|
||||
|
||||
Agents can scan your infrastructure for existing certificates you're not yet managing:
|
||||
### Filesystem discovery (agent-based)
|
||||
|
||||
```bash
|
||||
# Configure agent to scan directories
|
||||
export CERTCTL_DISCOVERY_DIRS="/etc/nginx/certs,/etc/ssl/certs,/var/lib/certs"
|
||||
|
||||
# Agent scans on startup + every 6 hours, reports findings to control plane
|
||||
# Agent scans on startup + every 6 hours
|
||||
```
|
||||
|
||||
Query discovered certificates:
|
||||
### Network discovery (agentless)
|
||||
|
||||
```bash
|
||||
# List all discovered certs from a specific agent
|
||||
curl -s "http://localhost:8443/api/v1/discovered-certificates?agent_id=agent-nginx-prod" | jq .
|
||||
|
||||
# Get discovery summary (counts by status)
|
||||
curl -s http://localhost:8443/api/v1/discovery-summary | jq .
|
||||
|
||||
# Claim a discovered cert (link to managed cert)
|
||||
curl -s -X POST "http://localhost:8443/api/v1/discovered-certificates/DISCOVERY_ID/claim" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"managed_certificate_id": "mc-api-prod"}' | jq .
|
||||
```
|
||||
|
||||
### Network Certificate Discovery
|
||||
|
||||
The server can also discover certificates by scanning TLS endpoints directly — no agent required:
|
||||
|
||||
```bash
|
||||
# Enable network scanning (set in environment or docker-compose)
|
||||
# Enable network scanning
|
||||
export CERTCTL_NETWORK_SCAN_ENABLED=true
|
||||
|
||||
# Create a scan target (e.g., scan your internal network on port 443)
|
||||
# Create a scan target
|
||||
curl -s -X POST http://localhost:8443/api/v1/network-scan-targets \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
@@ -389,17 +307,109 @@ curl -s -X POST http://localhost:8443/api/v1/network-scan-targets \
|
||||
|
||||
# Trigger an immediate scan
|
||||
curl -s -X POST http://localhost:8443/api/v1/network-scan-targets/nst-internal-network/scan | jq .
|
||||
|
||||
# List scan targets with results
|
||||
curl -s http://localhost:8443/api/v1/network-scan-targets | jq .
|
||||
```
|
||||
|
||||
Discovered network certificates appear in the same `GET /api/v1/discovered-certificates` list as filesystem-discovered certs, with `agent_id=server-scanner` and `source_format=network`.
|
||||
### Triage discovered certificates
|
||||
|
||||
```bash
|
||||
# List discovered certs
|
||||
curl -s "http://localhost:8443/api/v1/discovered-certificates?agent_id=agent-nginx-prod" | jq .
|
||||
|
||||
# Summary counts
|
||||
curl -s http://localhost:8443/api/v1/discovery-summary | jq .
|
||||
|
||||
# Claim a discovered cert (bring under management)
|
||||
curl -s -X POST "http://localhost:8443/api/v1/discovered-certificates/DISCOVERY_ID/claim" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"managed_certificate_id": "mc-api-prod"}' | jq .
|
||||
```
|
||||
|
||||
## CLI Tool
|
||||
|
||||
```bash
|
||||
cd cmd/cli && go build -o certctl-cli .
|
||||
|
||||
export CERTCTL_SERVER_URL="http://localhost:8443"
|
||||
export CERTCTL_API_KEY="test-key-123"
|
||||
|
||||
./certctl-cli certs list # List certificates
|
||||
./certctl-cli certs get mc-api-prod # Certificate details
|
||||
./certctl-cli certs renew mc-api-prod # Trigger renewal
|
||||
./certctl-cli certs revoke mc-api-prod --reason keyCompromise
|
||||
./certctl-cli agents list # List agents
|
||||
./certctl-cli jobs list # List jobs
|
||||
./certctl-cli import /path/to/certs.pem # Bulk import
|
||||
./certctl-cli status # Health + stats
|
||||
```
|
||||
|
||||
## MCP Server (AI Integration)
|
||||
|
||||
```bash
|
||||
cd cmd/mcp-server && go build -o mcp-server .
|
||||
|
||||
export CERTCTL_SERVER_URL="http://localhost:8443"
|
||||
export CERTCTL_API_KEY="test-key-123"
|
||||
|
||||
./mcp-server
|
||||
```
|
||||
|
||||
Exposes 78 MCP tools covering the REST API via stdio transport. Ask Claude: "What certificates are expiring in the next 30 days?", "Revoke the payments cert due to key compromise", "Show me the audit trail."
|
||||
|
||||
## Demo Data Reference
|
||||
|
||||
| Resource | Count | Examples |
|
||||
|----------|-------|---------|
|
||||
| Teams | 5 | Platform, Security, Payments, Frontend, Data |
|
||||
| Owners | 5 | Alice, Bob, Carol, Dave, Eve |
|
||||
| Issuers | 4 | Local Dev CA, Let's Encrypt Staging, step-ca Internal, DigiCert (disabled) |
|
||||
| Agents | 6 | ag-web-prod, ag-web-staging, ag-lb-prod, ag-iis-prod, ag-data-prod, server-scanner (network discovery) |
|
||||
| Targets | 5 | NGINX (prod/staging/data), F5 LB, IIS |
|
||||
| Certificates | 15 | Various statuses: Active, Expiring, Expired, Failed, Wildcard |
|
||||
| Discovered Certs | 9 | 5 Unmanaged (filesystem + network), 2 Managed (linked), 1 Dismissed, network-discovered expired printer cert |
|
||||
| Discovery Scans | 3 | Agent filesystem scans + network TLS scan |
|
||||
| Network Scan Targets | 3 | DC1 Web Servers, DC2 Application Tier, DMZ Public Endpoints |
|
||||
| Jobs (Approval) | 2 | AwaitingApproval renewal jobs for auth-prod and payments-prod |
|
||||
| Policies | 4 | Required owner, allowed environments, max lifetime, min renewal window |
|
||||
| Profiles | 4 | Standard TLS, Internal mTLS, Short-Lived, High Security |
|
||||
| Agent Groups | 5 | Linux agents, ARM agents, Production subnet, etc. |
|
||||
|
||||
## Dashboard Demo Mode
|
||||
|
||||
The dashboard works without a backend for screenshots and presentations:
|
||||
|
||||
```bash
|
||||
cd web && npm install && npm run dev
|
||||
# Dashboard at http://localhost:5173
|
||||
```
|
||||
|
||||
When the API is unreachable, the dashboard loads realistic mock data with a "Demo Mode" badge.
|
||||
|
||||
## Presenting to Stakeholders
|
||||
|
||||
A suggested 5-minute flow:
|
||||
|
||||
1. **Dashboard** — "Certificate inventory at a glance. Real-time charts show expiration trends and renewal health."
|
||||
2. **Expiring certs** — "These three would have caused outages. At 47-day lifespans, this happens every other week."
|
||||
3. **Certificate detail** — "Full lifecycle: who owns it, where it's deployed, deployment timeline, version history with rollback."
|
||||
4. **Revocation** — "One click revokes with an RFC 5280 reason code. CRL and OCSP served automatically."
|
||||
5. **Failed renewal** — "System tried 3 times, then alerted the team via Slack, Teams, PagerDuty, or OpsGenie."
|
||||
6. **Agent fleet** — "Agents handle key generation locally (ECDSA P-256). Private keys never leave your infrastructure."
|
||||
7. **Discovery** — "Agents scan filesystems, server probes TLS endpoints. We find what you're not managing yet."
|
||||
8. **Bulk operations** — "Select multiple certs, renew or revoke in bulk. At 47-day lifespans with hundreds of certs, this is essential."
|
||||
9. **Audit trail** — "Every action recorded. Export to CSV/JSON for compliance."
|
||||
10. **CLI + MCP** — "Terminal users get `certctl-cli`. AI assistants get MCP integration. Everything is API-first."
|
||||
|
||||
## Tear Down
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/docker-compose.yml down -v
|
||||
```
|
||||
|
||||
The `-v` flag removes the PostgreSQL data volume for a clean slate.
|
||||
|
||||
## What's Next
|
||||
|
||||
- **[Advanced Demo](demo-advanced.md)** — Issue a real certificate via the Local CA and watch it appear in the dashboard
|
||||
- **[Demo Walkthrough](demo-guide.md)** — Guided 5-minute stakeholder presentation
|
||||
- **[Advanced Demo](demo-advanced.md)** — Issue a real certificate via the Local CA end-to-end
|
||||
- **[Architecture](architecture.md)** — How the control plane, agents, and connectors work together
|
||||
- **[Connector Guide](connectors.md)** — Build custom connectors for your infrastructure
|
||||
- **[CLI Reference](cli.md)** — Manage certificates from your terminal
|
||||
- **[Concepts Guide](concepts.md)** — TLS certificates, CAs, and private keys explained from scratch
|
||||
|
||||
|
After Width: | Height: | Size: 755 KiB |
|
After Width: | Height: | Size: 179 KiB |
|
After Width: | Height: | Size: 160 KiB |
|
After Width: | Height: | Size: 340 KiB |
|
After Width: | Height: | Size: 296 KiB |
|
After Width: | Height: | Size: 229 KiB |
|
After Width: | Height: | Size: 182 KiB |
|
After Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 179 KiB |
|
After Width: | Height: | Size: 293 KiB |
|
After Width: | Height: | Size: 150 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 192 KiB |
|
After Width: | Height: | Size: 120 KiB |
|
After Width: | Height: | Size: 154 KiB |
|
After Width: | Height: | Size: 148 KiB |
|
After Width: | Height: | Size: 438 KiB |
|
After Width: | Height: | Size: 404 KiB |
|
After Width: | Height: | Size: 700 KiB |
|
After Width: | Height: | Size: 680 KiB |
|
After Width: | Height: | Size: 500 KiB |
|
After Width: | Height: | Size: 432 KiB |
|
After Width: | Height: | Size: 399 KiB |
|
After Width: | Height: | Size: 454 KiB |
|
After Width: | Height: | Size: 615 KiB |
|
After Width: | Height: | Size: 396 KiB |
|
After Width: | Height: | Size: 414 KiB |
|
After Width: | Height: | Size: 485 KiB |
|
After Width: | Height: | Size: 289 KiB |
|
After Width: | Height: | Size: 402 KiB |
|
After Width: | Height: | Size: 391 KiB |
@@ -1,12 +1,43 @@
|
||||
# certctl V2.0 Release QA Guide
|
||||
|
||||
Comprehensive manual testing playbook. Every test has a concrete command, an explanation of what it validates and why it matters, exact expected output, and an unambiguous pass/fail criterion. Run every test before tagging v2.0.0.
|
||||
Comprehensive manual testing playbook. Every test has a concrete command, an explanation of what it validates and why it matters, exact expected output, and an unambiguous pass/fail criterion.
|
||||
|
||||
## Contents
|
||||
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Part 1: Infrastructure & Deployment](#part-1-infrastructure--deployment)
|
||||
- [Part 2: Authentication & Security](#part-2-authentication--security)
|
||||
- [Part 3: Certificate Lifecycle (CRUD)](#part-3-certificate-lifecycle-crud)
|
||||
- [Part 4: Renewal Workflow](#part-4-renewal-workflow)
|
||||
- [Part 5: Revocation](#part-5-revocation)
|
||||
- [Part 6: Issuer Connectors](#part-6-issuer-connectors)
|
||||
- [Part 7: Target Connectors & Deployment](#part-7-target-connectors--deployment)
|
||||
- [Part 8: Agent Operations](#part-8-agent-operations)
|
||||
- [Part 9: Job System](#part-9-job-system)
|
||||
- [Part 10: Policies & Profiles](#part-10-policies--profiles)
|
||||
- [Part 11: Ownership, Teams & Agent Groups](#part-11-ownership-teams--agent-groups)
|
||||
- [Part 12: Notifications](#part-12-notifications)
|
||||
- [Part 13: Observability](#part-13-observability)
|
||||
- [Part 14: Audit Trail](#part-14-audit-trail)
|
||||
- [Part 15: Certificate Discovery (Filesystem + Network)](#part-15-certificate-discovery-filesystem--network)
|
||||
- [Part 16: Enhanced Query API](#part-16-enhanced-query-api)
|
||||
- [Part 17: CLI Tool](#part-17-cli-tool)
|
||||
- [Part 18: MCP Server](#part-18-mcp-server)
|
||||
- [Part 19: GUI Testing](#part-19-gui-testing)
|
||||
- [Part 20: Background Scheduler](#part-20-background-scheduler)
|
||||
- [Part 21: Error Handling](#part-21-error-handling)
|
||||
- [Part 22: Performance Spot Checks](#part-22-performance-spot-checks)
|
||||
- [Part 23: Structured Logging Verification](#part-23-structured-logging-verification)
|
||||
- [Part 24: Documentation Verification](#part-24-documentation-verification)
|
||||
- [Part 25: Regression Tests](#part-25-regression-tests)
|
||||
- [Part 26: EST Server (RFC 7030)](#part-26-est-server-rfc-7030)
|
||||
- [Release Sign-Off](#release-sign-off)
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Why manual QA on top of 900+ automated tests?
|
||||
### Why manual QA on top of automated tests?
|
||||
|
||||
Automated tests mock dependencies and run in isolation. Manual QA validates the full integrated stack: real PostgreSQL, real HTTP, real agent binary, real file I/O, real scheduler timing. It catches issues that unit tests can't: migration ordering, Docker networking, env var parsing, browser rendering, and timing-dependent scheduler behavior.
|
||||
|
||||
@@ -1423,6 +1454,62 @@ curl -s -w "\nHTTP %{http_code}\n" -X POST -H "$AUTH" -H "$CT" \
|
||||
|
||||
---
|
||||
|
||||
### 6.2 ACME DNS Challenge Configuration
|
||||
|
||||
**Test 6.2.1 — List ACME issuer with DNS-01 configuration**
|
||||
|
||||
```bash
|
||||
curl -s -H "$AUTH" "$SERVER/api/v1/issuers/iss-acme-le" | jq '{id, type, config}'
|
||||
```
|
||||
|
||||
**What:** Retrieves the ACME Let's Encrypt issuer and verifies its configuration.
|
||||
**Why:** ACME issuers configured for DNS-01 challenges need their solver scripts accessible for wildcard certificate support.
|
||||
**Expected:** HTTP 200. `type` = "acme". `config` may include challenge type and DNS script paths.
|
||||
**PASS if** HTTP 200 and type matches. **FAIL** otherwise.
|
||||
|
||||
---
|
||||
|
||||
**Test 6.2.2 — Create ACME issuer with DNS-PERSIST-01**
|
||||
|
||||
Edit `deploy/docker-compose.yml` to set environment variables for ACME DNS-PERSIST-01:
|
||||
- `CERTCTL_ACME_CHALLENGE_TYPE: dns-persist-01`
|
||||
- `CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN: le.example.com`
|
||||
- `CERTCTL_ACME_DNS_PRESENT_SCRIPT: /usr/local/bin/dns-present.sh`
|
||||
- `CERTCTL_ACME_DNS_CLEANUP_SCRIPT: /usr/local/bin/dns-cleanup.sh`
|
||||
|
||||
Restart and verify the issuer accepts the config:
|
||||
|
||||
```bash
|
||||
curl -s -H "$AUTH" "$SERVER/api/v1/issuers/iss-acme-le" | jq '{id, type}'
|
||||
```
|
||||
|
||||
**What:** Verifies that ACME issuers read DNS-PERSIST-01 configuration from environment variables.
|
||||
**Why:** DNS-PERSIST-01 requires a standing TXT record per IETF draft. The issuer must know the issuer domain and support this challenge type.
|
||||
**Expected:** HTTP 200. ACME issuer still functional.
|
||||
**PASS if** HTTP 200 and issuer still works. **FAIL** if 500 or issuer broken.
|
||||
|
||||
---
|
||||
|
||||
**Test 6.2.3 — Configure ACME with External Account Binding (ZeroSSL)**
|
||||
|
||||
Edit `deploy/docker-compose.yml` to set EAB environment variables:
|
||||
- `CERTCTL_ACME_DIRECTORY_URL: https://acme.zerossl.com/v2/DV90`
|
||||
- `CERTCTL_ACME_EAB_KID: your-zerossl-kid`
|
||||
- `CERTCTL_ACME_EAB_HMAC: your-base64url-hmac-key`
|
||||
|
||||
Restart and verify the issuer accepts the config:
|
||||
|
||||
```bash
|
||||
curl -s -H "$AUTH" "$SERVER/api/v1/issuers/iss-acme-prod" | jq '{id, type}'
|
||||
```
|
||||
|
||||
**What:** Verifies that ACME issuers read External Account Binding credentials from environment variables.
|
||||
**Why:** ZeroSSL, Google Trust Services, and SSL.com require EAB for ACME account registration. Without EAB, account creation fails and no certificates can be issued from these CAs.
|
||||
**Expected:** HTTP 200. ACME issuer functional with EAB credentials loaded.
|
||||
**PASS if** HTTP 200 and issuer responds. **FAIL** if 500 or startup errors related to EAB.
|
||||
|
||||
---
|
||||
|
||||
## Part 7: Target Connectors & Deployment
|
||||
|
||||
**What this validates:** CRUD for deployment targets, including type-specific configuration for all 5 target types.
|
||||
@@ -2094,6 +2181,49 @@ curl -s -w "\nHTTP %{http_code}\n" -X DELETE -H "$AUTH" "$SERVER/api/v1/agent-gr
|
||||
|
||||
---
|
||||
|
||||
### 11.4 Foreign Key Constraint Behavior
|
||||
|
||||
**What this validates:** Delete operations correctly fail with 409 when referenced entities still exist.
|
||||
|
||||
**Why it matters:** Owners and issuers use `ON DELETE RESTRICT` — you can't delete them while certificates reference them. Teams use `ON DELETE CASCADE`, so team deletes succeed and cascade. If the server returns a silent 500 instead of 409, the GUI swallows the error and the user thinks nothing happened.
|
||||
|
||||
**Test 11.4.1 — Delete owner with assigned certificates (expect 409)**
|
||||
|
||||
```bash
|
||||
# Try to delete Alice Chen (o-alice) — she owns certificates in the demo data
|
||||
curl -s -w "\nHTTP %{http_code}\n" -X DELETE -H "$AUTH" "$SERVER/api/v1/owners/o-alice" | jq .
|
||||
```
|
||||
|
||||
**Expected:** HTTP 409 with message "Cannot delete owner: certificates are still assigned to this owner".
|
||||
**PASS if** 409 Conflict. **FAIL** if 204 (data integrity violation) or 500 (unhelpful error).
|
||||
|
||||
---
|
||||
|
||||
**Test 11.4.2 — Delete issuer with assigned certificates (expect 409)**
|
||||
|
||||
```bash
|
||||
# Try to delete the Local Dev CA (iss-local) — certificates reference it
|
||||
curl -s -w "\nHTTP %{http_code}\n" -X DELETE -H "$AUTH" "$SERVER/api/v1/issuers/iss-local" | jq .
|
||||
```
|
||||
|
||||
**Expected:** HTTP 409 with message "Cannot delete issuer: certificates are still using this issuer".
|
||||
**PASS if** 409 Conflict. **FAIL** if 204 or 500.
|
||||
|
||||
---
|
||||
|
||||
**Test 11.4.3 — Delete team cascades successfully**
|
||||
|
||||
```bash
|
||||
# Create a test team, then delete it — teams use ON DELETE CASCADE
|
||||
curl -s -X POST -H "$AUTH" -H "$CT" -d '{"id": "t-fk-test", "name": "FK Test Team"}' $SERVER/api/v1/teams > /dev/null
|
||||
curl -s -w "\nHTTP %{http_code}\n" -X DELETE -H "$AUTH" "$SERVER/api/v1/teams/t-fk-test"
|
||||
```
|
||||
|
||||
**Expected:** HTTP 204 (cascade allows deletion).
|
||||
**PASS if** 204. **FAIL** if 409 or 500.
|
||||
|
||||
---
|
||||
|
||||
## Part 12: Notifications
|
||||
|
||||
**What this validates:** Notification creation, listing, and read status management.
|
||||
@@ -2325,8 +2455,8 @@ curl -s -H "$AUTH" "$SERVER/api/v1/metrics/prometheus" | grep -c "^# HELP"
|
||||
|
||||
**What:** Counts `# HELP` comment lines (metric descriptions).
|
||||
**Why:** HELP lines are required by the Prometheus exposition format. Missing = non-compliant.
|
||||
**Expected:** Count ≥ 11 (one per metric).
|
||||
**PASS if** count ≥ 11. **FAIL** if 0.
|
||||
**Expected:** Count > 0 (one per metric).
|
||||
**PASS if** count > 0. **FAIL** if 0.
|
||||
|
||||
---
|
||||
|
||||
@@ -2337,12 +2467,12 @@ curl -s -H "$AUTH" "$SERVER/api/v1/metrics/prometheus" | grep -c "^# TYPE"
|
||||
```
|
||||
|
||||
**What:** Counts `# TYPE` annotations (gauge/counter declarations).
|
||||
**Expected:** Count ≥ 11.
|
||||
**PASS if** count ≥ 11. **FAIL** if 0.
|
||||
**Expected:** Count > 0.
|
||||
**PASS if** count > 0. **FAIL** if 0.
|
||||
|
||||
---
|
||||
|
||||
**Test 13.3.4 — All 11 Prometheus metrics present**
|
||||
**Test 13.3.4 — All documented Prometheus metrics present**
|
||||
|
||||
```bash
|
||||
METRICS=$(curl -s -H "$AUTH" "$SERVER/api/v1/metrics/prometheus")
|
||||
@@ -2352,10 +2482,10 @@ for m in certctl_certificate_total certctl_certificate_active certctl_certificat
|
||||
done
|
||||
```
|
||||
|
||||
**What:** Verifies all 11 documented Prometheus metrics are present in the output.
|
||||
**What:** Verifies all documented Prometheus metrics are present in the output.
|
||||
**Why:** Missing metrics mean missing dashboard panels in Grafana. Each metric was chosen for operational value.
|
||||
**Expected:** Each metric reports count = 1 (present).
|
||||
**PASS if** all 11 metrics show count = 1. **FAIL** if any shows 0.
|
||||
**PASS if** all metrics show count = 1. **FAIL** if any shows 0.
|
||||
|
||||
---
|
||||
|
||||
@@ -3192,7 +3322,7 @@ echo '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"get_certificate",
|
||||
|
||||
## Part 19: GUI Testing
|
||||
|
||||
**What this validates:** The web dashboard — 19 pages of operational UI.
|
||||
**What this validates:** The full web dashboard — all pages of operational UI.
|
||||
|
||||
**Why it matters:** Operators spend 80% of their time in the GUI. If it's broken, the product is broken, regardless of how good the API is.
|
||||
|
||||
@@ -3236,26 +3366,61 @@ Open `http://localhost:8443` in a browser.
|
||||
| 19.4.5 | Inline policy editor | Click edit on policy section | Dropdown selectors appear, save/cancel buttons | PASS if edit mode works |
|
||||
| 19.4.6 | Revoke button | Click revoke | Reason modal, status updates after | PASS if revocation completes |
|
||||
|
||||
### 19.5 Other Pages
|
||||
|
||||
| Test ID | Test | Page | Expected | Pass/Fail Criteria |
|
||||
|---------|------|------|----------|-------------------|
|
||||
| 19.5.1 | Target wizard | Targets → New Target | 3-step wizard (type → config → review) | PASS if all 3 steps work |
|
||||
| 19.5.2 | Audit filters | Audit | Time, actor, action filters work | PASS if filters change results |
|
||||
| 19.5.3 | Audit export | Audit → Export | CSV/JSON file downloads | PASS if file downloads |
|
||||
| 19.5.4 | Short-lived creds | Short-Lived | Certs with TTL < 1h, countdown timers | PASS if timers count down |
|
||||
| 19.5.5 | Agent list | Agents | OS/Arch column visible | PASS if metadata shown |
|
||||
| 19.5.6 | Agent detail | Click agent | System Information card | PASS if OS, arch, IP shown |
|
||||
| 19.5.7 | Fleet overview | Fleet Overview | OS/arch grouping charts | PASS if pie charts render |
|
||||
|
||||
### 19.6 Cross-Cutting
|
||||
### 19.5 Jobs Page — Approval Workflow
|
||||
|
||||
| Test ID | Test | Action | Expected | Pass/Fail Criteria |
|
||||
|---------|------|--------|----------|-------------------|
|
||||
| 19.6.1 | Sidebar nav | Click all sidebar links | All pages load without errors | PASS if no broken routes |
|
||||
| 19.6.2 | Logout | Click logout | Returns to login screen | PASS if login page shown |
|
||||
| 19.6.3 | 401 redirect | Expire/remove auth token | Auto-redirect to login | PASS if login page shown |
|
||||
| 19.6.4 | Dark theme | Check page styling | Dark background, readable text | PASS if theme consistent |
|
||||
| 19.5.1 | Approval banner | Navigate to Jobs with AwaitingApproval jobs | Amber banner shows count of pending approvals | PASS if banner visible with correct count |
|
||||
| 19.5.2 | Approve button | Find AwaitingApproval job, click Approve | Job status changes to Running/Completed | PASS if status transitions |
|
||||
| 19.5.3 | Reject button | Find AwaitingApproval job, click Reject | Modal opens with reason input | PASS if modal appears |
|
||||
| 19.5.4 | Reject with reason | Enter reason, submit rejection | Job status changes, modal closes | PASS if job rejected |
|
||||
| 19.5.5 | Status filter | Select "Awaiting Approval" from status dropdown | Only AwaitingApproval jobs shown | PASS if filter works |
|
||||
| 19.5.6 | AwaitingCSR filter | Select "Awaiting CSR" from status dropdown | Only AwaitingCSR jobs shown | PASS if filter works |
|
||||
|
||||
### 19.6 Discovery Triage Page
|
||||
|
||||
| Test ID | Test | Action | Expected | Pass/Fail Criteria |
|
||||
|---------|------|--------|----------|-------------------|
|
||||
| 19.6.1 | Summary stats | Navigate to Discovery | Stats bar shows Unmanaged/Managed/Dismissed counts | PASS if all 3 counts visible |
|
||||
| 19.6.2 | Table loads | View Discovery page | Table populated with discovered certificates | PASS if certs listed |
|
||||
| 19.6.3 | Status filter | Select "Unmanaged" from status dropdown | Only Unmanaged certs shown | PASS if filter works |
|
||||
| 19.6.4 | Agent filter | Select agent from dropdown | Certs filtered by agent | PASS if filter works |
|
||||
| 19.6.5 | Claim button | Click Claim on Unmanaged cert | Modal opens with managed cert ID input | PASS if modal appears |
|
||||
| 19.6.6 | Claim submit | Enter cert ID, submit claim | Cert status changes to Managed, modal closes | PASS if status updates |
|
||||
| 19.6.7 | Dismiss button | Click Dismiss on Unmanaged cert | Cert status changes to Dismissed | PASS if status updates |
|
||||
| 19.6.8 | Scan history | Click "Show Scan History" | Collapsible panel shows scan records with agent, directories, counts | PASS if scan history visible |
|
||||
|
||||
### 19.7 Network Scan Management Page
|
||||
|
||||
| Test ID | Test | Action | Expected | Pass/Fail Criteria |
|
||||
|---------|------|--------|----------|-------------------|
|
||||
| 19.7.1 | Table loads | Navigate to Network Scans | Table with seed scan targets | PASS if targets listed |
|
||||
| 19.7.2 | New Target button | Click "+ New Target" | Create modal opens | PASS if modal visible |
|
||||
| 19.7.3 | Create target | Fill name, CIDRs, ports, submit | New target appears in table | PASS if target created |
|
||||
| 19.7.4 | Enable toggle | Click toggle on a target | Enabled state flips | PASS if toggle works |
|
||||
| 19.7.5 | Scan Now | Click Scan Now on a target | Scan triggered (check last_scan_at updates) | PASS if scan initiated |
|
||||
| 19.7.6 | Delete target | Click Delete on a target | Target removed from table | PASS if target gone |
|
||||
|
||||
### 19.8 Other Pages
|
||||
|
||||
| Test ID | Test | Page | Expected | Pass/Fail Criteria |
|
||||
|---------|------|------|----------|-------------------|
|
||||
| 19.8.1 | Target wizard | Targets → New Target | 3-step wizard (type → config → review) | PASS if all 3 steps work |
|
||||
| 19.8.2 | Audit filters | Audit | Time, actor, action filters work | PASS if filters change results |
|
||||
| 19.8.3 | Audit export | Audit → Export | CSV/JSON file downloads | PASS if file downloads |
|
||||
| 19.8.4 | Short-lived creds | Short-Lived | Certs with TTL < 1h, countdown timers | PASS if timers count down |
|
||||
| 19.8.5 | Agent list | Agents | OS/Arch column visible | PASS if metadata shown |
|
||||
| 19.8.6 | Agent detail | Click agent | System Information card | PASS if OS, arch, IP shown |
|
||||
| 19.8.7 | Fleet overview | Fleet Overview | OS/arch grouping charts | PASS if pie charts render |
|
||||
|
||||
### 19.9 Cross-Cutting
|
||||
|
||||
| Test ID | Test | Action | Expected | Pass/Fail Criteria |
|
||||
|---------|------|--------|----------|-------------------|
|
||||
| 19.9.1 | Sidebar nav | Click all sidebar links | All 21 pages load without errors | PASS if no broken routes |
|
||||
| 19.9.2 | Logout | Click logout | Returns to login screen | PASS if login page shown |
|
||||
| 19.9.3 | 401 redirect | Expire/remove auth token | Auto-redirect to login | PASS if login page shown |
|
||||
| 19.9.4 | Theme consistency | Check page styling | Light content area, teal sidebar, branded colors, readable text | PASS if theme consistent across all pages |
|
||||
|
||||
---
|
||||
|
||||
@@ -3655,36 +3820,38 @@ docker compose logs certctl-server 2>&1 | grep -v "^certctl-server" | grep -cv "
|
||||
|
||||
**What this validates:** Documentation accuracy against the running system. Claims in docs must match reality.
|
||||
|
||||
**Why it matters:** Inaccurate documentation destroys trust. If the README says "21 tables" but there are 19, or "78 MCP tools" but there are 76, evaluators question everything else too.
|
||||
**Why it matters:** Inaccurate documentation destroys trust. Claims in docs must match the running system. If the README says "X features" but the code doesn't have them, evaluators question everything else too.
|
||||
|
||||
| Test ID | Document | Verification | Pass/Fail Criteria |
|
||||
|---------|----------|-------------|-------------------|
|
||||
| 24.1.1 | `README.md` | Feature list matches actual capabilities. Screenshot paths resolve. Mermaid diagram says "21 tables". | PASS if all claims verified |
|
||||
| 24.1.1 | `README.md` | Feature list matches actual capabilities. Screenshot paths resolve. Mermaid diagram shows database schema tables. | PASS if all claims verified |
|
||||
| 24.1.2 | `docs/quickstart.md` | Every command in the quickstart works on a clean clone. | PASS if all commands succeed |
|
||||
| 24.1.3 | `docs/concepts.md` | Terminology matches API field names and UI labels. | PASS if terminology consistent |
|
||||
| 24.1.4 | `docs/architecture.md` | Component diagram matches `docker compose ps`. Says "21 tables", "78 MCP Tools", "900+ tests". | PASS if numbers match |
|
||||
| 24.1.5 | `docs/connectors.md` | All 5 issuer types and 5 target types documented. F5/IIS marked as stubs. | PASS if all documented |
|
||||
| 24.1.6 | `docs/features.md` | Endpoint count (93), MCP tools (78), table count (21), test count (900+) all accurate. | PASS if numbers match |
|
||||
| 24.1.7 | `docs/demo-guide.md` | Demo walkthrough works against fresh `docker compose up`. | PASS if all steps work |
|
||||
| 24.1.4 | `docs/architecture.md` | Component diagram matches `docker compose ps`. Key components and tables documented. | PASS if accurate |
|
||||
| 24.1.5 | `docs/connectors.md` | All issuer types and target types documented. F5/IIS marked as stubs. | PASS if all documented |
|
||||
| 24.1.6 | `docs/features.md` | Feature list complete and accurate. | PASS if accurate |
|
||||
| 24.1.7 | `docs/quickstart.md` | Quick start + demo walkthrough works against fresh `docker compose up`. | PASS if all steps work |
|
||||
| 24.1.8 | `docs/demo-advanced.md` | All parts executable against running stack. Network discovery section present. | PASS if all executable |
|
||||
| 24.1.9 | `docs/compliance.md` | Framework links resolve, mapping references real features. | PASS if links work |
|
||||
| 24.1.10 | `docs/compliance-soc2.md` | API endpoints cited actually exist in the router. | PASS if endpoints exist |
|
||||
| 24.1.11 | `docs/compliance-pci-dss.md` | Claims match implementation (audit trail, revocation, key management). | PASS if claims verified |
|
||||
| 24.1.12 | `docs/compliance-nist.md` | Key management claims match agent keygen behavior. | PASS if claims verified |
|
||||
| 24.1.13 | `docs/mcp.md` | Tool count = 78, domain count = 16, setup instructions work. | PASS if numbers match |
|
||||
| 24.1.14 | `api/openapi.yaml` | Operation count = 93, matches all routes in router.go. | PASS if count matches |
|
||||
| 24.1.13 | `docs/mcp.md` | Tool coverage documented, setup instructions work. | PASS if accurate |
|
||||
| 24.1.14 | `api/openapi.yaml` | OpenAPI spec matches all routes in router.go (check operation count). | PASS if count matches |
|
||||
|
||||
**Verification command for OpenAPI parity:**
|
||||
|
||||
```bash
|
||||
# Count OpenAPI operations
|
||||
grep -c "operationId:" api/openapi.yaml
|
||||
OPENAPI_OPS=$(grep -c "operationId:" api/openapi.yaml)
|
||||
# Count router registrations
|
||||
grep -c "r.Register\|r.mux.Handle" internal/api/router/router.go
|
||||
ROUTER_REGS=$(grep -c "r.Register\|r.mux.Handle" internal/api/router/router.go)
|
||||
echo "OpenAPI operations: $OPENAPI_OPS"
|
||||
echo "Router registrations: $ROUTER_REGS"
|
||||
```
|
||||
|
||||
**Expected:** Both return 93.
|
||||
**PASS if** both counts = 93. **FAIL** if mismatch.
|
||||
**Expected:** Both counts match.
|
||||
**PASS if** both counts are equal. **FAIL** if mismatch (indicates spec/code drift).
|
||||
|
||||
---
|
||||
|
||||
@@ -3741,21 +3908,42 @@ curl -s -H "$AUTH" "$SERVER/api/v1/network-scan-targets" | jq '{total, ids: [.it
|
||||
|
||||
---
|
||||
|
||||
**Test 25.1.4 — OpenAPI spec operations match router**
|
||||
**Test 25.1.4 — GUI delete on FK-restricted entities shows error, not silent failure**
|
||||
|
||||
```bash
|
||||
# Try deleting owner o-alice via API — she owns demo certificates
|
||||
CODE=$(curl -s -o /tmp/delete-resp.json -w "%{http_code}" -X DELETE -H "$AUTH" "$SERVER/api/v1/owners/o-alice")
|
||||
echo "DELETE owner with certs: HTTP $CODE"
|
||||
cat /tmp/delete-resp.json | jq .
|
||||
|
||||
# Try deleting issuer iss-local — certificates reference it
|
||||
CODE=$(curl -s -o /tmp/delete-resp.json -w "%{http_code}" -X DELETE -H "$AUTH" "$SERVER/api/v1/issuers/iss-local")
|
||||
echo "DELETE issuer with certs: HTTP $CODE"
|
||||
cat /tmp/delete-resp.json | jq .
|
||||
```
|
||||
|
||||
**What:** Verifies that deleting owners/issuers with assigned certificates returns 409 Conflict with a descriptive message.
|
||||
**Why:** This was a real bug — the backend returned 500 (generic "Failed to delete"), `fetchJSON` threw on the error, and TanStack Query's `onError` wasn't wired up. The user clicked OK on the confirm dialog and nothing visibly happened. Fixed by: (1) backend returns 409 with descriptive message for FK constraint violations, (2) `fetchJSON` handles 204 No Content for successful deletes, (3) frontend mutation `onError` surfaces the error.
|
||||
**Expected:** Both return HTTP 409 with descriptive conflict messages.
|
||||
**PASS if** both 409 with messages. **FAIL** if 500 (unhelpful error) or 204 (data integrity violation).
|
||||
|
||||
---
|
||||
|
||||
**Test 25.1.5 — OpenAPI spec operations match router**
|
||||
|
||||
```bash
|
||||
echo "OpenAPI operations: $(grep -c 'operationId:' api/openapi.yaml)"
|
||||
echo "Router registrations: $(grep -c 'r.Register\|r.mux.Handle' internal/api/router/router.go)"
|
||||
```
|
||||
|
||||
**What:** Counts operations in the OpenAPI spec and route registrations in the router.
|
||||
**Why:** The audit found the OpenAPI spec had 78 operations while the router had 93. This was fixed by adding 15 missing operations.
|
||||
**Expected:** Both = 93.
|
||||
**PASS if** both equal 93. **FAIL** if mismatch.
|
||||
**What:** Counts operations in the OpenAPI spec and route registrations in the router, verifying they match.
|
||||
**Why:** OpenAPI spec drift happens as endpoints are added or removed. Mismatches indicate the spec is out of date.
|
||||
**Expected:** Both counts equal.
|
||||
**PASS if** both counts match. **FAIL** if mismatch (indicates spec/code drift).
|
||||
|
||||
---
|
||||
|
||||
**Test 25.1.5 — Go service tests use strings.Contains, not errors.Is**
|
||||
**Test 25.1.6 — Go service tests use strings.Contains, not errors.Is**
|
||||
|
||||
```bash
|
||||
grep -rn "errors.Is.*errors.New\|errors.Is(.*err.*errors.New" internal/service/*_test.go | wc -l
|
||||
@@ -3768,9 +3956,248 @@ grep -rn "errors.Is.*errors.New\|errors.Is(.*err.*errors.New" internal/service/*
|
||||
|
||||
---
|
||||
|
||||
## Part 26: EST Server (RFC 7030)
|
||||
|
||||
**Scope:** Enrollment over Secure Transport — 4 endpoints under `/.well-known/est/` for device certificate enrollment. Tests cover CA cert distribution, certificate enrollment (PEM and base64-DER CSR formats), re-enrollment, CSR attributes, wire format compliance, and error handling.
|
||||
|
||||
**Prerequisites:** Server running with `CERTCTL_EST_ENABLED=true`, `CERTCTL_EST_ISSUER_ID=iss-local` (or a valid issuer). An ECDSA P-256 key pair and CSR for enrollment tests.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.1 — GET /.well-known/est/cacerts returns PKCS#7 CA chain**
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer $API_KEY" \
|
||||
http://localhost:8443/.well-known/est/cacerts
|
||||
```
|
||||
|
||||
**Expected:** HTTP 200, `Content-Type: application/pkcs7-mime`, `Content-Transfer-Encoding: base64`. Body is base64-encoded degenerate PKCS#7 SignedData containing the CA certificate chain.
|
||||
**PASS if** status = 200, correct content type, non-empty body.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.2 — GET /cacerts method enforcement**
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w "%{http_code}" -X POST \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
http://localhost:8443/.well-known/est/cacerts
|
||||
```
|
||||
|
||||
**Expected:** HTTP 405 Method Not Allowed.
|
||||
**PASS if** status = 405.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.3 — POST /.well-known/est/simpleenroll with PEM CSR**
|
||||
|
||||
Generate a test CSR and submit as PEM:
|
||||
|
||||
```bash
|
||||
# Generate ECDSA P-256 key and CSR
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out /tmp/est-test.key
|
||||
openssl req -new -key /tmp/est-test.key -out /tmp/est-test.csr \
|
||||
-subj "/CN=est-test.example.com" \
|
||||
-addext "subjectAltName=DNS:est-test.example.com"
|
||||
|
||||
# Submit PEM CSR
|
||||
curl -s -w "\n%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/pkcs10" \
|
||||
--data-binary @/tmp/est-test.csr \
|
||||
http://localhost:8443/.well-known/est/simpleenroll
|
||||
```
|
||||
|
||||
**Expected:** HTTP 200, `Content-Type: application/pkcs7-mime`, `Content-Transfer-Encoding: base64`. Body contains base64-encoded PKCS#7 with the signed certificate.
|
||||
**PASS if** status = 200, response decodes to valid PKCS#7.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.4 — POST /simpleenroll with base64-encoded DER CSR**
|
||||
|
||||
```bash
|
||||
# Convert PEM CSR to base64-encoded DER (EST wire format)
|
||||
openssl req -in /tmp/est-test.csr -outform DER | base64 > /tmp/est-test-b64der.csr
|
||||
|
||||
curl -s -w "\n%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/pkcs10" \
|
||||
--data-binary @/tmp/est-test-b64der.csr \
|
||||
http://localhost:8443/.well-known/est/simpleenroll
|
||||
```
|
||||
|
||||
**Expected:** HTTP 200. Server auto-detects base64-encoded DER and converts to PEM internally.
|
||||
**PASS if** status = 200.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.5 — POST /simpleenroll with empty body**
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/pkcs10" \
|
||||
-X POST -d "" \
|
||||
http://localhost:8443/.well-known/est/simpleenroll
|
||||
```
|
||||
|
||||
**Expected:** HTTP 400 Bad Request.
|
||||
**PASS if** status = 400.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.6 — POST /simpleenroll with invalid CSR**
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/pkcs10" \
|
||||
-X POST -d "not-a-valid-csr-at-all" \
|
||||
http://localhost:8443/.well-known/est/simpleenroll
|
||||
```
|
||||
|
||||
**Expected:** HTTP 400 Bad Request.
|
||||
**PASS if** status = 400.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.7 — POST /simpleenroll with CSR missing Common Name**
|
||||
|
||||
```bash
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out /tmp/est-nocn.key
|
||||
openssl req -new -key /tmp/est-nocn.key -out /tmp/est-nocn.csr -subj "/"
|
||||
|
||||
curl -s -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/pkcs10" \
|
||||
--data-binary @/tmp/est-nocn.csr \
|
||||
http://localhost:8443/.well-known/est/simpleenroll
|
||||
```
|
||||
|
||||
**Expected:** HTTP 500 (service returns error for missing CN). Error message should reference "Common Name".
|
||||
**PASS if** status != 200.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.8 — POST /simpleenroll method enforcement (GET not allowed)**
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
http://localhost:8443/.well-known/est/simpleenroll
|
||||
```
|
||||
|
||||
**Expected:** HTTP 405 Method Not Allowed.
|
||||
**PASS if** status = 405.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.9 — POST /.well-known/est/simplereenroll (re-enrollment)**
|
||||
|
||||
```bash
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out /tmp/est-renew.key
|
||||
openssl req -new -key /tmp/est-renew.key -out /tmp/est-renew.csr \
|
||||
-subj "/CN=renew-est.example.com" \
|
||||
-addext "subjectAltName=DNS:renew-est.example.com"
|
||||
|
||||
curl -s -w "\n%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/pkcs10" \
|
||||
--data-binary @/tmp/est-renew.csr \
|
||||
http://localhost:8443/.well-known/est/simplereenroll
|
||||
```
|
||||
|
||||
**Expected:** HTTP 200. Functionally identical to simpleenroll per RFC 7030 Section 4.2.2.
|
||||
**PASS if** status = 200, valid PKCS#7 response.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.10 — GET /simplereenroll method enforcement**
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
http://localhost:8443/.well-known/est/simplereenroll
|
||||
```
|
||||
|
||||
**Expected:** HTTP 405 Method Not Allowed.
|
||||
**PASS if** status = 405.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.11 — GET /.well-known/est/csrattrs returns 204 (no required attrs)**
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
http://localhost:8443/.well-known/est/csrattrs
|
||||
```
|
||||
|
||||
**Expected:** HTTP 204 No Content (default implementation requires no specific CSR attributes).
|
||||
**PASS if** status = 204.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.12 — POST /csrattrs method enforcement**
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-X POST http://localhost:8443/.well-known/est/csrattrs
|
||||
```
|
||||
|
||||
**Expected:** HTTP 405 Method Not Allowed.
|
||||
**PASS if** status = 405.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.13 — EST enrollment creates audit event**
|
||||
|
||||
After a successful simpleenroll request (Test 26.3), query the audit trail:
|
||||
|
||||
```bash
|
||||
curl -s -H "Authorization: Bearer $API_KEY" \
|
||||
"http://localhost:8443/api/v1/audit?page=1&per_page=10" | \
|
||||
jq '.data[] | select(.action == "est_simple_enroll")'
|
||||
```
|
||||
|
||||
**Expected:** At least one audit event with `action: "est_simple_enroll"`, `protocol: "EST"` in details, and the enrolled CN in the details.
|
||||
**PASS if** audit event found with correct action and details.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.14 — EST disabled returns 404**
|
||||
|
||||
With `CERTCTL_EST_ENABLED=false` (default), EST endpoints should not be registered:
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w "%{http_code}" http://localhost:8443/.well-known/est/cacerts
|
||||
```
|
||||
|
||||
**Expected:** HTTP 404 Not Found (endpoints not registered when EST is disabled).
|
||||
**PASS if** status = 404.
|
||||
|
||||
---
|
||||
|
||||
**Test 26.15 — EST with profile binding**
|
||||
|
||||
With `CERTCTL_EST_PROFILE_ID=profile-wifi-client`, verify that audit events include the profile_id in their details:
|
||||
|
||||
```bash
|
||||
# After enrollment with profile binding, check audit
|
||||
curl -s -H "Authorization: Bearer $API_KEY" \
|
||||
"http://localhost:8443/api/v1/audit?page=1&per_page=5" | \
|
||||
jq '.data[0].details.profile_id'
|
||||
```
|
||||
|
||||
**Expected:** Profile ID appears in audit event details when configured.
|
||||
**PASS if** `profile_id` present in audit details.
|
||||
|
||||
---
|
||||
|
||||
## Release Sign-Off
|
||||
|
||||
All 25 parts must pass before tagging v2.0.0.
|
||||
All 26 parts must pass before tagging v2.0.1.
|
||||
|
||||
| Section | Pass? | Tester | Date | Notes |
|
||||
|---------|-------|--------|------|-------|
|
||||
@@ -3799,6 +4226,7 @@ All 25 parts must pass before tagging v2.0.0.
|
||||
| Part 23: Structured Logging | ☐ | | | |
|
||||
| Part 24: Documentation Verification | ☐ | | | |
|
||||
| Part 25: Regression Tests | ☐ | | | |
|
||||
| Part 26: EST Server (RFC 7030) | ☐ | | | |
|
||||
|
||||
**Automated tests (900+) must also be green.** CI passing is necessary but not sufficient — this manual QA catches integration issues that isolated unit tests miss.
|
||||
**Automated tests must also be green.** CI passing is necessary but not sufficient — this manual QA catches integration issues that isolated unit tests miss.
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# Why certctl?
|
||||
|
||||
Certificate management is broken at every scale between "one domain on Let's Encrypt" and "Fortune 500 budget for Venafi."
|
||||
|
||||
If you run a personal blog, Certbot works fine. If your company spends $200K/year on Keyfactor, you're covered. But if you're an ops engineer managing 20-500 certificates across NGINX, Apache, HAProxy, and maybe a private CA — the tools available today either don't do enough or cost too much.
|
||||
|
||||
certctl fills that gap.
|
||||
|
||||
## The Problem
|
||||
|
||||
The CA/Browser Forum passed [Ballot SC-081v3](https://cabforum.org/2025/04/11/ballot-sc081v3-introduce-schedule-of-reducing-validity-and-data-reuse-periods/) in April 2025, mandating a phased reduction in TLS certificate lifetimes: 200 days as of March 2026, 100 days by March 2027, and 47 days by March 2029. That means every organization needs automated certificate renewal — not eventually, but now.
|
||||
|
||||
The existing options for automation are:
|
||||
|
||||
- **ACME clients** (Certbot, Lego, CertWarden): Handle issuance and renewal for ACME-compatible CAs, but don't manage deployment to target servers, don't provide inventory visibility, don't support non-ACME CAs, and don't offer audit trails or policy enforcement.
|
||||
- **Kubernetes-native** (cert-manager): Works well inside Kubernetes, but if your infrastructure includes bare-metal servers, VMs, or network appliances alongside Kubernetes, you need a separate solution for everything cert-manager can't reach.
|
||||
- **Commercial SaaS** (CertKit, Sectigo CLM): Handle more of the lifecycle but are proprietary, cloud-dependent, and priced per certificate — costs scale linearly with your infrastructure.
|
||||
- **Enterprise platforms** (Venafi, Keyfactor, AppViewX): Comprehensive but start at $75K/year and require dedicated teams to operate.
|
||||
|
||||
## What certctl Does Differently
|
||||
|
||||
certctl is a self-hosted certificate lifecycle platform. It handles issuance, renewal, deployment, revocation, discovery, and monitoring — with three design decisions that no other tool at any price point combines:
|
||||
|
||||
### 1. Private Keys Never Leave Your Infrastructure
|
||||
|
||||
certctl agents generate private keys locally using ECDSA P-256. The agent creates a CSR and submits it to the control plane. The signed certificate comes back. The private key stays on the agent's filesystem with 0600 permissions.
|
||||
|
||||
This isn't a premium feature — it's the default behavior in the free tier. Most competitors either generate keys server-side (creating a single point of compromise) or gate key isolation behind paid tiers.
|
||||
|
||||
### 2. CA-Agnostic Issuer Architecture
|
||||
|
||||
certctl works with any certificate authority, not just ACME providers:
|
||||
|
||||
- **ACME** (Let's Encrypt, ZeroSSL, Google Trust Services, Buypass) — HTTP-01 and DNS-01 challenges, DNS-PERSIST-01 for zero-touch renewals, External Account Binding
|
||||
- **step-ca** (Smallstep) — native /sign API with JWK provisioner authentication
|
||||
- **Local CA** — self-signed or sub-CA mode (chain to your enterprise root CA, e.g. ADCS)
|
||||
- **OpenSSL / Custom CA** — delegate signing to any shell script with configurable timeout
|
||||
- **EST enrollment** (RFC 7030) — device certificate enrollment for WiFi/802.1X, MDM, and IoT
|
||||
|
||||
Every issuer connector implements the same interface. Switching CAs or running multiple CAs in parallel requires zero code changes — just configuration.
|
||||
|
||||
### 3. Post-Deployment Verification (coming in v2.0.6)
|
||||
|
||||
Every other tool in this space stops at "the deployment command succeeded." certctl is adding a step nobody else has: after deploying a certificate to a target, the agent connects back to the target's TLS endpoint and verifies the served certificate matches what was deployed, using SHA-256 fingerprint comparison.
|
||||
|
||||
A reload command can exit 0 while the certificate doesn't take effect — wrong virtual host, stale cache, config that validates but doesn't apply. certctl will catch this.
|
||||
|
||||
## How certctl Compares
|
||||
|
||||
### vs. CertKit
|
||||
|
||||
Closest competitor architecturally — agent-based, private key isolation (Keystore), multi-platform. certctl leads on issuer coverage (ACME + step-ca + Local CA + OpenSSL + EST vs. ACME-only), PKI compliance (CRL, OCSP, RFC 5280 revocation, immutable audit trail — all missing from CertKit today), policy engine (5 rule types vs. none), and network discovery (CIDR TLS scanning vs. none). certctl is source-available (BSL 1.1 → Apache 2.0) with no cert limit; CertKit is proprietary SaaS with a 3-cert free tier. Where CertKit leads: more deployment targets today (adds LiteSpeed, IIS, auto-detection), Windows support, Kubernetes, and polished SaaS onboarding.
|
||||
|
||||
### vs. KeyTalk
|
||||
|
||||
Commercial (proprietary) PKI platform from a Dutch company — on-prem appliance, cloud, or managed service. Broader cert type coverage (TLS, S/MIME, device auth, VPN) and DigiCert + SCEP integrations. No public documentation on policy engine, API surface, or audit capabilities. No free tier, no public pricing. certctl trades breadth of cert types for full transparency — source-available, public API spec, free community edition with no limits.
|
||||
|
||||
### vs. Enterprise Platforms (Venafi, Keyfactor)
|
||||
|
||||
Comprehensive solutions with decades of features — at $75K-$250K+/yr. certctl targets organizations that need 80% of those capabilities at 1% of the cost. The trade-off: no SSO/RBAC yet (coming in certctl Pro), no F5/IIS target connectors yet, no SLA-backed support.
|
||||
|
||||
## Getting Started
|
||||
|
||||
```bash
|
||||
# Clone and start with Docker Compose (includes demo data)
|
||||
git clone https://github.com/shankar0123/certctl.git
|
||||
cd certctl/deploy
|
||||
docker compose up -d
|
||||
|
||||
# Open the dashboard
|
||||
open http://localhost:8443
|
||||
```
|
||||
|
||||
The demo seeds 15 certificates, 5 agents, 5 deployment targets, discovery data, network scan targets, and pending approval jobs so you can explore every feature immediately.
|
||||
|
||||
See the [Quickstart Guide](quickstart.md) for a full walkthrough.
|
||||
|
||||
## License
|
||||
|
||||
certctl is licensed under the [Business Source License 1.1](../LICENSE). The licensed work is free to use for any purpose other than offering a competing managed service. The license converts to Apache 2.0 on March 1, 2033.
|
||||
|
||||
The source is available, auditable, and self-hostable. You own your data, your keys, and your deployment.
|
||||
@@ -0,0 +1,404 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
)
|
||||
|
||||
// ESTService defines the service interface for EST enrollment operations.
|
||||
// EST (RFC 7030) is a protocol for certificate enrollment over HTTPS.
|
||||
type ESTService interface {
|
||||
// GetCACerts returns the PEM-encoded CA certificate chain for the EST issuer.
|
||||
GetCACerts(ctx context.Context) (string, error)
|
||||
|
||||
// SimpleEnroll processes a PKCS#10 CSR and returns a signed certificate.
|
||||
SimpleEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error)
|
||||
|
||||
// SimpleReEnroll processes a re-enrollment CSR (same as enroll for our purposes).
|
||||
SimpleReEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error)
|
||||
|
||||
// GetCSRAttrs returns the CSR attributes the server wants clients to include.
|
||||
GetCSRAttrs(ctx context.Context) ([]byte, error)
|
||||
}
|
||||
|
||||
// ESTHandler handles HTTP requests for the EST protocol (RFC 7030).
|
||||
//
|
||||
// EST endpoints are served under /.well-known/est/ per the RFC.
|
||||
// Wire format: base64-encoded DER (PKCS#7 for certs, PKCS#10 for CSRs).
|
||||
//
|
||||
// Supported operations:
|
||||
// - GET /.well-known/est/cacerts — CA certificate distribution
|
||||
// - POST /.well-known/est/simpleenroll — initial enrollment
|
||||
// - POST /.well-known/est/simplereenroll — re-enrollment
|
||||
// - GET /.well-known/est/csrattrs — CSR attributes
|
||||
type ESTHandler struct {
|
||||
svc ESTService
|
||||
}
|
||||
|
||||
// NewESTHandler creates a new ESTHandler.
|
||||
func NewESTHandler(svc ESTService) ESTHandler {
|
||||
return ESTHandler{svc: svc}
|
||||
}
|
||||
|
||||
// CACerts handles GET /.well-known/est/cacerts
|
||||
// Returns the CA certificate chain as base64-encoded PKCS#7 (certs-only).
|
||||
// Per RFC 7030 Section 4.1, this is a "certs-only" CMC Simple PKI Response.
|
||||
// For simplicity and broad client compatibility, we return base64-encoded DER certificates.
|
||||
func (h ESTHandler) CACerts(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
caCertPEM, err := h.svc.GetCACerts(r.Context())
|
||||
if err != nil {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, fmt.Sprintf("Failed to get CA certificates: %v", err), requestID)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse PEM to DER for PKCS#7 encoding
|
||||
derCerts, err := pemToDERChain(caCertPEM)
|
||||
if err != nil {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to encode CA certificates", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
// Build a simple PKCS#7 SignedData (certs-only, degenerate) structure
|
||||
pkcs7Data, err := buildCertsOnlyPKCS7(derCerts)
|
||||
if err != nil {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to build PKCS#7 response", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
// RFC 7030 Section 4.1.3: response is base64-encoded application/pkcs7-mime
|
||||
w.Header().Set("Content-Type", "application/pkcs7-mime; smime-type=certs-only")
|
||||
w.Header().Set("Content-Transfer-Encoding", "base64")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
encoded := base64.StdEncoding.EncodeToString(pkcs7Data)
|
||||
// Write base64 with line breaks at 76 chars per RFC 2045
|
||||
for i := 0; i < len(encoded); i += 76 {
|
||||
end := i + 76
|
||||
if end > len(encoded) {
|
||||
end = len(encoded)
|
||||
}
|
||||
w.Write([]byte(encoded[i:end]))
|
||||
w.Write([]byte("\r\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// SimpleEnroll handles POST /.well-known/est/simpleenroll
|
||||
// Accepts a base64-encoded PKCS#10 CSR and returns a base64-encoded PKCS#7 certificate.
|
||||
func (h ESTHandler) SimpleEnroll(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
csrPEM, err := h.readCSRFromRequest(r)
|
||||
if err != nil {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, fmt.Sprintf("Invalid CSR: %v", err), requestID)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.svc.SimpleEnroll(r.Context(), csrPEM)
|
||||
if err != nil {
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, fmt.Sprintf("Enrollment failed: %v", err), requestID)
|
||||
return
|
||||
}
|
||||
|
||||
h.writeCertResponse(w, result)
|
||||
}
|
||||
|
||||
// SimpleReEnroll handles POST /.well-known/est/simplereenroll
|
||||
// Same as SimpleEnroll but for re-enrollment (certificate renewal).
|
||||
func (h ESTHandler) SimpleReEnroll(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
csrPEM, err := h.readCSRFromRequest(r)
|
||||
if err != nil {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, fmt.Sprintf("Invalid CSR: %v", err), requestID)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.svc.SimpleReEnroll(r.Context(), csrPEM)
|
||||
if err != nil {
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, fmt.Sprintf("Re-enrollment failed: %v", err), requestID)
|
||||
return
|
||||
}
|
||||
|
||||
h.writeCertResponse(w, result)
|
||||
}
|
||||
|
||||
// CSRAttrs handles GET /.well-known/est/csrattrs
|
||||
// Returns the CSR attributes the server wants the client to include in enrollment requests.
|
||||
func (h ESTHandler) CSRAttrs(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
attrs, err := h.svc.GetCSRAttrs(r.Context())
|
||||
if err != nil {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, fmt.Sprintf("Failed to get CSR attributes: %v", err), requestID)
|
||||
return
|
||||
}
|
||||
|
||||
if len(attrs) == 0 {
|
||||
// No specific attributes required — return 204
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/csrattrs")
|
||||
w.Header().Set("Content-Transfer-Encoding", "base64")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(base64.StdEncoding.EncodeToString(attrs)))
|
||||
}
|
||||
|
||||
// readCSRFromRequest reads and decodes the CSR from an EST enrollment request.
|
||||
// EST sends CSRs as base64-encoded PKCS#10 DER with Content-Type application/pkcs10.
|
||||
func (h ESTHandler) readCSRFromRequest(r *http.Request) (string, error) {
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 1MB limit
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read request body: %w", err)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if len(body) == 0 {
|
||||
return "", fmt.Errorf("empty request body")
|
||||
}
|
||||
|
||||
// Check if it's already PEM-encoded (some clients send PEM directly)
|
||||
bodyStr := strings.TrimSpace(string(body))
|
||||
if strings.HasPrefix(bodyStr, "-----BEGIN CERTIFICATE REQUEST-----") {
|
||||
// Validate it parses
|
||||
block, _ := pem.Decode([]byte(bodyStr))
|
||||
if block == nil {
|
||||
return "", fmt.Errorf("invalid PEM-encoded CSR")
|
||||
}
|
||||
if _, err := x509.ParseCertificateRequest(block.Bytes); err != nil {
|
||||
return "", fmt.Errorf("invalid CSR: %w", err)
|
||||
}
|
||||
return bodyStr, nil
|
||||
}
|
||||
|
||||
// EST standard: base64-encoded DER PKCS#10
|
||||
derBytes, err := base64.StdEncoding.DecodeString(bodyStr)
|
||||
if err != nil {
|
||||
// Try with padding/whitespace stripped
|
||||
cleaned := strings.Map(func(r rune) rune {
|
||||
if r == '\r' || r == '\n' || r == ' ' || r == '\t' {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, bodyStr)
|
||||
derBytes, err = base64.StdEncoding.DecodeString(cleaned)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to decode base64 CSR: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate it's a valid PKCS#10 CSR
|
||||
if _, err := x509.ParseCertificateRequest(derBytes); err != nil {
|
||||
return "", fmt.Errorf("invalid PKCS#10 CSR: %w", err)
|
||||
}
|
||||
|
||||
// Convert DER to PEM for internal use (certctl services expect PEM)
|
||||
csrPEM := pem.EncodeToMemory(&pem.Block{
|
||||
Type: "CERTIFICATE REQUEST",
|
||||
Bytes: derBytes,
|
||||
})
|
||||
return string(csrPEM), nil
|
||||
}
|
||||
|
||||
// writeCertResponse writes an EST enrollment response as base64-encoded PKCS#7.
|
||||
func (h ESTHandler) writeCertResponse(w http.ResponseWriter, result *domain.ESTEnrollResult) {
|
||||
// Parse cert and chain PEM to DER
|
||||
var derCerts [][]byte
|
||||
|
||||
// Add the issued certificate
|
||||
certDER, err := pemToDERChain(result.CertPEM)
|
||||
if err != nil || len(certDER) == 0 {
|
||||
http.Error(w, "Failed to encode certificate", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
derCerts = append(derCerts, certDER...)
|
||||
|
||||
// Add the CA chain if present
|
||||
if result.ChainPEM != "" {
|
||||
chainDER, err := pemToDERChain(result.ChainPEM)
|
||||
if err == nil {
|
||||
derCerts = append(derCerts, chainDER...)
|
||||
}
|
||||
}
|
||||
|
||||
// Build PKCS#7 certs-only
|
||||
pkcs7Data, err := buildCertsOnlyPKCS7(derCerts)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to build PKCS#7 response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/pkcs7-mime; smime-type=certs-only")
|
||||
w.Header().Set("Content-Transfer-Encoding", "base64")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
encoded := base64.StdEncoding.EncodeToString(pkcs7Data)
|
||||
for i := 0; i < len(encoded); i += 76 {
|
||||
end := i + 76
|
||||
if end > len(encoded) {
|
||||
end = len(encoded)
|
||||
}
|
||||
w.Write([]byte(encoded[i:end]))
|
||||
w.Write([]byte("\r\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// pemToDERChain converts PEM-encoded certificates to a slice of DER-encoded certificates.
|
||||
func pemToDERChain(pemData string) ([][]byte, error) {
|
||||
var derCerts [][]byte
|
||||
rest := []byte(pemData)
|
||||
for {
|
||||
var block *pem.Block
|
||||
block, rest = pem.Decode(rest)
|
||||
if block == nil {
|
||||
break
|
||||
}
|
||||
if block.Type == "CERTIFICATE" {
|
||||
derCerts = append(derCerts, block.Bytes)
|
||||
}
|
||||
}
|
||||
if len(derCerts) == 0 {
|
||||
return nil, fmt.Errorf("no certificates found in PEM data")
|
||||
}
|
||||
return derCerts, nil
|
||||
}
|
||||
|
||||
// buildCertsOnlyPKCS7 creates a degenerate PKCS#7 SignedData structure containing only certificates.
|
||||
// This is the "certs-only" format specified in RFC 7030 Section 4.1.3 for /cacerts responses
|
||||
// and enrollment responses.
|
||||
//
|
||||
// ASN.1 structure (simplified):
|
||||
//
|
||||
// ContentInfo {
|
||||
// contentType: signedData (1.2.840.113549.1.7.2)
|
||||
// content: SignedData {
|
||||
// version: 1
|
||||
// digestAlgorithms: {} (empty)
|
||||
// encapContentInfo: { contentType: data (1.2.840.113549.1.7.1) }
|
||||
// certificates: [cert1, cert2, ...]
|
||||
// signerInfos: {} (empty)
|
||||
// }
|
||||
// }
|
||||
func buildCertsOnlyPKCS7(derCerts [][]byte) ([]byte, error) {
|
||||
// We build the ASN.1 manually to avoid pulling in a PKCS#7 library.
|
||||
// This is a well-defined, static structure — no signing needed.
|
||||
|
||||
// OID for signedData: 1.2.840.113549.1.7.2
|
||||
oidSignedData := []byte{0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02}
|
||||
// OID for data: 1.2.840.113549.1.7.1
|
||||
oidData := []byte{0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01}
|
||||
|
||||
// Build certificates [0] IMPLICIT SET OF Certificate
|
||||
var certsContent []byte
|
||||
for _, cert := range derCerts {
|
||||
certsContent = append(certsContent, cert...)
|
||||
}
|
||||
certsField := asn1WrapImplicit(0, certsContent)
|
||||
|
||||
// Build encapContentInfo: SEQUENCE { OID data }
|
||||
encapContentInfo := asn1WrapSequence(oidData)
|
||||
|
||||
// Build digestAlgorithms: SET {} (empty)
|
||||
digestAlgorithms := asn1WrapSet(nil)
|
||||
|
||||
// Build signerInfos: SET {} (empty)
|
||||
signerInfos := asn1WrapSet(nil)
|
||||
|
||||
// Version: INTEGER 1
|
||||
version := []byte{0x02, 0x01, 0x01}
|
||||
|
||||
// Build SignedData SEQUENCE
|
||||
var signedDataContent []byte
|
||||
signedDataContent = append(signedDataContent, version...)
|
||||
signedDataContent = append(signedDataContent, digestAlgorithms...)
|
||||
signedDataContent = append(signedDataContent, encapContentInfo...)
|
||||
signedDataContent = append(signedDataContent, certsField...)
|
||||
signedDataContent = append(signedDataContent, signerInfos...)
|
||||
signedData := asn1WrapSequence(signedDataContent)
|
||||
|
||||
// Wrap in [0] EXPLICIT for ContentInfo.content
|
||||
contentField := asn1WrapExplicit(0, signedData)
|
||||
|
||||
// Build ContentInfo SEQUENCE
|
||||
var contentInfoContent []byte
|
||||
contentInfoContent = append(contentInfoContent, oidSignedData...)
|
||||
contentInfoContent = append(contentInfoContent, contentField...)
|
||||
contentInfo := asn1WrapSequence(contentInfoContent)
|
||||
|
||||
return contentInfo, nil
|
||||
}
|
||||
|
||||
// asn1WrapSequence wraps content in an ASN.1 SEQUENCE tag (0x30).
|
||||
func asn1WrapSequence(content []byte) []byte {
|
||||
return asn1Wrap(0x30, content)
|
||||
}
|
||||
|
||||
// asn1WrapSet wraps content in an ASN.1 SET tag (0x31).
|
||||
func asn1WrapSet(content []byte) []byte {
|
||||
return asn1Wrap(0x31, content)
|
||||
}
|
||||
|
||||
// asn1WrapExplicit wraps content in an ASN.1 context-specific EXPLICIT tag.
|
||||
func asn1WrapExplicit(tag int, content []byte) []byte {
|
||||
return asn1Wrap(byte(0xa0|tag), content)
|
||||
}
|
||||
|
||||
// asn1WrapImplicit wraps content in an ASN.1 context-specific IMPLICIT CONSTRUCTED tag.
|
||||
func asn1WrapImplicit(tag int, content []byte) []byte {
|
||||
return asn1Wrap(byte(0xa0|tag), content)
|
||||
}
|
||||
|
||||
// asn1Wrap wraps content with an ASN.1 tag and length.
|
||||
func asn1Wrap(tag byte, content []byte) []byte {
|
||||
length := len(content)
|
||||
var result []byte
|
||||
result = append(result, tag)
|
||||
result = append(result, asn1EncodeLength(length)...)
|
||||
result = append(result, content...)
|
||||
return result
|
||||
}
|
||||
|
||||
// asn1EncodeLength encodes a length in ASN.1 DER format.
|
||||
func asn1EncodeLength(length int) []byte {
|
||||
if length < 0x80 {
|
||||
return []byte{byte(length)}
|
||||
}
|
||||
// Long form
|
||||
var lengthBytes []byte
|
||||
l := length
|
||||
for l > 0 {
|
||||
lengthBytes = append([]byte{byte(l & 0xff)}, lengthBytes...)
|
||||
l >>= 8
|
||||
}
|
||||
return append([]byte{byte(0x80 | len(lengthBytes))}, lengthBytes...)
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
)
|
||||
|
||||
// mockESTService implements ESTService for testing.
|
||||
type mockESTService struct {
|
||||
CACertPEM string
|
||||
CACertErr error
|
||||
EnrollResult *domain.ESTEnrollResult
|
||||
EnrollErr error
|
||||
CSRAttrs []byte
|
||||
CSRAttrsErr error
|
||||
}
|
||||
|
||||
func (m *mockESTService) GetCACerts(ctx context.Context) (string, error) {
|
||||
return m.CACertPEM, m.CACertErr
|
||||
}
|
||||
|
||||
func (m *mockESTService) SimpleEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error) {
|
||||
return m.EnrollResult, m.EnrollErr
|
||||
}
|
||||
|
||||
func (m *mockESTService) SimpleReEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error) {
|
||||
return m.EnrollResult, m.EnrollErr
|
||||
}
|
||||
|
||||
func (m *mockESTService) GetCSRAttrs(ctx context.Context) ([]byte, error) {
|
||||
return m.CSRAttrs, m.CSRAttrsErr
|
||||
}
|
||||
|
||||
// generateTestCSRPEM creates a valid ECDSA P-256 CSR for testing.
|
||||
func generateTestCSRPEM(t *testing.T) string {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate key: %v", err)
|
||||
}
|
||||
template := &x509.CertificateRequest{
|
||||
Subject: pkix.Name{CommonName: "test.example.com"},
|
||||
DNSNames: []string{"test.example.com", "www.example.com"},
|
||||
}
|
||||
csrDER, err := x509.CreateCertificateRequest(rand.Reader, template, key)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create CSR: %v", err)
|
||||
}
|
||||
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER}))
|
||||
}
|
||||
|
||||
// generateTestCSRBase64DER creates a valid base64-encoded DER CSR for EST wire format.
|
||||
func generateTestCSRBase64DER(t *testing.T) string {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate key: %v", err)
|
||||
}
|
||||
template := &x509.CertificateRequest{
|
||||
Subject: pkix.Name{CommonName: "test.example.com"},
|
||||
DNSNames: []string{"test.example.com"},
|
||||
}
|
||||
csrDER, err := x509.CreateCertificateRequest(rand.Reader, template, key)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create CSR: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(csrDER)
|
||||
}
|
||||
|
||||
// generateTestCertPEM creates a real self-signed certificate PEM for testing.
|
||||
func generateTestCertPEM(t *testing.T) string {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate key: %v", err)
|
||||
}
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "Test CA"},
|
||||
NotBefore: time.Now().Add(-1 * time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
IsCA: true,
|
||||
BasicConstraintsValid: true,
|
||||
}
|
||||
certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create certificate: %v", err)
|
||||
}
|
||||
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}))
|
||||
}
|
||||
|
||||
func TestESTCACerts_Success(t *testing.T) {
|
||||
certPEM := generateTestCertPEM(t)
|
||||
svc := &mockESTService{
|
||||
CACertPEM: certPEM,
|
||||
}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/cacerts", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.CACerts(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
ct := w.Header().Get("Content-Type")
|
||||
if !strings.Contains(ct, "application/pkcs7-mime") {
|
||||
t.Errorf("expected application/pkcs7-mime content type, got %s", ct)
|
||||
}
|
||||
cte := w.Header().Get("Content-Transfer-Encoding")
|
||||
if cte != "base64" {
|
||||
t.Errorf("expected base64 content-transfer-encoding, got %s", cte)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTCACerts_MethodNotAllowed(t *testing.T) {
|
||||
svc := &mockESTService{}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/est/cacerts", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.CACerts(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTCACerts_ServiceError(t *testing.T) {
|
||||
svc := &mockESTService{
|
||||
CACertErr: errors.New("issuer unavailable"),
|
||||
}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/cacerts", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.CACerts(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTSimpleEnroll_Success_PEM(t *testing.T) {
|
||||
csrPEM := generateTestCSRPEM(t)
|
||||
certPEM := generateTestCertPEM(t)
|
||||
svc := &mockESTService{
|
||||
EnrollResult: &domain.ESTEnrollResult{
|
||||
CertPEM: certPEM,
|
||||
ChainPEM: certPEM,
|
||||
},
|
||||
}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/est/simpleenroll", strings.NewReader(csrPEM))
|
||||
req.Header.Set("Content-Type", "application/pkcs10")
|
||||
w := httptest.NewRecorder()
|
||||
h.SimpleEnroll(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
ct := w.Header().Get("Content-Type")
|
||||
if !strings.Contains(ct, "application/pkcs7-mime") {
|
||||
t.Errorf("expected application/pkcs7-mime, got %s", ct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTSimpleEnroll_Success_Base64DER(t *testing.T) {
|
||||
csrB64 := generateTestCSRBase64DER(t)
|
||||
certPEM := generateTestCertPEM(t)
|
||||
svc := &mockESTService{
|
||||
EnrollResult: &domain.ESTEnrollResult{
|
||||
CertPEM: certPEM,
|
||||
ChainPEM: "",
|
||||
},
|
||||
}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/est/simpleenroll", strings.NewReader(csrB64))
|
||||
req.Header.Set("Content-Type", "application/pkcs10")
|
||||
w := httptest.NewRecorder()
|
||||
h.SimpleEnroll(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTSimpleEnroll_MethodNotAllowed(t *testing.T) {
|
||||
svc := &mockESTService{}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/simpleenroll", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.SimpleEnroll(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTSimpleEnroll_EmptyBody(t *testing.T) {
|
||||
svc := &mockESTService{}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/est/simpleenroll", strings.NewReader(""))
|
||||
w := httptest.NewRecorder()
|
||||
h.SimpleEnroll(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTSimpleEnroll_InvalidCSR(t *testing.T) {
|
||||
svc := &mockESTService{}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/est/simpleenroll", strings.NewReader("not-a-valid-csr"))
|
||||
w := httptest.NewRecorder()
|
||||
h.SimpleEnroll(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTSimpleEnroll_ServiceError(t *testing.T) {
|
||||
csrPEM := generateTestCSRPEM(t)
|
||||
svc := &mockESTService{
|
||||
EnrollErr: errors.New("issuance failed"),
|
||||
}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/est/simpleenroll", strings.NewReader(csrPEM))
|
||||
w := httptest.NewRecorder()
|
||||
h.SimpleEnroll(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTSimpleReEnroll_Success(t *testing.T) {
|
||||
csrPEM := generateTestCSRPEM(t)
|
||||
certPEM := generateTestCertPEM(t)
|
||||
svc := &mockESTService{
|
||||
EnrollResult: &domain.ESTEnrollResult{
|
||||
CertPEM: certPEM,
|
||||
ChainPEM: certPEM,
|
||||
},
|
||||
}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/est/simplereenroll", strings.NewReader(csrPEM))
|
||||
w := httptest.NewRecorder()
|
||||
h.SimpleReEnroll(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTSimpleReEnroll_MethodNotAllowed(t *testing.T) {
|
||||
svc := &mockESTService{}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/simplereenroll", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.SimpleReEnroll(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTCSRAttrs_NoContent(t *testing.T) {
|
||||
svc := &mockESTService{
|
||||
CSRAttrs: nil,
|
||||
}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/csrattrs", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.CSRAttrs(w, req)
|
||||
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Errorf("expected 204, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTCSRAttrs_WithData(t *testing.T) {
|
||||
svc := &mockESTService{
|
||||
CSRAttrs: []byte{0x30, 0x00}, // empty SEQUENCE
|
||||
}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/csrattrs", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.CSRAttrs(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", w.Code)
|
||||
}
|
||||
ct := w.Header().Get("Content-Type")
|
||||
if ct != "application/csrattrs" {
|
||||
t.Errorf("expected application/csrattrs, got %s", ct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTCSRAttrs_MethodNotAllowed(t *testing.T) {
|
||||
svc := &mockESTService{}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/est/csrattrs", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.CSRAttrs(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCertsOnlyPKCS7(t *testing.T) {
|
||||
// Test with a dummy DER certificate
|
||||
dummyCert := []byte{0x30, 0x82, 0x01, 0x00} // minimal ASN.1 SEQUENCE
|
||||
result, err := buildCertsOnlyPKCS7([][]byte{dummyCert})
|
||||
if err != nil {
|
||||
t.Fatalf("buildCertsOnlyPKCS7 failed: %v", err)
|
||||
}
|
||||
if len(result) == 0 {
|
||||
t.Error("expected non-empty PKCS#7 output")
|
||||
}
|
||||
// Verify it starts with SEQUENCE tag
|
||||
if result[0] != 0x30 {
|
||||
t.Errorf("expected PKCS#7 to start with SEQUENCE tag (0x30), got 0x%02x", result[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPemToDERChain(t *testing.T) {
|
||||
pemData := generateTestCertPEM(t)
|
||||
certs, err := pemToDERChain(pemData)
|
||||
if err != nil {
|
||||
t.Fatalf("pemToDERChain failed: %v", err)
|
||||
}
|
||||
if len(certs) != 1 {
|
||||
t.Errorf("expected 1 cert, got %d", len(certs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPemToDERChain_NoCerts(t *testing.T) {
|
||||
_, err := pemToDERChain("not a PEM")
|
||||
if err == nil {
|
||||
t.Error("expected error for invalid PEM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestASN1EncodeLength(t *testing.T) {
|
||||
tests := []struct {
|
||||
length int
|
||||
expected []byte
|
||||
}{
|
||||
{0, []byte{0x00}},
|
||||
{1, []byte{0x01}},
|
||||
{127, []byte{0x7f}},
|
||||
{128, []byte{0x81, 0x80}},
|
||||
{256, []byte{0x82, 0x01, 0x00}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
result := asn1EncodeLength(tt.length)
|
||||
if len(result) != len(tt.expected) {
|
||||
t.Errorf("asn1EncodeLength(%d): expected %d bytes, got %d", tt.length, len(tt.expected), len(result))
|
||||
continue
|
||||
}
|
||||
for i := range result {
|
||||
if result[i] != tt.expected[i] {
|
||||
t.Errorf("asn1EncodeLength(%d): byte %d: expected 0x%02x, got 0x%02x", tt.length, i, tt.expected[i], result[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,7 +184,13 @@ func (h IssuerHandler) DeleteIssuer(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if err := h.svc.DeleteIssuer(id); err != nil {
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to delete issuer", requestID)
|
||||
if strings.Contains(err.Error(), "violates foreign key") || strings.Contains(err.Error(), "RESTRICT") {
|
||||
ErrorWithRequestID(w, http.StatusConflict, "Cannot delete issuer: certificates are still using this issuer", requestID)
|
||||
} else if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Issuer not found", requestID)
|
||||
} else {
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to delete issuer", requestID)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -77,8 +77,8 @@ func (m *mockNetworkScanService) TriggerScan(ctx context.Context, targetID strin
|
||||
func TestListNetworkScanTargets(t *testing.T) {
|
||||
svc := &mockNetworkScanService{
|
||||
targets: []*domain.NetworkScanTarget{
|
||||
{ID: "nst-1", Name: "target1", CIDRs: []string{"10.0.0.0/24"}, Ports: []int{443}},
|
||||
{ID: "nst-2", Name: "target2", CIDRs: []string{"192.168.0.0/16"}, Ports: []int{443, 8443}},
|
||||
{ID: "nst-1", Name: "target1", CIDRs: []string{"10.0.0.0/24"}, Ports: []int64{443}},
|
||||
{ID: "nst-2", Name: "target2", CIDRs: []string{"192.168.0.0/16"}, Ports: []int64{443, 8443}},
|
||||
},
|
||||
}
|
||||
h := NewNetworkScanHandler(svc)
|
||||
@@ -118,7 +118,7 @@ func TestCreateNetworkScanTarget(t *testing.T) {
|
||||
body, _ := json.Marshal(map[string]interface{}{
|
||||
"name": "Production",
|
||||
"cidrs": []string{"10.0.0.0/24"},
|
||||
"ports": []int{443},
|
||||
"ports": []int64{443},
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/network-scan-targets", bytes.NewReader(body))
|
||||
|
||||
@@ -183,7 +183,13 @@ func (h OwnerHandler) DeleteOwner(w http.ResponseWriter, r *http.Request) {
|
||||
id = parts[0]
|
||||
|
||||
if err := h.svc.DeleteOwner(id); err != nil {
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to delete owner", requestID)
|
||||
if strings.Contains(err.Error(), "violates foreign key") || strings.Contains(err.Error(), "RESTRICT") {
|
||||
ErrorWithRequestID(w, http.StatusConflict, "Cannot delete owner: certificates are still assigned to this owner", requestID)
|
||||
} else if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Owner not found", requestID)
|
||||
} else {
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to delete owner", requestID)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -209,6 +209,16 @@ func (r *Router) RegisterHandlers(
|
||||
r.Register("POST /api/v1/network-scan-targets/{id}/scan", http.HandlerFunc(networkScan.TriggerNetworkScan))
|
||||
}
|
||||
|
||||
// RegisterESTHandlers sets up EST (RFC 7030) routes under /.well-known/est/.
|
||||
// EST endpoints use a separate middleware chain (no API key auth — EST uses TLS client certs).
|
||||
func (r *Router) RegisterESTHandlers(est handler.ESTHandler) {
|
||||
// EST endpoints per RFC 7030 Section 3.2.2
|
||||
r.Register("GET /.well-known/est/cacerts", http.HandlerFunc(est.CACerts))
|
||||
r.Register("POST /.well-known/est/simpleenroll", http.HandlerFunc(est.SimpleEnroll))
|
||||
r.Register("POST /.well-known/est/simplereenroll", http.HandlerFunc(est.SimpleReEnroll))
|
||||
r.Register("GET /.well-known/est/csrattrs", http.HandlerFunc(est.CSRAttrs))
|
||||
}
|
||||
|
||||
// GetMux returns the underlying http.ServeMux for direct access if needed.
|
||||
func (r *Router) GetMux() *http.ServeMux {
|
||||
return r.mux
|
||||
|
||||
@@ -22,6 +22,7 @@ type Config struct {
|
||||
CA CAConfig
|
||||
Notifiers NotifierConfig
|
||||
NetworkScan NetworkScanConfig
|
||||
EST ESTConfig
|
||||
}
|
||||
|
||||
// NotifierConfig contains configuration for notification connectors.
|
||||
@@ -66,11 +67,12 @@ type StepCAConfig struct {
|
||||
|
||||
// ACMEConfig contains ACME issuer connector configuration.
|
||||
type ACMEConfig struct {
|
||||
DirectoryURL string
|
||||
Email string
|
||||
ChallengeType string // "http-01" (default) or "dns-01"
|
||||
DNSPresentScript string
|
||||
DNSCleanUpScript string
|
||||
DirectoryURL string
|
||||
Email string
|
||||
ChallengeType string // "http-01" (default), "dns-01", or "dns-persist-01"
|
||||
DNSPresentScript string
|
||||
DNSCleanUpScript string
|
||||
DNSPersistIssuerDomain string // Required for dns-persist-01 (e.g., "letsencrypt.org")
|
||||
}
|
||||
|
||||
// OpenSSLConfig contains OpenSSL/Custom CA issuer connector configuration.
|
||||
@@ -81,6 +83,14 @@ type OpenSSLConfig struct {
|
||||
TimeoutSeconds int
|
||||
}
|
||||
|
||||
// ESTConfig controls the RFC 7030 Enrollment over Secure Transport server.
|
||||
type ESTConfig struct {
|
||||
Enabled bool // Enable EST endpoints (default false)
|
||||
IssuerID string // Which issuer connector to use for EST enrollment (e.g., "iss-local")
|
||||
// ProfileID optionally constrains EST enrollments to a specific certificate profile.
|
||||
ProfileID string
|
||||
}
|
||||
|
||||
// NetworkScanConfig controls the server-side active TLS scanner.
|
||||
type NetworkScanConfig struct {
|
||||
Enabled bool // Enable network scanning (default false)
|
||||
@@ -189,6 +199,11 @@ func Load() (*Config, error) {
|
||||
Enabled: getEnvBool("CERTCTL_NETWORK_SCAN_ENABLED", false),
|
||||
ScanInterval: getEnvDuration("CERTCTL_NETWORK_SCAN_INTERVAL", 6*time.Hour),
|
||||
},
|
||||
EST: ESTConfig{
|
||||
Enabled: getEnvBool("CERTCTL_EST_ENABLED", false),
|
||||
IssuerID: getEnv("CERTCTL_EST_ISSUER_ID", "iss-local"),
|
||||
ProfileID: getEnv("CERTCTL_EST_PROFILE_ID", ""),
|
||||
},
|
||||
}
|
||||
|
||||
if err := cfg.Validate(); err != nil {
|
||||
|
||||
@@ -6,12 +6,16 @@ import (
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -28,21 +32,28 @@ type Config struct {
|
||||
EABHmac string `json:"eab_hmac,omitempty"` // External Account Binding HMAC Key
|
||||
HTTPPort int `json:"http_port,omitempty"` // Port for HTTP-01 challenge server (default: 80)
|
||||
|
||||
// ChallengeType selects the ACME challenge method: "http-01" (default) or "dns-01".
|
||||
// ChallengeType selects the ACME challenge method: "http-01" (default), "dns-01", or "dns-persist-01".
|
||||
// DNS-01 is required for wildcard certificates (*.example.com).
|
||||
// DNS-PERSIST-01 uses a standing TXT record (set once, reused forever) — no per-renewal DNS updates.
|
||||
ChallengeType string `json:"challenge_type,omitempty"`
|
||||
|
||||
// DNSPresentScript is the path to a script that creates DNS TXT records (dns-01 only).
|
||||
// DNSPresentScript is the path to a script that creates DNS TXT records (dns-01 and dns-persist-01).
|
||||
// The script receives CERTCTL_DNS_DOMAIN, CERTCTL_DNS_FQDN, CERTCTL_DNS_VALUE, CERTCTL_DNS_TOKEN.
|
||||
DNSPresentScript string `json:"dns_present_script,omitempty"`
|
||||
|
||||
// DNSCleanUpScript is the path to a script that removes DNS TXT records (dns-01 only).
|
||||
// Optional — if not set, records are not cleaned up automatically.
|
||||
// Not used by dns-persist-01 (records are permanent).
|
||||
DNSCleanUpScript string `json:"dns_cleanup_script,omitempty"`
|
||||
|
||||
// DNSPropagationWait is how long to wait (in seconds) after creating the TXT record
|
||||
// before telling the CA to validate. Defaults to 30 seconds.
|
||||
DNSPropagationWait int `json:"dns_propagation_wait,omitempty"`
|
||||
|
||||
// DNSPersistIssuerDomain is the CA's issuer domain name for dns-persist-01 records.
|
||||
// Used to construct the TXT record value: "<issuer-domain>; accounturi=<account-uri>".
|
||||
// Required when ChallengeType is "dns-persist-01". For Let's Encrypt, use "letsencrypt.org".
|
||||
DNSPersistIssuerDomain string `json:"dns_persist_issuer_domain,omitempty"`
|
||||
}
|
||||
|
||||
// Connector implements the issuer.Connector interface for ACME-compatible CAs
|
||||
@@ -87,10 +98,11 @@ func New(config *Config, logger *slog.Logger) *Connector {
|
||||
challengeTokens: make(map[string]string),
|
||||
}
|
||||
|
||||
// Initialize DNS solver if dns-01 challenge type is configured
|
||||
if config != nil && config.ChallengeType == "dns-01" && config.DNSPresentScript != "" {
|
||||
// Initialize DNS solver if dns-01 or dns-persist-01 challenge type is configured
|
||||
if config != nil && (config.ChallengeType == "dns-01" || config.ChallengeType == "dns-persist-01") && config.DNSPresentScript != "" {
|
||||
c.dnsSolver = NewScriptDNSSolver(config.DNSPresentScript, config.DNSCleanUpScript, logger)
|
||||
logger.Info("DNS-01 challenge solver configured",
|
||||
logger.Info("DNS challenge solver configured",
|
||||
"challenge_type", config.ChallengeType,
|
||||
"present_script", config.DNSPresentScript,
|
||||
"cleanup_script", config.DNSCleanUpScript)
|
||||
}
|
||||
@@ -141,13 +153,18 @@ func (c *Connector) ValidateConfig(ctx context.Context, rawConfig json.RawMessag
|
||||
}
|
||||
|
||||
// Validate challenge type
|
||||
if cfg.ChallengeType != "http-01" && cfg.ChallengeType != "dns-01" {
|
||||
return fmt.Errorf("invalid challenge_type: %s (must be http-01 or dns-01)", cfg.ChallengeType)
|
||||
if cfg.ChallengeType != "http-01" && cfg.ChallengeType != "dns-01" && cfg.ChallengeType != "dns-persist-01" {
|
||||
return fmt.Errorf("invalid challenge_type: %s (must be http-01, dns-01, or dns-persist-01)", cfg.ChallengeType)
|
||||
}
|
||||
|
||||
// DNS-01 requires a present script
|
||||
if cfg.ChallengeType == "dns-01" && cfg.DNSPresentScript == "" {
|
||||
return fmt.Errorf("dns_present_script is required for dns-01 challenge type")
|
||||
// DNS-01 and DNS-PERSIST-01 require a present script
|
||||
if (cfg.ChallengeType == "dns-01" || cfg.ChallengeType == "dns-persist-01") && cfg.DNSPresentScript == "" {
|
||||
return fmt.Errorf("dns_present_script is required for %s challenge type", cfg.ChallengeType)
|
||||
}
|
||||
|
||||
// DNS-PERSIST-01 requires an issuer domain
|
||||
if cfg.ChallengeType == "dns-persist-01" && cfg.DNSPersistIssuerDomain == "" {
|
||||
return fmt.Errorf("dns_persist_issuer_domain is required for dns-persist-01 challenge type (e.g., \"letsencrypt.org\")")
|
||||
}
|
||||
|
||||
if cfg.DNSPropagationWait == 0 {
|
||||
@@ -156,8 +173,8 @@ func (c *Connector) ValidateConfig(ctx context.Context, rawConfig json.RawMessag
|
||||
|
||||
c.config = &cfg
|
||||
|
||||
// Re-initialize DNS solver if switching to dns-01
|
||||
if cfg.ChallengeType == "dns-01" && cfg.DNSPresentScript != "" {
|
||||
// Re-initialize DNS solver if switching to dns-01 or dns-persist-01
|
||||
if (cfg.ChallengeType == "dns-01" || cfg.ChallengeType == "dns-persist-01") && cfg.DNSPresentScript != "" {
|
||||
c.dnsSolver = NewScriptDNSSolver(cfg.DNSPresentScript, cfg.DNSCleanUpScript, c.logger)
|
||||
}
|
||||
|
||||
@@ -188,6 +205,33 @@ func (c *Connector) ensureClient(ctx context.Context) error {
|
||||
acct := &acme.Account{
|
||||
Contact: []string{"mailto:" + c.config.Email},
|
||||
}
|
||||
|
||||
// Auto-fetch EAB credentials from ZeroSSL if directory URL is ZeroSSL and no EAB provided.
|
||||
// ZeroSSL offers a public endpoint that returns EAB credentials given an email address,
|
||||
// so users don't need to visit the ZeroSSL dashboard manually.
|
||||
if c.config.EABKid == "" && c.config.EABHmac == "" && isZeroSSL(c.config.DirectoryURL) {
|
||||
kid, hmac, eabErr := fetchZeroSSLEAB(ctx, c.config.Email)
|
||||
if eabErr != nil {
|
||||
return fmt.Errorf("failed to auto-fetch ZeroSSL EAB credentials: %w", eabErr)
|
||||
}
|
||||
c.config.EABKid = kid
|
||||
c.config.EABHmac = hmac
|
||||
c.logger.Info("auto-fetched EAB credentials from ZeroSSL", "eab_kid", kid)
|
||||
}
|
||||
|
||||
// External Account Binding (required by ZeroSSL, Google Trust Services, SSL.com, etc.)
|
||||
if c.config.EABKid != "" && c.config.EABHmac != "" {
|
||||
hmacKey, decodeErr := base64.RawURLEncoding.DecodeString(c.config.EABHmac)
|
||||
if decodeErr != nil {
|
||||
return fmt.Errorf("failed to decode EAB HMAC key (expected base64url): %w", decodeErr)
|
||||
}
|
||||
acct.ExternalAccountBinding = &acme.ExternalAccountBinding{
|
||||
KID: c.config.EABKid,
|
||||
Key: hmacKey,
|
||||
}
|
||||
c.logger.Info("using External Account Binding for ACME registration", "eab_kid", c.config.EABKid)
|
||||
}
|
||||
|
||||
_, err = c.client.Register(ctx, acct, acme.AcceptTOS)
|
||||
if err != nil {
|
||||
// Account may already exist, try to get it
|
||||
@@ -203,6 +247,67 @@ func (c *Connector) ensureClient(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// zeroSSLEABEndpoint is the ZeroSSL API endpoint for auto-generating EAB credentials.
|
||||
// Variable (not const) to allow test overrides.
|
||||
var zeroSSLEABEndpoint = "https://api.zerossl.com/acme/eab-credentials-email"
|
||||
|
||||
// isZeroSSL returns true if the ACME directory URL points to ZeroSSL.
|
||||
func isZeroSSL(directoryURL string) bool {
|
||||
return strings.Contains(strings.ToLower(directoryURL), "zerossl.com")
|
||||
}
|
||||
|
||||
// fetchZeroSSLEAB retrieves EAB credentials from ZeroSSL's public API endpoint.
|
||||
// ZeroSSL provides this so users don't need to visit the dashboard manually.
|
||||
// Returns (kid, hmac_key, error). The HMAC key is already base64url-encoded.
|
||||
func fetchZeroSSLEAB(ctx context.Context, email string) (string, string, error) {
|
||||
if email == "" {
|
||||
return "", "", fmt.Errorf("email is required for ZeroSSL EAB auto-fetch")
|
||||
}
|
||||
|
||||
form := url.Values{"email": {email}}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, zeroSSLEABEndpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", "", fmt.Errorf("ZeroSSL API returned status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
EABKid string `json:"eab_kid"`
|
||||
EABHmac string `json:"eab_hmac_key"`
|
||||
ErrorMsg string `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return "", "", fmt.Errorf("parse response: %w", err)
|
||||
}
|
||||
|
||||
if !result.Success || result.EABKid == "" || result.EABHmac == "" {
|
||||
errDetail := result.ErrorMsg
|
||||
if errDetail == "" {
|
||||
errDetail = string(body)
|
||||
}
|
||||
return "", "", fmt.Errorf("ZeroSSL EAB generation failed: %s", errDetail)
|
||||
}
|
||||
|
||||
return result.EABKid, result.EABHmac, nil
|
||||
}
|
||||
|
||||
// IssueCertificate submits a certificate issuance request to the ACME CA.
|
||||
//
|
||||
// Flow:
|
||||
@@ -335,12 +440,16 @@ func (c *Connector) GetOrderStatus(ctx context.Context, orderID string) (*issuer
|
||||
}
|
||||
|
||||
// solveAuthorizations processes all authorization URLs and solves their challenges.
|
||||
// Supports both HTTP-01 and DNS-01 challenge types based on configuration.
|
||||
// Supports HTTP-01, DNS-01, and DNS-PERSIST-01 challenge types based on configuration.
|
||||
func (c *Connector) solveAuthorizations(ctx context.Context, authzURLs []string) error {
|
||||
if c.config.ChallengeType == "dns-01" {
|
||||
switch c.config.ChallengeType {
|
||||
case "dns-01":
|
||||
return c.solveAuthorizationsDNS01(ctx, authzURLs)
|
||||
case "dns-persist-01":
|
||||
return c.solveAuthorizationsDNSPersist01(ctx, authzURLs)
|
||||
default:
|
||||
return c.solveAuthorizationsHTTP01(ctx, authzURLs)
|
||||
}
|
||||
return c.solveAuthorizationsHTTP01(ctx, authzURLs)
|
||||
}
|
||||
|
||||
// solveAuthorizationsHTTP01 solves challenges using the HTTP-01 method.
|
||||
@@ -497,6 +606,126 @@ func (c *Connector) solveAuthorizationsDNS01(ctx context.Context, authzURLs []st
|
||||
return nil
|
||||
}
|
||||
|
||||
// solveAuthorizationsDNSPersist01 solves challenges using the DNS-PERSIST-01 method.
|
||||
// DNS-PERSIST-01 uses a standing TXT record at _validation-persist.<domain> that persists
|
||||
// across renewals. The record contains the CA's issuer domain and the ACME account URI,
|
||||
// authorizing unlimited future issuances without per-renewal DNS updates.
|
||||
//
|
||||
// Flow:
|
||||
// 1. For each authorization, check if it's already valid (standing record exists)
|
||||
// 2. If pending, find the dns-persist-01 challenge
|
||||
// 3. Build the TXT record value: "<issuer-domain>; accounturi=<account-uri>"
|
||||
// 4. Create the _validation-persist TXT record via the present script (one-time)
|
||||
// 5. Wait for propagation, then accept the challenge
|
||||
// 6. No cleanup — the record is permanent by design
|
||||
//
|
||||
// See: draft-ietf-acme-dns-persist (IETF), CA/Browser Forum ballot SC-088v3
|
||||
func (c *Connector) solveAuthorizationsDNSPersist01(ctx context.Context, authzURLs []string) error {
|
||||
if c.dnsSolver == nil {
|
||||
return fmt.Errorf("dns-persist-01 challenge type configured but no DNS solver available")
|
||||
}
|
||||
|
||||
// Get the account URI for the TXT record value
|
||||
if err := c.ensureClient(ctx); err != nil {
|
||||
return fmt.Errorf("ACME client init for dns-persist-01: %w", err)
|
||||
}
|
||||
acct, err := c.client.GetReg(ctx, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get ACME account URI for dns-persist-01: %w", err)
|
||||
}
|
||||
|
||||
for _, authzURL := range authzURLs {
|
||||
authz, err := c.client.GetAuthorization(ctx, authzURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get authorization %s: %w", authzURL, err)
|
||||
}
|
||||
|
||||
// If already valid (standing record recognized), skip
|
||||
if authz.Status == acme.StatusValid {
|
||||
c.logger.Info("dns-persist-01 authorization already valid (standing record recognized)",
|
||||
"domain", authz.Identifier.Value)
|
||||
continue
|
||||
}
|
||||
|
||||
// Find the dns-persist-01 challenge
|
||||
var persistChallenge *acme.Challenge
|
||||
for _, ch := range authz.Challenges {
|
||||
if ch.Type == "dns-persist-01" {
|
||||
persistChallenge = ch
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: if the CA doesn't offer dns-persist-01 yet, try dns-01
|
||||
if persistChallenge == nil {
|
||||
c.logger.Warn("dns-persist-01 challenge not offered by CA, falling back to dns-01",
|
||||
"domain", authz.Identifier.Value)
|
||||
return c.solveAuthorizationsDNS01(ctx, authzURLs)
|
||||
}
|
||||
|
||||
domain := authz.Identifier.Value
|
||||
|
||||
// Build the persistent TXT record value per draft-ietf-acme-dns-persist:
|
||||
// "<issuer-domain>; accounturi=<account-uri>"
|
||||
recordValue := fmt.Sprintf("%s; accounturi=%s", c.config.DNSPersistIssuerDomain, acct.URI)
|
||||
|
||||
c.logger.Info("creating persistent DNS validation record",
|
||||
"domain", domain,
|
||||
"fqdn", "_validation-persist."+domain,
|
||||
"issuer_domain", c.config.DNSPersistIssuerDomain,
|
||||
"account_uri", acct.URI)
|
||||
|
||||
// Create the standing TXT record via the present script.
|
||||
// The script receives CERTCTL_DNS_FQDN="_validation-persist.<domain>"
|
||||
// and CERTCTL_DNS_VALUE="<issuer-domain>; accounturi=<account-uri>".
|
||||
if err := c.presentPersistRecord(ctx, domain, persistChallenge.Token, recordValue); err != nil {
|
||||
return fmt.Errorf("failed to create persistent DNS record for %s: %w", domain, err)
|
||||
}
|
||||
|
||||
// Wait for DNS propagation
|
||||
propagationWait := time.Duration(c.config.DNSPropagationWait) * time.Second
|
||||
c.logger.Info("waiting for DNS propagation",
|
||||
"domain", domain,
|
||||
"wait_seconds", c.config.DNSPropagationWait)
|
||||
time.Sleep(propagationWait)
|
||||
|
||||
// Tell the CA we're ready
|
||||
if _, err := c.client.Accept(ctx, persistChallenge); err != nil {
|
||||
return fmt.Errorf("failed to accept dns-persist-01 challenge: %w", err)
|
||||
}
|
||||
|
||||
// Wait for authorization to be valid
|
||||
if _, err := c.client.WaitAuthorization(ctx, authzURL); err != nil {
|
||||
return fmt.Errorf("dns-persist-01 authorization failed for %s: %w", domain, err)
|
||||
}
|
||||
|
||||
c.logger.Info("dns-persist-01 authorization validated (record is now permanent)",
|
||||
"domain", domain)
|
||||
|
||||
// No cleanup — the record is permanent by design.
|
||||
// Future renewals will skip challenge solving entirely (authz.Status == StatusValid).
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// presentPersistRecord creates a _validation-persist TXT record using the DNS solver.
|
||||
// Unlike dns-01 which uses _acme-challenge, dns-persist-01 uses _validation-persist.
|
||||
func (c *Connector) presentPersistRecord(ctx context.Context, domain, token, recordValue string) error {
|
||||
if c.dnsSolver == nil {
|
||||
return fmt.Errorf("DNS solver not configured")
|
||||
}
|
||||
|
||||
// Use PresentPersist if available (ScriptDNSSolver) — targets _validation-persist prefix.
|
||||
if solver, ok := c.dnsSolver.(*ScriptDNSSolver); ok {
|
||||
return solver.PresentPersist(ctx, domain, token, recordValue)
|
||||
}
|
||||
|
||||
// For other DNSSolver implementations, fall back to Present.
|
||||
// Custom implementations should read CERTCTL_DNS_FQDN to determine the record name.
|
||||
return c.dnsSolver.Present(ctx, domain, token, recordValue)
|
||||
}
|
||||
|
||||
// startChallengeServer starts an HTTP server that responds to ACME HTTP-01 challenges.
|
||||
// It listens on the configured HTTP port and serves challenge tokens at
|
||||
// /.well-known/acme-challenge/{token}.
|
||||
@@ -619,3 +848,8 @@ func (c *Connector) GenerateCRL(ctx context.Context, revokedCerts []issuer.Revok
|
||||
func (c *Connector) SignOCSPResponse(ctx context.Context, req issuer.OCSPSignRequest) ([]byte, error) {
|
||||
return nil, fmt.Errorf("ACME issuers do not support OCSP response signing")
|
||||
}
|
||||
|
||||
// GetCACertPEM is not supported by ACME issuers (the CA chain is returned per-issuance).
|
||||
func (c *Connector) GetCACertPEM(ctx context.Context) (string, error) {
|
||||
return "", fmt.Errorf("ACME issuers do not provide a static CA certificate; chain is returned per-issuance")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func testLogger() *slog.Logger {
|
||||
return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
|
||||
}
|
||||
|
||||
func TestValidateConfig_MissingDirectoryURL(t *testing.T) {
|
||||
c := New(nil, testLogger())
|
||||
cfg, _ := json.Marshal(map[string]string{"email": "test@example.com"})
|
||||
err := c.ValidateConfig(context.Background(), cfg)
|
||||
if err == nil || !strings.Contains(err.Error(), "directory_url is required") {
|
||||
t.Fatalf("expected directory_url error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateConfig_MissingEmail(t *testing.T) {
|
||||
c := New(nil, testLogger())
|
||||
cfg, _ := json.Marshal(map[string]string{"directory_url": "https://example.com/directory"})
|
||||
err := c.ValidateConfig(context.Background(), cfg)
|
||||
if err == nil || !strings.Contains(err.Error(), "email is required") {
|
||||
t.Fatalf("expected email error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateConfig_InvalidChallengeType(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"newNonce":"","newAccount":"","newOrder":""}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(nil, testLogger())
|
||||
cfg, _ := json.Marshal(map[string]string{
|
||||
"directory_url": srv.URL,
|
||||
"email": "test@example.com",
|
||||
"challenge_type": "invalid-challenge",
|
||||
})
|
||||
err := c.ValidateConfig(context.Background(), cfg)
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid challenge_type") {
|
||||
t.Fatalf("expected invalid challenge_type error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateConfig_Success(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"newNonce":"","newAccount":"","newOrder":""}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(nil, testLogger())
|
||||
cfg, _ := json.Marshal(map[string]string{
|
||||
"directory_url": srv.URL,
|
||||
"email": "test@example.com",
|
||||
})
|
||||
err := c.ValidateConfig(context.Background(), cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("expected success, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateConfig_EABFieldsPreserved(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"newNonce":"","newAccount":"","newOrder":""}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(nil, testLogger())
|
||||
cfg, _ := json.Marshal(map[string]string{
|
||||
"directory_url": srv.URL,
|
||||
"email": "test@example.com",
|
||||
"eab_kid": "kid-12345",
|
||||
"eab_hmac": base64.RawURLEncoding.EncodeToString([]byte("test-hmac-key")),
|
||||
})
|
||||
err := c.ValidateConfig(context.Background(), cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("expected success, got: %v", err)
|
||||
}
|
||||
if c.config.EABKid != "kid-12345" {
|
||||
t.Fatalf("expected EABKid to be preserved, got: %s", c.config.EABKid)
|
||||
}
|
||||
if c.config.EABHmac == "" {
|
||||
t.Fatal("expected EABHmac to be preserved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureClient_EABDecodeError(t *testing.T) {
|
||||
c := New(&Config{
|
||||
DirectoryURL: "https://acme.example.com/directory",
|
||||
Email: "test@example.com",
|
||||
EABKid: "kid-12345",
|
||||
EABHmac: "!!!not-valid-base64url!!!",
|
||||
}, testLogger())
|
||||
|
||||
err := c.ensureClient(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "decode EAB HMAC") {
|
||||
t.Fatalf("expected EAB decode error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureClient_EABBindingSet(t *testing.T) {
|
||||
// We can't fully mock the ACME protocol (JWS nonce exchange), but we can
|
||||
// verify that valid EAB credentials are decoded and attached to the account
|
||||
// without panicking. The ensureClient call will fail at the network level
|
||||
// (no real ACME server), but it must NOT fail at EAB decoding.
|
||||
hmacKey := base64.RawURLEncoding.EncodeToString([]byte("test-hmac-secret-key"))
|
||||
c := New(&Config{
|
||||
DirectoryURL: "https://127.0.0.1:1/directory", // unreachable — that's fine
|
||||
Email: "test@example.com",
|
||||
EABKid: "kid-zerossl-12345",
|
||||
EABHmac: hmacKey,
|
||||
}, testLogger())
|
||||
|
||||
err := c.ensureClient(context.Background())
|
||||
// Expected: network error (unreachable server), NOT an EAB decode error
|
||||
if err != nil && strings.Contains(err.Error(), "decode EAB HMAC") {
|
||||
t.Fatalf("EAB decode should not fail with valid base64url key, got: %v", err)
|
||||
}
|
||||
// We expect some error (network unreachable) — that's correct
|
||||
if err == nil {
|
||||
t.Log("ensureClient succeeded (unexpected but not a failure for this test)")
|
||||
}
|
||||
}
|
||||
|
||||
// --- ZeroSSL auto-EAB tests ---
|
||||
|
||||
func TestIsZeroSSL(t *testing.T) {
|
||||
tests := []struct {
|
||||
url string
|
||||
expect bool
|
||||
}{
|
||||
{"https://acme.zerossl.com/v2/DV90", true},
|
||||
{"https://ACME.ZEROSSL.COM/v2/DV90", true},
|
||||
{"https://acme-v02.api.letsencrypt.org/directory", false},
|
||||
{"https://acme.example.com/directory", false},
|
||||
{"", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := isZeroSSL(tt.url); got != tt.expect {
|
||||
t.Errorf("isZeroSSL(%q) = %v, want %v", tt.url, got, tt.expect)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchZeroSSLEAB_Success(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
t.Errorf("expected POST, got %s", r.Method)
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/x-www-form-urlencoded" {
|
||||
t.Errorf("expected form content-type, got %s", ct)
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if email := r.FormValue("email"); email != "test@example.com" {
|
||||
t.Errorf("expected email test@example.com, got %s", email)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"success":true,"eab_kid":"kid_abc123","eab_hmac_key":"dGVzdC1obWFjLWtleQ"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// Override the endpoint for testing
|
||||
origEndpoint := zeroSSLEABEndpoint
|
||||
defer func() { zeroSSLEABEndpoint = origEndpoint }()
|
||||
zeroSSLEABEndpoint = srv.URL
|
||||
|
||||
kid, hmac, err := fetchZeroSSLEAB(context.Background(), "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("expected success, got: %v", err)
|
||||
}
|
||||
if kid != "kid_abc123" {
|
||||
t.Errorf("expected kid_abc123, got %s", kid)
|
||||
}
|
||||
if hmac != "dGVzdC1obWFjLWtleQ" {
|
||||
t.Errorf("expected dGVzdC1obWFjLWtleQ, got %s", hmac)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchZeroSSLEAB_EmptyEmail(t *testing.T) {
|
||||
_, _, err := fetchZeroSSLEAB(context.Background(), "")
|
||||
if err == nil || !strings.Contains(err.Error(), "email is required") {
|
||||
t.Fatalf("expected email required error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchZeroSSLEAB_APIError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprint(w, `{"success":false,"error":"invalid email"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
origEndpoint := zeroSSLEABEndpoint
|
||||
defer func() { zeroSSLEABEndpoint = origEndpoint }()
|
||||
zeroSSLEABEndpoint = srv.URL
|
||||
|
||||
_, _, err := fetchZeroSSLEAB(context.Background(), "bad@example.com")
|
||||
if err == nil || !strings.Contains(err.Error(), "status 400") {
|
||||
t.Fatalf("expected API error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchZeroSSLEAB_MissingCredentials(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"success":false,"error":"rate limited"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
origEndpoint := zeroSSLEABEndpoint
|
||||
defer func() { zeroSSLEABEndpoint = origEndpoint }()
|
||||
zeroSSLEABEndpoint = srv.URL
|
||||
|
||||
_, _, err := fetchZeroSSLEAB(context.Background(), "test@example.com")
|
||||
if err == nil || !strings.Contains(err.Error(), "EAB generation failed") {
|
||||
t.Fatalf("expected EAB generation failed error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureClient_ZeroSSLAutoEAB(t *testing.T) {
|
||||
// Mock ZeroSSL EAB endpoint
|
||||
eabSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"success":true,"eab_kid":"auto-kid-123","eab_hmac_key":"dGVzdC1obWFjLWtleQ"}`)
|
||||
}))
|
||||
defer eabSrv.Close()
|
||||
|
||||
origEndpoint := zeroSSLEABEndpoint
|
||||
defer func() { zeroSSLEABEndpoint = origEndpoint }()
|
||||
zeroSSLEABEndpoint = eabSrv.URL
|
||||
|
||||
// Use an unreachable ACME directory — we only care that auto-EAB fetch happens
|
||||
c := New(&Config{
|
||||
DirectoryURL: "https://acme.zerossl.com/v2/DV90",
|
||||
Email: "test@example.com",
|
||||
// EABKid and EABHmac intentionally empty — should auto-fetch
|
||||
}, testLogger())
|
||||
|
||||
err := c.ensureClient(context.Background())
|
||||
// Will fail at ACME protocol level (unreachable ZeroSSL directory), but
|
||||
// EAB credentials should have been auto-fetched and set on config
|
||||
if c.config.EABKid != "auto-kid-123" {
|
||||
t.Errorf("expected auto-fetched EABKid, got: %s (err: %v)", c.config.EABKid, err)
|
||||
}
|
||||
if c.config.EABHmac != "dGVzdC1obWFjLWtleQ" {
|
||||
t.Errorf("expected auto-fetched EABHmac, got: %s", c.config.EABHmac)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,24 @@ func (s *ScriptDNSSolver) CleanUp(ctx context.Context, domain, token, keyAuth st
|
||||
return s.runScript(ctx, s.CleanUpScript, domain, fqdn, token, keyAuth)
|
||||
}
|
||||
|
||||
// PresentPersist creates a persistent DNS TXT record at _validation-persist.<domain>.
|
||||
// Used by dns-persist-01 (draft-ietf-acme-dns-persist). Unlike Present (which targets
|
||||
// _acme-challenge), this targets _validation-persist and the record is intended to be permanent.
|
||||
func (s *ScriptDNSSolver) PresentPersist(ctx context.Context, domain, token, recordValue string) error {
|
||||
if s.PresentScript == "" {
|
||||
return fmt.Errorf("DNS present script not configured")
|
||||
}
|
||||
|
||||
fqdn := "_validation-persist." + domain
|
||||
|
||||
s.Logger.Info("creating persistent DNS TXT record via script",
|
||||
"domain", domain,
|
||||
"fqdn", fqdn,
|
||||
"script", s.PresentScript)
|
||||
|
||||
return s.runScript(ctx, s.PresentScript, domain, fqdn, token, recordValue)
|
||||
}
|
||||
|
||||
// runScript executes a DNS hook script with the appropriate environment variables.
|
||||
func (s *ScriptDNSSolver) runScript(ctx context.Context, script, domain, fqdn, token, keyAuth string) error {
|
||||
timeout := s.Timeout
|
||||
|
||||
@@ -110,3 +110,86 @@ echo "cleaned $CERTCTL_DNS_FQDN" > ` + outputFile + `
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestScriptDNSSolver_PresentPersist(t *testing.T) {
|
||||
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("PresentPersist_Success", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
outputFile := filepath.Join(tmpDir, "persist-record.txt")
|
||||
|
||||
scriptPath := filepath.Join(tmpDir, "present.sh")
|
||||
script := `#!/bin/sh
|
||||
echo "DOMAIN=$CERTCTL_DNS_DOMAIN FQDN=$CERTCTL_DNS_FQDN VALUE=$CERTCTL_DNS_VALUE TOKEN=$CERTCTL_DNS_TOKEN" > ` + outputFile + `
|
||||
`
|
||||
if err := os.WriteFile(scriptPath, []byte(script), 0755); err != nil {
|
||||
t.Fatalf("Failed to create script: %v", err)
|
||||
}
|
||||
|
||||
solver := acmeissuer.NewScriptDNSSolver(scriptPath, "", logger)
|
||||
err := solver.PresentPersist(ctx, "example.com", "test-token", "letsencrypt.org; accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/123")
|
||||
if err != nil {
|
||||
t.Fatalf("PresentPersist failed: %v", err)
|
||||
}
|
||||
|
||||
output, err := os.ReadFile(outputFile)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read output file: %v", err)
|
||||
}
|
||||
|
||||
// Verify _validation-persist prefix (not _acme-challenge)
|
||||
expected := "DOMAIN=example.com FQDN=_validation-persist.example.com VALUE=letsencrypt.org; accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/123 TOKEN=test-token\n"
|
||||
if string(output) != expected {
|
||||
t.Errorf("Script output mismatch:\ngot: %q\nwant: %q", string(output), expected)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PresentPersist_NoScript", func(t *testing.T) {
|
||||
solver := acmeissuer.NewScriptDNSSolver("", "", logger)
|
||||
err := solver.PresentPersist(ctx, "example.com", "token", "letsencrypt.org; accounturi=https://example.com/acct/1")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error when no script is configured")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PresentPersist_ScriptFailure", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
scriptPath := filepath.Join(tmpDir, "fail.sh")
|
||||
script := `#!/bin/sh
|
||||
echo "error: DNS API failure" >&2
|
||||
exit 1
|
||||
`
|
||||
os.WriteFile(scriptPath, []byte(script), 0755)
|
||||
|
||||
solver := acmeissuer.NewScriptDNSSolver(scriptPath, "", logger)
|
||||
err := solver.PresentPersist(ctx, "example.com", "token", "letsencrypt.org; accounturi=https://example.com/acct/1")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error from failing script")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PresentPersist_WildcardDomain", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
outputFile := filepath.Join(tmpDir, "persist-wildcard.txt")
|
||||
|
||||
scriptPath := filepath.Join(tmpDir, "present.sh")
|
||||
script := `#!/bin/sh
|
||||
echo "FQDN=$CERTCTL_DNS_FQDN" > ` + outputFile + `
|
||||
`
|
||||
os.WriteFile(scriptPath, []byte(script), 0755)
|
||||
|
||||
solver := acmeissuer.NewScriptDNSSolver(scriptPath, "", logger)
|
||||
// For *.example.com, the persist record should be at _validation-persist.example.com
|
||||
err := solver.PresentPersist(ctx, "example.com", "token", "letsencrypt.org; accounturi=https://example.com/acct/1")
|
||||
if err != nil {
|
||||
t.Fatalf("PresentPersist failed for wildcard base domain: %v", err)
|
||||
}
|
||||
|
||||
output, _ := os.ReadFile(outputFile)
|
||||
expected := "FQDN=_validation-persist.example.com\n"
|
||||
if string(output) != expected {
|
||||
t.Errorf("FQDN mismatch: got %q, want %q", string(output), expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@ type Connector interface {
|
||||
// SignOCSPResponse signs an OCSP response for the given certificate serial.
|
||||
// Returns nil if the issuer does not support OCSP (e.g., ACME).
|
||||
SignOCSPResponse(ctx context.Context, req OCSPSignRequest) ([]byte, error)
|
||||
|
||||
// GetCACertPEM returns the PEM-encoded CA certificate chain for this issuer.
|
||||
// Used by the EST /cacerts endpoint. Returns empty string if not available.
|
||||
GetCACertPEM(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
// IssuanceRequest contains the parameters for issuing a new certificate.
|
||||
|
||||
@@ -664,3 +664,12 @@ func (c *Connector) SignOCSPResponse(ctx context.Context, req issuer.OCSPSignReq
|
||||
|
||||
return respBytes, nil
|
||||
}
|
||||
|
||||
// GetCACertPEM returns the PEM-encoded CA certificate for this issuer.
|
||||
// Used by the EST /cacerts endpoint to distribute the CA trust chain.
|
||||
func (c *Connector) GetCACertPEM(ctx context.Context) (string, error) {
|
||||
if err := c.ensureCA(ctx); err != nil {
|
||||
return "", fmt.Errorf("CA initialization failed: %w", err)
|
||||
}
|
||||
return c.caCertPEM, nil
|
||||
}
|
||||
|
||||
@@ -358,6 +358,11 @@ func (c *Connector) SignOCSPResponse(ctx context.Context, req issuer.OCSPSignReq
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// GetCACertPEM is not supported by the custom CA connector (no CA cert access).
|
||||
func (c *Connector) GetCACertPEM(ctx context.Context) (string, error) {
|
||||
return "", fmt.Errorf("custom CA connector does not provide CA certificate access")
|
||||
}
|
||||
|
||||
// --- Helper Methods ---
|
||||
|
||||
// writeTempFile writes data to a temporary file and returns its path.
|
||||
|
||||
@@ -467,5 +467,10 @@ func (c *Connector) SignOCSPResponse(ctx context.Context, req issuer.OCSPSignReq
|
||||
return nil, fmt.Errorf("step-ca provides its own OCSP responder; use step-ca's /ocsp directly")
|
||||
}
|
||||
|
||||
// GetCACertPEM is not directly supported; step-ca serves its own /root endpoint.
|
||||
func (c *Connector) GetCACertPEM(ctx context.Context) (string, error) {
|
||||
return "", fmt.Errorf("step-ca serves its own CA certificate at /root; use step-ca's endpoint directly")
|
||||
}
|
||||
|
||||
// Ensure Connector implements the issuer.Connector interface.
|
||||
var _ issuer.Connector = (*Connector)(nil)
|
||||
|
||||
@@ -43,7 +43,7 @@ func TestDiscoveredCertificate_IsExpired(t *testing.T) {
|
||||
{"expired certificate", &pastTime, true},
|
||||
{"valid certificate", &futureTime, false},
|
||||
{"nil NotAfter", nil, false},
|
||||
{"expires at current time (edge case)", &now, false}, // Before() = false when at same time
|
||||
{"expires at current time (edge case)", func() *time.Time { t := now.Add(1 * time.Second); return &t }(), false}, // 1s in future — Before() returns false
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package domain
|
||||
|
||||
// ESTEnrollResult holds the result of an EST (RFC 7030) enrollment operation.
|
||||
type ESTEnrollResult struct {
|
||||
CertPEM string `json:"cert_pem"` // PEM-encoded signed certificate
|
||||
ChainPEM string `json:"chain_pem"` // PEM-encoded CA chain
|
||||
}
|
||||
@@ -7,7 +7,7 @@ type NetworkScanTarget struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
CIDRs []string `json:"cidrs"`
|
||||
Ports []int `json:"ports"`
|
||||
Ports []int64 `json:"ports"`
|
||||
Enabled bool `json:"enabled"`
|
||||
ScanIntervalHours int `json:"scan_interval_hours"`
|
||||
TimeoutMs int `json:"timeout_ms"`
|
||||
|
||||
@@ -10,7 +10,7 @@ func TestNetworkScanTarget_Defaults(t *testing.T) {
|
||||
ID: "nst-test",
|
||||
Name: "Test Target",
|
||||
CIDRs: []string{"10.0.0.0/24"},
|
||||
Ports: []int{443},
|
||||
Ports: []int64{443},
|
||||
Enabled: true,
|
||||
ScanIntervalHours: 6,
|
||||
TimeoutMs: 5000,
|
||||
@@ -35,7 +35,7 @@ func TestNetworkScanTarget_WithScanResults(t *testing.T) {
|
||||
ID: "nst-prod",
|
||||
Name: "Production Network",
|
||||
CIDRs: []string{"192.168.1.0/24", "10.0.0.0/16"},
|
||||
Ports: []int{443, 8443, 636},
|
||||
Ports: []int64{443, 8443, 636},
|
||||
Enabled: true,
|
||||
ScanIntervalHours: 1,
|
||||
TimeoutMs: 3000,
|
||||
|
||||
@@ -2,9 +2,17 @@ package integration
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -892,3 +900,269 @@ func TestM20EnhancedQueryAPI(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// generateE2ECSRPEM creates a valid ECDSA P-256 CSR PEM for integration testing.
|
||||
func generateE2ECSRPEM(t *testing.T, cn string, sans []string) string {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("generate key: %v", err)
|
||||
}
|
||||
template := &x509.CertificateRequest{
|
||||
Subject: pkix.Name{CommonName: cn},
|
||||
DNSNames: sans,
|
||||
}
|
||||
csrDER, err := x509.CreateCertificateRequest(rand.Reader, template, key)
|
||||
if err != nil {
|
||||
t.Fatalf("create CSR: %v", err)
|
||||
}
|
||||
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER}))
|
||||
}
|
||||
|
||||
// generateE2ECSRBase64DER creates a valid base64-encoded DER CSR for EST wire format testing.
|
||||
func generateE2ECSRBase64DER(t *testing.T, cn string, sans []string) string {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("generate key: %v", err)
|
||||
}
|
||||
template := &x509.CertificateRequest{
|
||||
Subject: pkix.Name{CommonName: cn},
|
||||
DNSNames: sans,
|
||||
}
|
||||
csrDER, err := x509.CreateCertificateRequest(rand.Reader, template, key)
|
||||
if err != nil {
|
||||
t.Fatalf("create CSR: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(csrDER)
|
||||
}
|
||||
|
||||
// TestPrometheusMetrics exercises the Prometheus metrics endpoint (M22).
|
||||
func TestPrometheusMetrics(t *testing.T) {
|
||||
server, _, _, _ := setupTestServer(t)
|
||||
|
||||
t.Run("GetPrometheusMetrics_Success", func(t *testing.T) {
|
||||
resp, err := http.Get(server.URL + "/api/v1/metrics/prometheus")
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
// Verify Content-Type contains text/plain
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if !strings.Contains(contentType, "text/plain") {
|
||||
t.Errorf("expected Content-Type containing 'text/plain', got %s", contentType)
|
||||
}
|
||||
|
||||
// Read and verify Prometheus format
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
bodyStr := string(body)
|
||||
|
||||
// Should contain HELP and TYPE lines for metrics
|
||||
if !strings.Contains(bodyStr, "# HELP") {
|
||||
t.Error("expected HELP line in Prometheus response")
|
||||
}
|
||||
if !strings.Contains(bodyStr, "# TYPE") {
|
||||
t.Error("expected TYPE line in Prometheus response")
|
||||
}
|
||||
|
||||
// Should contain metric lines (gauge, counter, uptime)
|
||||
if !strings.Contains(bodyStr, "certctl_") {
|
||||
t.Error("expected certctl_ prefixed metrics in response")
|
||||
}
|
||||
|
||||
t.Logf("Prometheus metrics endpoint working, body size: %d bytes", len(bodyStr))
|
||||
})
|
||||
|
||||
t.Run("GetPrometheusMetrics_MethodNotAllowed", func(t *testing.T) {
|
||||
resp, err := http.Post(server.URL+"/api/v1/metrics/prometheus", "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestESTEndpoints exercises the EST (RFC 7030) enrollment endpoints end-to-end (M23).
|
||||
func TestESTEndpoints(t *testing.T) {
|
||||
server, _, _, _ := setupTestServer(t)
|
||||
|
||||
// ===========================
|
||||
// GET /cacerts — CA certificate chain
|
||||
// ===========================
|
||||
t.Run("GetCACerts_Success", func(t *testing.T) {
|
||||
resp, err := http.Get(server.URL + "/.well-known/est/cacerts")
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
ct := resp.Header.Get("Content-Type")
|
||||
if !strings.Contains(ct, "application/pkcs7-mime") {
|
||||
t.Errorf("expected application/pkcs7-mime content type, got %s", ct)
|
||||
}
|
||||
cte := resp.Header.Get("Content-Transfer-Encoding")
|
||||
if cte != "base64" {
|
||||
t.Errorf("expected base64 content-transfer-encoding, got %s", cte)
|
||||
}
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
if len(bodyBytes) == 0 {
|
||||
t.Error("expected non-empty PKCS#7 response body")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetCACerts_MethodNotAllowed", func(t *testing.T) {
|
||||
resp, err := http.Post(server.URL+"/.well-known/est/cacerts", "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
|
||||
// ===========================
|
||||
// POST /simpleenroll — certificate enrollment
|
||||
// ===========================
|
||||
t.Run("SimpleEnroll_PEM_Success", func(t *testing.T) {
|
||||
csrPEM := generateE2ECSRPEM(t, "est-test.example.com", []string{"est-test.example.com"})
|
||||
resp, err := http.Post(server.URL+"/.well-known/est/simpleenroll", "application/pkcs10", strings.NewReader(csrPEM))
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
ct := resp.Header.Get("Content-Type")
|
||||
if !strings.Contains(ct, "application/pkcs7-mime") {
|
||||
t.Errorf("expected application/pkcs7-mime, got %s", ct)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("SimpleEnroll_Base64DER_Success", func(t *testing.T) {
|
||||
csrB64 := generateE2ECSRBase64DER(t, "est-der.example.com", []string{"est-der.example.com"})
|
||||
resp, err := http.Post(server.URL+"/.well-known/est/simpleenroll", "application/pkcs10", strings.NewReader(csrB64))
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("SimpleEnroll_EmptyBody", func(t *testing.T) {
|
||||
resp, err := http.Post(server.URL+"/.well-known/est/simpleenroll", "application/pkcs10", strings.NewReader(""))
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for empty body, got %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("SimpleEnroll_InvalidCSR", func(t *testing.T) {
|
||||
resp, err := http.Post(server.URL+"/.well-known/est/simpleenroll", "application/pkcs10", strings.NewReader("not-a-valid-csr"))
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for invalid CSR, got %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("SimpleEnroll_MissingCN", func(t *testing.T) {
|
||||
csrPEM := generateE2ECSRPEM(t, "", []string{"no-cn.example.com"})
|
||||
resp, err := http.Post(server.URL+"/.well-known/est/simpleenroll", "application/pkcs10", strings.NewReader(csrPEM))
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// Should fail because EST requires a Common Name
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
t.Error("expected error for CSR without Common Name")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("SimpleEnroll_MethodNotAllowed", func(t *testing.T) {
|
||||
resp, err := http.Get(server.URL + "/.well-known/est/simpleenroll")
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
|
||||
// ===========================
|
||||
// POST /simplereenroll — certificate re-enrollment
|
||||
// ===========================
|
||||
t.Run("SimpleReEnroll_Success", func(t *testing.T) {
|
||||
csrPEM := generateE2ECSRPEM(t, "renew-est.example.com", []string{"renew-est.example.com"})
|
||||
resp, err := http.Post(server.URL+"/.well-known/est/simplereenroll", "application/pkcs10", strings.NewReader(csrPEM))
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("SimpleReEnroll_MethodNotAllowed", func(t *testing.T) {
|
||||
resp, err := http.Get(server.URL + "/.well-known/est/simplereenroll")
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
|
||||
// ===========================
|
||||
// GET /csrattrs — CSR attributes
|
||||
// ===========================
|
||||
t.Run("GetCSRAttrs_NoContent", func(t *testing.T) {
|
||||
resp, err := http.Get(server.URL + "/.well-known/est/csrattrs")
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// Default implementation returns nil attrs → 204 No Content
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
t.Errorf("expected 204, got %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetCSRAttrs_MethodNotAllowed", func(t *testing.T) {
|
||||
resp, err := http.Post(server.URL+"/.well-known/est/csrattrs", "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -82,6 +82,10 @@ func TestCertificateLifecycle(t *testing.T) {
|
||||
discoveryHandler := handler.NewDiscoveryHandler(&mockDiscoveryService{})
|
||||
networkScanHandler := handler.NewNetworkScanHandler(&mockNetworkScanService{})
|
||||
|
||||
// EST handler — uses real Local CA issuer via ESTService
|
||||
estService := service.NewESTService("iss-local", issuerRegistry["iss-local"], auditService, logger)
|
||||
estHandler := handler.NewESTHandler(estService)
|
||||
|
||||
// Create router and register handlers
|
||||
r := router.New()
|
||||
r.RegisterHandlers(
|
||||
@@ -103,6 +107,7 @@ func TestCertificateLifecycle(t *testing.T) {
|
||||
discoveryHandler,
|
||||
networkScanHandler,
|
||||
)
|
||||
r.RegisterESTHandlers(estHandler)
|
||||
|
||||
// Create test server
|
||||
server := httptest.NewServer(r)
|
||||
|
||||
@@ -75,6 +75,10 @@ func setupTestServer(t *testing.T) (*httptest.Server, *mockCertificateRepository
|
||||
discoveryHandler := handler.NewDiscoveryHandler(&mockDiscoveryService{})
|
||||
networkScanHandler := handler.NewNetworkScanHandler(&mockNetworkScanService{})
|
||||
|
||||
// EST handler — uses real Local CA issuer via ESTService
|
||||
estService := service.NewESTService("iss-local", issuerRegistry["iss-local"], auditService, logger)
|
||||
estHandler := handler.NewESTHandler(estService)
|
||||
|
||||
r := router.New()
|
||||
r.RegisterHandlers(
|
||||
certificateHandler,
|
||||
@@ -95,6 +99,7 @@ func setupTestServer(t *testing.T) (*httptest.Server, *mockCertificateRepository
|
||||
discoveryHandler,
|
||||
networkScanHandler,
|
||||
)
|
||||
r.RegisterESTHandlers(estHandler)
|
||||
|
||||
server := httptest.NewServer(r)
|
||||
t.Cleanup(func() { server.Close() })
|
||||
@@ -799,4 +804,3 @@ func TestRevocationEndpoints(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// mockNetworkScanService is defined in lifecycle_test.go (same package)
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
)
|
||||
|
||||
// ESTService implements the EST (RFC 7030) enrollment protocol.
|
||||
// It delegates certificate operations to an existing IssuerConnector and records
|
||||
// enrollment events in the audit trail.
|
||||
type ESTService struct {
|
||||
issuer IssuerConnector
|
||||
issuerID string
|
||||
auditService *AuditService
|
||||
logger *slog.Logger
|
||||
profileID string // optional: constrain enrollments to a specific profile
|
||||
}
|
||||
|
||||
// NewESTService creates a new ESTService for the given issuer connector.
|
||||
func NewESTService(issuerID string, issuer IssuerConnector, auditService *AuditService, logger *slog.Logger) *ESTService {
|
||||
return &ESTService{
|
||||
issuer: issuer,
|
||||
issuerID: issuerID,
|
||||
auditService: auditService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// SetProfileID constrains EST enrollments to a specific certificate profile.
|
||||
func (s *ESTService) SetProfileID(profileID string) {
|
||||
s.profileID = profileID
|
||||
}
|
||||
|
||||
// GetCACerts returns the PEM-encoded CA certificate chain for this EST server.
|
||||
// RFC 7030 Section 4.1: /cacerts distributes the current CA certificates.
|
||||
func (s *ESTService) GetCACerts(ctx context.Context) (string, error) {
|
||||
caPEM, err := s.issuer.GetCACertPEM(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get CA certificates from issuer %s: %w", s.issuerID, err)
|
||||
}
|
||||
if caPEM == "" {
|
||||
return "", fmt.Errorf("issuer %s does not provide CA certificates for EST", s.issuerID)
|
||||
}
|
||||
return caPEM, nil
|
||||
}
|
||||
|
||||
// SimpleEnroll processes an initial enrollment request.
|
||||
// RFC 7030 Section 4.2: /simpleenroll accepts a PKCS#10 CSR and returns a signed cert.
|
||||
func (s *ESTService) SimpleEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error) {
|
||||
return s.processEnrollment(ctx, csrPEM, "est_simple_enroll")
|
||||
}
|
||||
|
||||
// SimpleReEnroll processes a re-enrollment request.
|
||||
// RFC 7030 Section 4.2.2: /simplereenroll is functionally identical to /simpleenroll
|
||||
// but is used when renewing an existing certificate.
|
||||
func (s *ESTService) SimpleReEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error) {
|
||||
return s.processEnrollment(ctx, csrPEM, "est_simple_reenroll")
|
||||
}
|
||||
|
||||
// GetCSRAttrs returns the CSR attributes the server wants clients to include.
|
||||
// RFC 7030 Section 4.5: /csrattrs tells clients what to put in their CSR.
|
||||
// Returns nil if no specific attributes are required.
|
||||
func (s *ESTService) GetCSRAttrs(ctx context.Context) ([]byte, error) {
|
||||
// For now, we don't require specific CSR attributes.
|
||||
// In the future, this could return key type constraints from the profile.
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// processEnrollment handles the common enrollment logic for both simpleenroll and simplereenroll.
|
||||
func (s *ESTService) processEnrollment(ctx context.Context, csrPEM string, auditAction string) (*domain.ESTEnrollResult, error) {
|
||||
// Parse the CSR to extract CN and SANs
|
||||
block, _ := pem.Decode([]byte(csrPEM))
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("invalid CSR PEM")
|
||||
}
|
||||
|
||||
csr, err := x509.ParseCertificateRequest(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse CSR: %w", err)
|
||||
}
|
||||
|
||||
if err := csr.CheckSignature(); err != nil {
|
||||
return nil, fmt.Errorf("CSR signature verification failed: %w", err)
|
||||
}
|
||||
|
||||
commonName := csr.Subject.CommonName
|
||||
if commonName == "" {
|
||||
return nil, fmt.Errorf("CSR must include a Common Name")
|
||||
}
|
||||
|
||||
// Collect SANs
|
||||
var sans []string
|
||||
for _, dns := range csr.DNSNames {
|
||||
sans = append(sans, dns)
|
||||
}
|
||||
for _, ip := range csr.IPAddresses {
|
||||
sans = append(sans, ip.String())
|
||||
}
|
||||
for _, email := range csr.EmailAddresses {
|
||||
sans = append(sans, email)
|
||||
}
|
||||
for _, uri := range csr.URIs {
|
||||
sans = append(sans, uri.String())
|
||||
}
|
||||
|
||||
s.logger.Info("EST enrollment request",
|
||||
"action", auditAction,
|
||||
"common_name", commonName,
|
||||
"sans", strings.Join(sans, ","),
|
||||
"issuer", s.issuerID)
|
||||
|
||||
// Issue the certificate via the configured issuer connector
|
||||
result, err := s.issuer.IssueCertificate(ctx, commonName, sans, csrPEM)
|
||||
if err != nil {
|
||||
s.logger.Error("EST enrollment failed",
|
||||
"action", auditAction,
|
||||
"common_name", commonName,
|
||||
"error", err)
|
||||
return nil, fmt.Errorf("certificate issuance failed: %w", err)
|
||||
}
|
||||
|
||||
// Audit the enrollment
|
||||
if s.auditService != nil {
|
||||
details := map[string]interface{}{
|
||||
"common_name": commonName,
|
||||
"sans": sans,
|
||||
"issuer_id": s.issuerID,
|
||||
"serial": result.Serial,
|
||||
"protocol": "EST",
|
||||
}
|
||||
if s.profileID != "" {
|
||||
details["profile_id"] = s.profileID
|
||||
}
|
||||
_ = s.auditService.RecordEvent(ctx, "est-client", "system", auditAction, "certificate", result.Serial, details)
|
||||
}
|
||||
|
||||
s.logger.Info("EST enrollment successful",
|
||||
"action", auditAction,
|
||||
"common_name", commonName,
|
||||
"serial", result.Serial,
|
||||
"not_after", result.NotAfter)
|
||||
|
||||
return &domain.ESTEnrollResult{
|
||||
CertPEM: result.CertPEM,
|
||||
ChainPEM: result.ChainPEM,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// generateCSRPEM creates a valid ECDSA P-256 CSR for testing.
|
||||
func generateCSRPEM(t *testing.T, cn string, sans []string) string {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("generate key: %v", err)
|
||||
}
|
||||
template := &x509.CertificateRequest{
|
||||
Subject: pkix.Name{CommonName: cn},
|
||||
DNSNames: sans,
|
||||
}
|
||||
csrDER, err := x509.CreateCertificateRequest(rand.Reader, template, key)
|
||||
if err != nil {
|
||||
t.Fatalf("create CSR: %v", err)
|
||||
}
|
||||
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER}))
|
||||
}
|
||||
|
||||
func TestESTService_GetCACerts_Success(t *testing.T) {
|
||||
mockIssuer := &mockIssuerConnector{}
|
||||
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
|
||||
|
||||
caPEM, err := svc.GetCACerts(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if caPEM == "" {
|
||||
t.Error("expected non-empty CA PEM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTService_GetCACerts_IssuerError(t *testing.T) {
|
||||
mockIssuer := &mockIssuerConnector{Err: errors.New("CA unavailable")}
|
||||
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
|
||||
|
||||
_, err := svc.GetCACerts(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "CA unavailable") {
|
||||
t.Errorf("expected error to contain 'CA unavailable', got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTService_SimpleEnroll_Success(t *testing.T) {
|
||||
mockIssuer := &mockIssuerConnector{}
|
||||
auditRepo := newMockAuditRepository()
|
||||
auditSvc := NewAuditService(auditRepo)
|
||||
svc := NewESTService("iss-local", mockIssuer, auditSvc, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
|
||||
|
||||
csrPEM := generateCSRPEM(t, "test.example.com", []string{"test.example.com"})
|
||||
|
||||
result, err := svc.SimpleEnroll(context.Background(), csrPEM)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if result == nil {
|
||||
t.Fatal("expected non-nil result")
|
||||
}
|
||||
if result.CertPEM == "" {
|
||||
t.Error("expected non-empty CertPEM")
|
||||
}
|
||||
|
||||
// Verify audit event was recorded
|
||||
if len(auditRepo.Events) == 0 {
|
||||
t.Error("expected audit event to be recorded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTService_SimpleEnroll_InvalidCSR(t *testing.T) {
|
||||
mockIssuer := &mockIssuerConnector{}
|
||||
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
|
||||
|
||||
_, err := svc.SimpleEnroll(context.Background(), "not-valid-pem")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid CSR")
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTService_SimpleEnroll_MissingCN(t *testing.T) {
|
||||
mockIssuer := &mockIssuerConnector{}
|
||||
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
|
||||
|
||||
csrPEM := generateCSRPEM(t, "", []string{"test.example.com"})
|
||||
|
||||
_, err := svc.SimpleEnroll(context.Background(), csrPEM)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing CN")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "Common Name") {
|
||||
t.Errorf("expected 'Common Name' in error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTService_SimpleEnroll_IssuerError(t *testing.T) {
|
||||
mockIssuer := &mockIssuerConnector{Err: errors.New("issuance failed")}
|
||||
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
|
||||
|
||||
csrPEM := generateCSRPEM(t, "test.example.com", nil)
|
||||
|
||||
_, err := svc.SimpleEnroll(context.Background(), csrPEM)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "issuance failed") {
|
||||
t.Errorf("expected 'issuance failed', got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTService_SimpleReEnroll_Success(t *testing.T) {
|
||||
mockIssuer := &mockIssuerConnector{}
|
||||
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
|
||||
|
||||
csrPEM := generateCSRPEM(t, "renew.example.com", []string{"renew.example.com"})
|
||||
|
||||
result, err := svc.SimpleReEnroll(context.Background(), csrPEM)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if result == nil {
|
||||
t.Fatal("expected non-nil result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTService_GetCSRAttrs_Empty(t *testing.T) {
|
||||
mockIssuer := &mockIssuerConnector{}
|
||||
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
|
||||
|
||||
attrs, err := svc.GetCSRAttrs(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if attrs != nil {
|
||||
t.Errorf("expected nil attrs, got %v", attrs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTService_SimpleEnroll_WithProfile(t *testing.T) {
|
||||
mockIssuer := &mockIssuerConnector{}
|
||||
auditRepo := newMockAuditRepository()
|
||||
auditSvc := NewAuditService(auditRepo)
|
||||
svc := NewESTService("iss-local", mockIssuer, auditSvc, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
|
||||
svc.SetProfileID("profile-wifi-client")
|
||||
|
||||
csrPEM := generateCSRPEM(t, "device.example.com", nil)
|
||||
|
||||
result, err := svc.SimpleEnroll(context.Background(), csrPEM)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if result == nil {
|
||||
t.Fatal("expected non-nil result")
|
||||
}
|
||||
|
||||
// Verify audit event includes profile_id
|
||||
if len(auditRepo.Events) == 0 {
|
||||
t.Fatal("expected audit event")
|
||||
}
|
||||
lastEvent := auditRepo.Events[len(auditRepo.Events)-1]
|
||||
if lastEvent.Details == nil {
|
||||
t.Fatal("expected audit details")
|
||||
}
|
||||
}
|
||||
@@ -95,3 +95,8 @@ func (a *IssuerConnectorAdapter) SignOCSPResponse(ctx context.Context, req OCSPS
|
||||
NextUpdate: req.NextUpdate,
|
||||
})
|
||||
}
|
||||
|
||||
// GetCACertPEM delegates to the underlying connector.
|
||||
func (a *IssuerConnectorAdapter) GetCACertPEM(ctx context.Context) (string, error) {
|
||||
return a.connector.GetCACertPEM(ctx)
|
||||
}
|
||||
|
||||
@@ -96,6 +96,10 @@ func (m *mockConnectorLayerIssuer) SignOCSPResponse(ctx context.Context, req iss
|
||||
return []byte("mock-ocsp-response"), nil
|
||||
}
|
||||
|
||||
func (m *mockConnectorLayerIssuer) GetCACertPEM(ctx context.Context) (string, error) {
|
||||
return "-----BEGIN CERTIFICATE-----\nmock-ca-cert\n-----END CERTIFICATE-----", nil
|
||||
}
|
||||
|
||||
// Tests for IssueCertificate
|
||||
|
||||
func TestIssuerConnectorAdapter_IssueCertificate_Success(t *testing.T) {
|
||||
|
||||
@@ -76,7 +76,7 @@ func (s *NetworkScanService) CreateTarget(ctx context.Context, target *domain.Ne
|
||||
}
|
||||
}
|
||||
if len(target.Ports) == 0 {
|
||||
target.Ports = []int{443}
|
||||
target.Ports = []int64{443}
|
||||
}
|
||||
if target.ScanIntervalHours == 0 {
|
||||
target.ScanIntervalHours = 6
|
||||
@@ -276,7 +276,7 @@ func (s *NetworkScanService) scanTarget(ctx context.Context, target *domain.Netw
|
||||
}
|
||||
|
||||
// expandEndpoints converts CIDR ranges and ports into a list of "ip:port" endpoints.
|
||||
func (s *NetworkScanService) expandEndpoints(cidrs []string, ports []int) []string {
|
||||
func (s *NetworkScanService) expandEndpoints(cidrs []string, ports []int64) []string {
|
||||
var endpoints []string
|
||||
|
||||
for _, cidr := range cidrs {
|
||||
|
||||
@@ -123,7 +123,7 @@ func TestNetworkScanService_CreateTarget(t *testing.T) {
|
||||
target, err := svc.CreateTarget(context.Background(), &domain.NetworkScanTarget{
|
||||
Name: "Test Network",
|
||||
CIDRs: []string{"10.0.0.0/24"},
|
||||
Ports: []int{443, 8443},
|
||||
Ports: []int64{443, 8443},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTarget failed: %v", err)
|
||||
@@ -221,7 +221,7 @@ func TestNetworkScanService_ListTargets(t *testing.T) {
|
||||
|
||||
func TestExpandEndpoints(t *testing.T) {
|
||||
svc := &NetworkScanService{}
|
||||
endpoints := svc.expandEndpoints([]string{"192.168.1.1"}, []int{443, 8443})
|
||||
endpoints := svc.expandEndpoints([]string{"192.168.1.1"}, []int64{443, 8443})
|
||||
if len(endpoints) != 2 {
|
||||
t.Errorf("expected 2 endpoints, got %d: %v", len(endpoints), endpoints)
|
||||
}
|
||||
|
||||
@@ -44,6 +44,8 @@ type IssuerConnector interface {
|
||||
GenerateCRL(ctx context.Context, revokedCerts []CRLEntry) ([]byte, error)
|
||||
// SignOCSPResponse signs an OCSP response for the given certificate serial.
|
||||
SignOCSPResponse(ctx context.Context, req OCSPSignRequest) ([]byte, error)
|
||||
// GetCACertPEM returns the PEM-encoded CA certificate chain for this issuer.
|
||||
GetCACertPEM(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
// IssuanceResult holds the result of a certificate issuance or renewal operation.
|
||||
|
||||
@@ -187,7 +187,7 @@ func TestGetJobStats_Empty(t *testing.T) {
|
||||
|
||||
func TestGetJobStats_WithData(t *testing.T) {
|
||||
svc, _, jobRepo, _ := newTestStatsService()
|
||||
completedAt := time.Now().Add(-1 * time.Hour)
|
||||
completedAt := time.Now()
|
||||
jobRepo.AddJob(&domain.Job{ID: "j-1", Status: domain.JobStatusCompleted, CompletedAt: &completedAt})
|
||||
jobRepo.AddJob(&domain.Job{ID: "j-2", Status: domain.JobStatusFailed, CompletedAt: &completedAt})
|
||||
|
||||
|
||||
@@ -634,6 +634,13 @@ func (m *mockIssuerConnector) SignOCSPResponse(ctx context.Context, req OCSPSign
|
||||
return []byte("mock-ocsp-response"), nil
|
||||
}
|
||||
|
||||
func (m *mockIssuerConnector) GetCACertPEM(ctx context.Context) (string, error) {
|
||||
if m.Err != nil {
|
||||
return "", m.Err
|
||||
}
|
||||
return "-----BEGIN CERTIFICATE-----\nmock-ca-cert\n-----END CERTIFICATE-----", nil
|
||||
}
|
||||
|
||||
// Constructor functions for mocks
|
||||
|
||||
func newMockCertificateRepository() *mockCertRepo {
|
||||
|
||||
@@ -214,3 +214,113 @@ INSERT INTO agent_group_members (agent_group_id, agent_id, membership_type, crea
|
||||
('ag-manual', 'ag-web-staging', 'include', NOW()),
|
||||
('ag-manual', 'ag-iis-prod', 'exclude', NOW())
|
||||
ON CONFLICT (agent_group_id, agent_id) DO NOTHING;
|
||||
|
||||
-- Sentinel agent for network-discovered certificates (created by server on startup, seed for demo)
|
||||
INSERT INTO agents (id, name, hostname, status, last_heartbeat_at, registered_at, api_key_hash, os, architecture, ip_address, version) VALUES
|
||||
('server-scanner', 'Network Scanner (Server-Side)', 'certctl-server', 'online', NOW(), NOW() - INTERVAL '30 days', 'sentinel_no_auth', 'linux', 'amd64', '127.0.0.1', '2.0.5')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Discovery Scans — show recent scan activity from agents
|
||||
INSERT INTO discovery_scans (id, agent_id, directories, certificates_found, certificates_new, errors_count, scan_duration_ms, started_at, completed_at) VALUES
|
||||
('ds-web-prod-01', 'ag-web-prod', '{/etc/nginx/ssl,/etc/pki/tls/certs}', 4, 2, 0, 1250, NOW() - INTERVAL '3 hours', NOW() - INTERVAL '3 hours' + INTERVAL '1 second'),
|
||||
('ds-data-prod-01', 'ag-data-prod', '{/etc/nginx/ssl,/opt/certs}', 3, 1, 0, 980, NOW() - INTERVAL '2 hours', NOW() - INTERVAL '2 hours' + INTERVAL '1 second'),
|
||||
('ds-network-scan-01','server-scanner', '{network-scan}', 3, 3, 0, 4500, NOW() - INTERVAL '1 hour', NOW() - INTERVAL '1 hour' + INTERVAL '5 seconds')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Discovered Certificates — populate discovery triage page with realistic mix
|
||||
INSERT INTO discovered_certificates (id, fingerprint_sha256, common_name, sans, serial_number, issuer_dn, subject_dn, not_before, not_after, key_algorithm, key_size, is_ca, pem_data, source_path, source_format, agent_id, discovery_scan_id, managed_certificate_id, status, first_seen_at, last_seen_at) VALUES
|
||||
-- Unmanaged: found on filesystem, not yet claimed
|
||||
('dc-unmanaged-01', 'sha256:f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0',
|
||||
'internal-service.example.com', ARRAY['internal-service.example.com', 'internal-svc.local'],
|
||||
'1A:2B:3C:4D:5E:6F:00:11', 'CN=Example Internal CA,O=Example Corp',
|
||||
'CN=internal-service.example.com,O=Example Corp', NOW() - INTERVAL '200 days', NOW() + INTERVAL '20 days',
|
||||
'RSA', 2048, false, '', '/etc/pki/tls/certs/internal-svc.pem', 'PEM',
|
||||
'ag-web-prod', 'ds-web-prod-01', NULL, 'Unmanaged',
|
||||
NOW() - INTERVAL '7 days', NOW() - INTERVAL '3 hours'),
|
||||
|
||||
('dc-unmanaged-02', 'sha256:a9b8c7d6e5f4a3b2c1d0e9f8a7b6c5d4e3f2a1b0',
|
||||
'monitoring.internal.example.com', ARRAY['monitoring.internal.example.com', 'prometheus.internal.example.com'],
|
||||
'2B:3C:4D:5E:6F:7A:00:22', 'CN=Let''s Encrypt Authority X3,O=Let''s Encrypt',
|
||||
'CN=monitoring.internal.example.com', NOW() - INTERVAL '60 days', NOW() + INTERVAL '30 days',
|
||||
'ECDSA', 256, false, '', '/opt/certs/monitoring.pem', 'PEM',
|
||||
'ag-data-prod', 'ds-data-prod-01', NULL, 'Unmanaged',
|
||||
NOW() - INTERVAL '5 days', NOW() - INTERVAL '2 hours'),
|
||||
|
||||
('dc-unmanaged-03', 'sha256:1122334455667788990011223344556677889900',
|
||||
'db-replication.example.com', ARRAY['db-replication.example.com'],
|
||||
'3C:4D:5E:6F:7A:8B:00:33', 'CN=Example Internal CA,O=Example Corp',
|
||||
'CN=db-replication.example.com,O=Example Corp', NOW() - INTERVAL '300 days', NOW() - INTERVAL '10 days',
|
||||
'RSA', 4096, false, '', '/etc/pki/tls/certs/db-repl.pem', 'PEM',
|
||||
'ag-web-prod', 'ds-web-prod-01', NULL, 'Unmanaged',
|
||||
NOW() - INTERVAL '7 days', NOW() - INTERVAL '3 hours'),
|
||||
|
||||
-- Managed: already linked to managed certificates
|
||||
('dc-managed-01', 'sha256:ab12cd34ef56ab12cd34ef56ab12cd34ef56ab12',
|
||||
'api.example.com', ARRAY['api.example.com', 'api-v2.example.com'],
|
||||
'0A:1B:2C:3D:4E:5F:00:01', 'CN=CertCtl Demo CA',
|
||||
'CN=api.example.com', NOW() - INTERVAL '15 days', NOW() + INTERVAL '75 days',
|
||||
'ECDSA', 256, false, '', '/etc/nginx/ssl/cert.pem', 'PEM',
|
||||
'ag-web-prod', 'ds-web-prod-01', 'mc-api-prod', 'Managed',
|
||||
NOW() - INTERVAL '15 days', NOW() - INTERVAL '3 hours'),
|
||||
|
||||
('dc-managed-02', 'sha256:cd34ef56ab12cd34ef56ab12cd34ef56ab12cd34',
|
||||
'data.example.com', ARRAY['data.example.com', 'analytics.example.com'],
|
||||
'0A:1B:2C:3D:4E:5F:00:06', 'CN=CertCtl Demo CA',
|
||||
'CN=data.example.com', NOW() - INTERVAL '35 days', NOW() + INTERVAL '55 days',
|
||||
'ECDSA', 256, false, '', '/etc/nginx/ssl/cert.pem', 'PEM',
|
||||
'ag-data-prod', 'ds-data-prod-01', 'mc-data-prod', 'Managed',
|
||||
NOW() - INTERVAL '35 days', NOW() - INTERVAL '2 hours'),
|
||||
|
||||
-- Dismissed: triaged and explicitly ignored
|
||||
('dc-dismissed-01', 'sha256:9988776655443322110099887766554433221100',
|
||||
'test-selfsigned.local', ARRAY['test-selfsigned.local', 'localhost'],
|
||||
'00:00:00:00:00:00:FF:01', 'CN=test-selfsigned.local',
|
||||
'CN=test-selfsigned.local', NOW() - INTERVAL '365 days', NOW() + INTERVAL '365 days',
|
||||
'RSA', 2048, false, '', '/etc/pki/tls/certs/test.pem', 'PEM',
|
||||
'ag-web-prod', 'ds-web-prod-01', NULL, 'Dismissed',
|
||||
NOW() - INTERVAL '7 days', NOW() - INTERVAL '3 hours'),
|
||||
|
||||
-- Network-discovered certs (from server-scanner sentinel agent)
|
||||
('dc-network-01', 'sha256:net1aabbccdd11223344556677889900aabbccdd',
|
||||
'switch-mgmt.example.com', ARRAY['switch-mgmt.example.com'],
|
||||
'5E:6F:7A:8B:9C:0D:00:44', 'CN=Example Network CA,O=Example Corp',
|
||||
'CN=switch-mgmt.example.com,O=Example Corp', NOW() - INTERVAL '180 days', NOW() + INTERVAL '5 days',
|
||||
'RSA', 2048, false, '', '10.0.1.50:443', 'TLS',
|
||||
'server-scanner', 'ds-network-scan-01', NULL, 'Unmanaged',
|
||||
NOW() - INTERVAL '1 hour', NOW() - INTERVAL '1 hour'),
|
||||
|
||||
('dc-network-02', 'sha256:net2eeff00112233445566778899aabbccddeeff',
|
||||
'printer.example.com', ARRAY['printer.example.com'],
|
||||
'6F:7A:8B:9C:0D:1E:00:55', 'CN=printer.example.com',
|
||||
'CN=printer.example.com', NOW() - INTERVAL '400 days', NOW() - INTERVAL '30 days',
|
||||
'RSA', 1024, false, '', '10.0.2.100:443', 'TLS',
|
||||
'server-scanner', 'ds-network-scan-01', NULL, 'Unmanaged',
|
||||
NOW() - INTERVAL '1 hour', NOW() - INTERVAL '1 hour'),
|
||||
|
||||
('dc-network-03', 'sha256:net3001122334455667788990011223344556677',
|
||||
'vpn-appliance.example.com', ARRAY['vpn-appliance.example.com', '10.0.1.1'],
|
||||
'7A:8B:9C:0D:1E:2F:00:66', 'CN=Fortinet CA,O=Fortinet',
|
||||
'CN=vpn-appliance.example.com', NOW() - INTERVAL '90 days', NOW() + INTERVAL '275 days',
|
||||
'RSA', 2048, false, '', '10.0.1.1:443', 'TLS',
|
||||
'server-scanner', 'ds-network-scan-01', NULL, 'Unmanaged',
|
||||
NOW() - INTERVAL '1 hour', NOW() - INTERVAL '1 hour')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Jobs — add AwaitingApproval jobs for approval workflow demo
|
||||
INSERT INTO jobs (id, type, certificate_id, target_id, agent_id, status, attempts, max_attempts, last_error, scheduled_at, created_at) VALUES
|
||||
('job-approval-01', 'renewal', 'mc-auth-prod', NULL, 'ag-web-prod', 'AwaitingApproval', 0, 3, NULL, NOW() - INTERVAL '1 hour', NOW() - INTERVAL '1 hour'),
|
||||
('job-approval-02', 'renewal', 'mc-pay-prod', NULL, 'ag-web-prod', 'AwaitingApproval', 0, 3, NULL, NOW() - INTERVAL '30 minutes', NOW() - INTERVAL '30 minutes')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Update network scan targets with last_scan data so GUI shows recent activity
|
||||
UPDATE network_scan_targets SET
|
||||
last_scan_at = NOW() - INTERVAL '1 hour',
|
||||
last_scan_duration_ms = 4500,
|
||||
last_scan_certs_found = 3
|
||||
WHERE id = 'nst-dc1-web';
|
||||
|
||||
UPDATE network_scan_targets SET
|
||||
last_scan_at = NOW() - INTERVAL '2 hours',
|
||||
last_scan_duration_ms = 8200,
|
||||
last_scan_certs_found = 0
|
||||
WHERE id = 'nst-dc2-apps';
|
||||
|
||||
@@ -61,6 +61,18 @@ import {
|
||||
getJobTrends,
|
||||
getIssuanceRate,
|
||||
getMetrics,
|
||||
getDiscoveredCertificates,
|
||||
getDiscoveredCertificate,
|
||||
claimDiscoveredCertificate,
|
||||
dismissDiscoveredCertificate,
|
||||
getDiscoveryScans,
|
||||
getDiscoverySummary,
|
||||
getNetworkScanTargets,
|
||||
getNetworkScanTarget,
|
||||
createNetworkScanTarget,
|
||||
updateNetworkScanTarget,
|
||||
deleteNetworkScanTarget,
|
||||
triggerNetworkScan,
|
||||
} from './client';
|
||||
|
||||
// Mock global fetch
|
||||
@@ -686,4 +698,104 @@ describe('API Client', () => {
|
||||
expect(result.status).toBe('ok');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Discovery ────────────────────────────────────
|
||||
|
||||
describe('Discovery', () => {
|
||||
it('getDiscoveredCertificates calls with params', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ data: [], total: 0, page: 1, per_page: 50 }));
|
||||
await getDiscoveredCertificates({ status: 'Unmanaged' });
|
||||
expect(mockFetch.mock.calls[0][0]).toContain('/api/v1/discovered-certificates');
|
||||
expect(mockFetch.mock.calls[0][0]).toContain('status=Unmanaged');
|
||||
});
|
||||
|
||||
it('getDiscoveredCertificate calls with id', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ id: 'dc-1', common_name: 'test.example.com' }));
|
||||
const result = await getDiscoveredCertificate('dc-1');
|
||||
expect(mockFetch.mock.calls[0][0]).toBe('/api/v1/discovered-certificates/dc-1');
|
||||
expect(result.common_name).toBe('test.example.com');
|
||||
});
|
||||
|
||||
it('claimDiscoveredCertificate sends POST with managed cert id', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ message: 'claimed' }));
|
||||
await claimDiscoveredCertificate('dc-1', 'mc-api-prod');
|
||||
const [url, init] = mockFetch.mock.calls[0];
|
||||
expect(url).toBe('/api/v1/discovered-certificates/dc-1/claim');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(JSON.parse(init.body)).toEqual({ managed_certificate_id: 'mc-api-prod' });
|
||||
});
|
||||
|
||||
it('dismissDiscoveredCertificate sends POST', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ message: 'dismissed' }));
|
||||
await dismissDiscoveredCertificate('dc-1');
|
||||
const [url, init] = mockFetch.mock.calls[0];
|
||||
expect(url).toBe('/api/v1/discovered-certificates/dc-1/dismiss');
|
||||
expect(init.method).toBe('POST');
|
||||
});
|
||||
|
||||
it('getDiscoveryScans calls endpoint', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ data: [], total: 0, page: 1, per_page: 50 }));
|
||||
await getDiscoveryScans();
|
||||
expect(mockFetch.mock.calls[0][0]).toContain('/api/v1/discovery-scans');
|
||||
});
|
||||
|
||||
it('getDiscoverySummary calls endpoint', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ Unmanaged: 5, Managed: 3, Dismissed: 1 }));
|
||||
const result = await getDiscoverySummary();
|
||||
expect(mockFetch.mock.calls[0][0]).toBe('/api/v1/discovery-summary');
|
||||
expect(result.Unmanaged).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Network Scan Targets ────────────────────────
|
||||
|
||||
describe('Network Scan Targets', () => {
|
||||
it('getNetworkScanTargets calls endpoint', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ data: [], total: 0, page: 1, per_page: 50 }));
|
||||
await getNetworkScanTargets();
|
||||
expect(mockFetch.mock.calls[0][0]).toContain('/api/v1/network-scan-targets');
|
||||
});
|
||||
|
||||
it('getNetworkScanTarget calls with id', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ id: 'nst-1', name: 'DMZ' }));
|
||||
const result = await getNetworkScanTarget('nst-1');
|
||||
expect(mockFetch.mock.calls[0][0]).toBe('/api/v1/network-scan-targets/nst-1');
|
||||
expect(result.name).toBe('DMZ');
|
||||
});
|
||||
|
||||
it('createNetworkScanTarget sends POST', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ id: 'nst-new', name: 'Production' }));
|
||||
await createNetworkScanTarget({ name: 'Production', cidrs: ['10.0.0.0/24'], ports: [443] });
|
||||
const [url, init] = mockFetch.mock.calls[0];
|
||||
expect(url).toBe('/api/v1/network-scan-targets');
|
||||
expect(init.method).toBe('POST');
|
||||
const body = JSON.parse(init.body);
|
||||
expect(body.name).toBe('Production');
|
||||
expect(body.cidrs).toEqual(['10.0.0.0/24']);
|
||||
});
|
||||
|
||||
it('updateNetworkScanTarget sends PUT', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ id: 'nst-1', enabled: false }));
|
||||
await updateNetworkScanTarget('nst-1', { enabled: false });
|
||||
const [url, init] = mockFetch.mock.calls[0];
|
||||
expect(url).toBe('/api/v1/network-scan-targets/nst-1');
|
||||
expect(init.method).toBe('PUT');
|
||||
});
|
||||
|
||||
it('deleteNetworkScanTarget sends DELETE', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({}, 204));
|
||||
await deleteNetworkScanTarget('nst-1');
|
||||
const [url, init] = mockFetch.mock.calls[0];
|
||||
expect(url).toBe('/api/v1/network-scan-targets/nst-1');
|
||||
expect(init.method).toBe('DELETE');
|
||||
});
|
||||
|
||||
it('triggerNetworkScan sends POST to scan endpoint', async () => {
|
||||
mockFetch.mockReturnValueOnce(mockJsonResponse({ message: 'scan triggered' }));
|
||||
await triggerNetworkScan('nst-1');
|
||||
const [url, init] = mockFetch.mock.calls[0];
|
||||
expect(url).toBe('/api/v1/network-scan-targets/nst-1/scan');
|
||||
expect(init.method).toBe('POST');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Certificate, CertificateVersion, Agent, Job, Notification, AuditEvent, PolicyRule, PolicyViolation, Issuer, Target, CertificateProfile, Owner, Team, AgentGroup, PaginatedResponse, DashboardSummary, CertificateStatusCount, ExpirationBucket, JobTrendDataPoint, IssuanceRateDataPoint, MetricsResponse } from './types';
|
||||
import type { Certificate, CertificateVersion, Agent, Job, Notification, AuditEvent, PolicyRule, PolicyViolation, Issuer, Target, CertificateProfile, Owner, Team, AgentGroup, PaginatedResponse, DashboardSummary, CertificateStatusCount, ExpirationBucket, JobTrendDataPoint, IssuanceRateDataPoint, MetricsResponse, DiscoveredCertificate, DiscoveryScan, DiscoverySummary, NetworkScanTarget } from './types';
|
||||
|
||||
const BASE = '/api/v1';
|
||||
|
||||
@@ -42,6 +42,7 @@ async function fetchJSON<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
}
|
||||
throw new Error(errorMsg || `HTTP ${res.status}`);
|
||||
}
|
||||
if (res.status === 204) return {} as T;
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -257,6 +258,53 @@ export const approveRenewal = (jobId: string) =>
|
||||
export const rejectRenewal = (jobId: string, reason: string) =>
|
||||
fetchJSON<{ message: string }>(`${BASE}/jobs/${jobId}/reject`, { method: 'POST', body: JSON.stringify({ reason }) });
|
||||
|
||||
// Discovery
|
||||
export const getDiscoveredCertificates = (params: Record<string, string> = {}) => {
|
||||
const qs = new URLSearchParams({ page: '1', per_page: '50', ...params }).toString();
|
||||
return fetchJSON<PaginatedResponse<DiscoveredCertificate>>(`${BASE}/discovered-certificates?${qs}`);
|
||||
};
|
||||
|
||||
export const getDiscoveredCertificate = (id: string) =>
|
||||
fetchJSON<DiscoveredCertificate>(`${BASE}/discovered-certificates/${id}`);
|
||||
|
||||
export const claimDiscoveredCertificate = (id: string, managedCertificateId: string) =>
|
||||
fetchJSON<{ message: string }>(`${BASE}/discovered-certificates/${id}/claim`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ managed_certificate_id: managedCertificateId }),
|
||||
});
|
||||
|
||||
export const dismissDiscoveredCertificate = (id: string) =>
|
||||
fetchJSON<{ message: string }>(`${BASE}/discovered-certificates/${id}/dismiss`, { method: 'POST' });
|
||||
|
||||
export const getDiscoveryScans = (params: Record<string, string> = {}) => {
|
||||
const qs = new URLSearchParams({ page: '1', per_page: '50', ...params }).toString();
|
||||
return fetchJSON<PaginatedResponse<DiscoveryScan>>(`${BASE}/discovery-scans?${qs}`);
|
||||
};
|
||||
|
||||
export const getDiscoverySummary = () =>
|
||||
fetchJSON<DiscoverySummary>(`${BASE}/discovery-summary`);
|
||||
|
||||
// Network Scan Targets
|
||||
export const getNetworkScanTargets = (params: Record<string, string> = {}) => {
|
||||
const qs = new URLSearchParams({ page: '1', per_page: '50', ...params }).toString();
|
||||
return fetchJSON<PaginatedResponse<NetworkScanTarget>>(`${BASE}/network-scan-targets?${qs}`);
|
||||
};
|
||||
|
||||
export const getNetworkScanTarget = (id: string) =>
|
||||
fetchJSON<NetworkScanTarget>(`${BASE}/network-scan-targets/${id}`);
|
||||
|
||||
export const createNetworkScanTarget = (data: Partial<NetworkScanTarget>) =>
|
||||
fetchJSON<NetworkScanTarget>(`${BASE}/network-scan-targets`, { method: 'POST', body: JSON.stringify(data) });
|
||||
|
||||
export const updateNetworkScanTarget = (id: string, data: Partial<NetworkScanTarget>) =>
|
||||
fetchJSON<NetworkScanTarget>(`${BASE}/network-scan-targets/${id}`, { method: 'PUT', body: JSON.stringify(data) });
|
||||
|
||||
export const deleteNetworkScanTarget = (id: string) =>
|
||||
fetchJSON<{ message: string }>(`${BASE}/network-scan-targets/${id}`, { method: 'DELETE' });
|
||||
|
||||
export const triggerNetworkScan = (id: string) =>
|
||||
fetchJSON<{ message: string }>(`${BASE}/network-scan-targets/${id}/scan`, { method: 'POST' });
|
||||
|
||||
// Stats
|
||||
export const getDashboardSummary = () =>
|
||||
fetchJSON<DashboardSummary>(`${BASE}/stats/summary`);
|
||||
|
||||
@@ -244,6 +244,67 @@ export interface IssuanceRateDataPoint {
|
||||
issued_count: number;
|
||||
}
|
||||
|
||||
// Discovery types
|
||||
export interface DiscoveredCertificate {
|
||||
id: string;
|
||||
fingerprint_sha256: string;
|
||||
common_name: string;
|
||||
sans: string[];
|
||||
serial_number: string;
|
||||
issuer_dn: string;
|
||||
subject_dn: string;
|
||||
not_before?: string;
|
||||
not_after?: string;
|
||||
key_algorithm: string;
|
||||
key_size: number;
|
||||
is_ca: boolean;
|
||||
source_path: string;
|
||||
source_format: string;
|
||||
agent_id: string;
|
||||
discovery_scan_id?: string;
|
||||
managed_certificate_id?: string;
|
||||
status: string;
|
||||
first_seen_at: string;
|
||||
last_seen_at: string;
|
||||
dismissed_at?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface DiscoveryScan {
|
||||
id: string;
|
||||
agent_id: string;
|
||||
directories: string[];
|
||||
certificates_found: number;
|
||||
certificates_new: number;
|
||||
errors_count: number;
|
||||
scan_duration_ms: number;
|
||||
started_at: string;
|
||||
completed_at?: string;
|
||||
}
|
||||
|
||||
export interface DiscoverySummary {
|
||||
Unmanaged: number;
|
||||
Managed: number;
|
||||
Dismissed: number;
|
||||
}
|
||||
|
||||
// Network scan types
|
||||
export interface NetworkScanTarget {
|
||||
id: string;
|
||||
name: string;
|
||||
cidrs: string[];
|
||||
ports: number[];
|
||||
enabled: boolean;
|
||||
scan_interval_hours: number;
|
||||
timeout_ms: number;
|
||||
last_scan_at?: string;
|
||||
last_scan_duration_ms?: number;
|
||||
last_scan_certs_found?: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface MetricsResponse {
|
||||
gauge: {
|
||||
certificate_total: number;
|
||||
|
||||
|
After Width: | Height: | Size: 755 KiB |
@@ -7,10 +7,10 @@ export default function AuthGate({ children }: { children: ReactNode }) {
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-900 flex items-center justify-center">
|
||||
<div className="min-h-screen bg-page flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold text-blue-400 mb-2">certctl</h1>
|
||||
<p className="text-sm text-slate-400">Connecting...</p>
|
||||
<h1 className="text-2xl font-bold text-brand-500 mb-2">certctl</h1>
|
||||
<p className="text-sm text-ink-muted">Connecting...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -20,7 +20,7 @@ interface DataTableProps<T> {
|
||||
export default function DataTable<T>({ columns, data, onRowClick, emptyMessage, isLoading, keyField = 'id', selectable, selectedKeys, onSelectionChange }: DataTableProps<T>) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16 text-slate-400">
|
||||
<div className="flex items-center justify-center py-16 text-ink-muted">
|
||||
<svg className="animate-spin h-5 w-5 mr-3" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
@@ -32,7 +32,7 @@ export default function DataTable<T>({ columns, data, onRowClick, emptyMessage,
|
||||
|
||||
if (!data.length) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16 text-slate-500">
|
||||
<div className="flex items-center justify-center py-16 text-ink-faint">
|
||||
{emptyMessage || 'No data found'}
|
||||
</div>
|
||||
);
|
||||
@@ -62,19 +62,19 @@ export default function DataTable<T>({ columns, data, onRowClick, emptyMessage,
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b-2 border-slate-700">
|
||||
<tr className="border-b-2 border-surface-border bg-surface-muted">
|
||||
{selectable && (
|
||||
<th className="px-3 py-3 w-10">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allSelected || false}
|
||||
onChange={toggleAll}
|
||||
className="rounded border-slate-600 bg-slate-900 text-blue-600 focus:ring-blue-500 focus:ring-offset-0 cursor-pointer"
|
||||
className="rounded border-surface-border bg-white text-brand-500 focus:ring-brand-500 focus:ring-offset-0 cursor-pointer"
|
||||
/>
|
||||
</th>
|
||||
)}
|
||||
{columns.map(col => (
|
||||
<th key={col.key} className={`px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider ${col.className || ''}`}>
|
||||
<th key={col.key} className={`px-4 py-3 text-left text-xs font-semibold text-ink-muted uppercase tracking-wider ${col.className || ''}`}>
|
||||
{col.label}
|
||||
</th>
|
||||
))}
|
||||
@@ -88,7 +88,7 @@ export default function DataTable<T>({ columns, data, onRowClick, emptyMessage,
|
||||
<tr
|
||||
key={rowKey}
|
||||
onClick={() => onRowClick?.(item)}
|
||||
className={`border-b border-slate-700/50 transition-colors hover:bg-blue-500/5 ${onRowClick ? 'cursor-pointer' : ''} ${isSelected ? 'bg-blue-500/10' : ''}`}
|
||||
className={`border-b border-surface-border/50 transition-colors hover:bg-surface-muted ${onRowClick ? 'cursor-pointer' : ''} ${isSelected ? 'bg-brand-50' : ''}`}
|
||||
>
|
||||
{selectable && (
|
||||
<td className="px-3 py-3 w-10">
|
||||
@@ -97,12 +97,12 @@ export default function DataTable<T>({ columns, data, onRowClick, emptyMessage,
|
||||
checked={isSelected || false}
|
||||
onChange={(e) => { e.stopPropagation(); toggleOne(rowKey); }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="rounded border-slate-600 bg-slate-900 text-blue-600 focus:ring-blue-500 focus:ring-offset-0 cursor-pointer"
|
||||
className="rounded border-surface-border bg-white text-brand-500 focus:ring-brand-500 focus:ring-offset-0 cursor-pointer"
|
||||
/>
|
||||
</td>
|
||||
)}
|
||||
{columns.map(col => (
|
||||
<td key={col.key} className={`px-4 py-3 ${col.className || ''}`}>
|
||||
<td key={col.key} className={`px-4 py-3 text-ink ${col.className || ''}`}>
|
||||
{col.render(item)}
|
||||
</td>
|
||||
))}
|
||||
|
||||
@@ -26,10 +26,10 @@ export default class ErrorBoundary extends Component<Props, State> {
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-slate-900">
|
||||
<div className="flex items-center justify-center min-h-screen bg-page">
|
||||
<div className="text-center p-8">
|
||||
<h1 className="text-xl font-semibold text-red-400 mb-2">Something went wrong</h1>
|
||||
<p className="text-sm text-slate-400 mb-4">
|
||||
<h1 className="text-xl font-semibold text-red-700 mb-2">Something went wrong</h1>
|
||||
<p className="text-sm text-ink-muted mb-4">
|
||||
{this.state.error?.message || 'An unexpected error occurred'}
|
||||
</p>
|
||||
<button
|
||||
@@ -37,7 +37,7 @@ export default class ErrorBoundary extends Component<Props, State> {
|
||||
this.setState({ hasError: false, error: null });
|
||||
window.location.reload();
|
||||
}}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-500"
|
||||
className="px-4 py-2 bg-brand-500 text-white rounded text-sm hover:bg-brand-600"
|
||||
>
|
||||
Reload Page
|
||||
</button>
|
||||
|
||||
@@ -5,12 +5,12 @@ interface ErrorStateProps {
|
||||
|
||||
export default function ErrorState({ error, onRetry }: ErrorStateProps) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-slate-400">
|
||||
<svg className="w-12 h-12 text-red-400 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<div className="flex flex-col items-center justify-center py-16 text-ink-muted">
|
||||
<svg className="w-12 h-12 text-red-700 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
|
||||
</svg>
|
||||
<p className="text-sm mb-2">Failed to load data</p>
|
||||
<p className="text-xs text-slate-500 mb-4">{error.message}</p>
|
||||
<p className="text-sm mb-2 text-ink">Failed to load data</p>
|
||||
<p className="text-xs text-ink-faint mb-4">{error.message}</p>
|
||||
{onRetry && (
|
||||
<button onClick={onRetry} className="btn btn-primary text-xs">
|
||||
Retry
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NavLink, Outlet } from 'react-router-dom';
|
||||
import { useAuth } from './AuthProvider';
|
||||
import logo from '../assets/certctl-logo.png';
|
||||
|
||||
const nav = [
|
||||
{ to: '/', label: 'Dashboard', icon: 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-4 0h4' },
|
||||
@@ -15,13 +16,15 @@ const nav = [
|
||||
{ to: '/owners', label: 'Owners', icon: 'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z' },
|
||||
{ to: '/teams', label: 'Teams', icon: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z' },
|
||||
{ to: '/agent-groups', label: 'Agent Groups', icon: 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10 M9 3v2m6-2v2' },
|
||||
{ to: '/discovery', label: 'Discovery', icon: 'M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z' },
|
||||
{ to: '/network-scans', label: 'Network Scans', icon: 'M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z M9 12l2 2 4-4' },
|
||||
{ to: '/short-lived', label: 'Short-Lived', icon: 'M13 10V3L4 14h7v7l9-11h-7z' },
|
||||
{ to: '/audit', label: 'Audit Trail', icon: 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z' },
|
||||
];
|
||||
|
||||
function Icon({ d }: { d: string }) {
|
||||
return (
|
||||
<svg className="w-5 h-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<svg className="w-[18px] h-[18px] shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d={d} />
|
||||
</svg>
|
||||
);
|
||||
@@ -32,23 +35,30 @@ export default function Layout() {
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden">
|
||||
{/* Sidebar */}
|
||||
<aside className="w-64 bg-slate-800 border-r border-slate-700 flex flex-col">
|
||||
<div className="p-6 border-b border-slate-700">
|
||||
<h1 className="text-xl font-bold text-blue-400">certctl</h1>
|
||||
<p className="text-xs text-slate-400 uppercase tracking-wider mt-1">Certificate Control Plane</p>
|
||||
{/* Sidebar — deep teal from logo */}
|
||||
<aside className="w-60 bg-sidebar flex flex-col shadow-xl">
|
||||
{/* Logo — large and prominent */}
|
||||
<div className="px-4 pt-5 pb-4 flex flex-col items-center gap-2">
|
||||
<div className="bg-white rounded-xl p-2 shadow-lg">
|
||||
<img src={logo} alt="certctl" className="h-16 w-16" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="text-lg font-bold text-white tracking-tight">certctl</h1>
|
||||
<p className="text-[10px] text-brand-300 uppercase tracking-[0.2em]">Control Plane</p>
|
||||
</div>
|
||||
</div>
|
||||
<nav className="flex-1 p-4 space-y-1 overflow-y-auto">
|
||||
|
||||
<nav className="flex-1 py-2 px-3 space-y-0.5 overflow-y-auto">
|
||||
{nav.map(item => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
end={item.to === '/'}
|
||||
className={({ isActive }) =>
|
||||
`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm transition-colors ${
|
||||
`flex items-center gap-3 px-3 py-2 text-[13px] rounded transition-all duration-150 ${
|
||||
isActive
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'text-slate-400 hover:bg-slate-700 hover:text-slate-200'
|
||||
? 'bg-white/15 text-white font-semibold shadow-sm'
|
||||
: 'text-sidebar-text hover:text-white hover:bg-white/10'
|
||||
}`
|
||||
}
|
||||
>
|
||||
@@ -57,12 +67,13 @@ export default function Layout() {
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
<div className="p-4 border-t border-slate-700 flex items-center justify-between">
|
||||
<span className="text-xs text-slate-500">certctl v1.0-dev</span>
|
||||
|
||||
<div className="px-5 py-3 border-t border-white/10 flex items-center justify-between">
|
||||
<span className="text-[10px] text-brand-300/60 font-mono">v2.0.5</span>
|
||||
{authRequired && (
|
||||
<button
|
||||
onClick={logout}
|
||||
className="text-xs text-slate-500 hover:text-slate-300 transition-colors"
|
||||
className="text-xs text-sidebar-text hover:text-white transition-colors"
|
||||
title="Sign out"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
@@ -73,8 +84,8 @@ export default function Layout() {
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Main content */}
|
||||
<main className="flex-1 flex flex-col overflow-hidden">
|
||||
{/* Main content — light background */}
|
||||
<main className="flex-1 flex flex-col overflow-hidden bg-page">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -6,10 +6,10 @@ interface PageHeaderProps {
|
||||
|
||||
export default function PageHeader({ title, subtitle, action }: PageHeaderProps) {
|
||||
return (
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-700 bg-slate-800">
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-surface-border bg-surface">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">{title}</h2>
|
||||
{subtitle && <p className="text-sm text-slate-400 mt-0.5">{subtitle}</p>}
|
||||
<h2 className="text-lg font-semibold text-ink">{title}</h2>
|
||||
{subtitle && <p className="text-sm text-ink-muted mt-0.5">{subtitle}</p>}
|
||||
</div>
|
||||
{action}
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const statusStyles: Record<string, string> = {
|
||||
// Certificate statuses
|
||||
Active: 'badge-success',
|
||||
Expiring: 'badge-warning',
|
||||
Expired: 'badge-danger',
|
||||
@@ -8,6 +9,8 @@ const statusStyles: Record<string, string> = {
|
||||
Revoked: 'badge-danger',
|
||||
// Job statuses
|
||||
Pending: 'badge-info',
|
||||
AwaitingCSR: 'badge-info',
|
||||
AwaitingApproval: 'badge-info',
|
||||
Running: 'badge-warning',
|
||||
Completed: 'badge-success',
|
||||
Failed: 'badge-danger',
|
||||
@@ -16,6 +19,10 @@ const statusStyles: Record<string, string> = {
|
||||
Online: 'badge-success',
|
||||
Offline: 'badge-danger',
|
||||
Stale: 'badge-warning',
|
||||
// Discovery statuses
|
||||
Unmanaged: 'badge-warning',
|
||||
Managed: 'badge-success',
|
||||
Dismissed: 'badge-neutral',
|
||||
// Notification statuses
|
||||
sent: 'badge-success',
|
||||
pending: 'badge-warning',
|
||||
|
||||
@@ -1,30 +1,53 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap');
|
||||
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-slate-900 text-slate-100 antialiased;
|
||||
@apply bg-page text-ink antialiased;
|
||||
font-family: 'Inter', system-ui, -apple-system, sans-serif;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
/* Badges */
|
||||
.badge {
|
||||
@apply inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium;
|
||||
@apply inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold tracking-wide;
|
||||
}
|
||||
.badge-success { @apply bg-emerald-500/10 text-emerald-400 border border-emerald-500/20; }
|
||||
.badge-warning { @apply bg-amber-500/10 text-amber-400 border border-amber-500/20; }
|
||||
.badge-danger { @apply bg-red-500/10 text-red-400 border border-red-500/20; }
|
||||
.badge-info { @apply bg-blue-500/10 text-blue-400 border border-blue-500/20; }
|
||||
.badge-neutral { @apply bg-slate-500/10 text-slate-400 border border-slate-500/20; }
|
||||
.badge-success { @apply bg-emerald-100 text-emerald-700; }
|
||||
.badge-warning { @apply bg-amber-100 text-amber-700; }
|
||||
.badge-danger { @apply bg-red-100 text-red-700; }
|
||||
.badge-info { @apply bg-brand-100 text-brand-700; }
|
||||
.badge-neutral { @apply bg-slate-100 text-slate-600; }
|
||||
|
||||
/* Cards */
|
||||
.card {
|
||||
@apply bg-slate-800 border border-slate-700 rounded-lg;
|
||||
@apply bg-surface border border-surface-border rounded-md shadow-sm;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn {
|
||||
@apply inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors;
|
||||
@apply inline-flex items-center justify-center gap-2 px-4 py-2 rounded text-sm font-semibold transition-all duration-150;
|
||||
}
|
||||
.btn-primary { @apply bg-brand-500 hover:bg-brand-600 text-white shadow-sm; }
|
||||
.btn-danger { @apply bg-red-500 hover:bg-red-600 text-white shadow-sm; }
|
||||
.btn-ghost { @apply text-ink-muted hover:text-ink hover:bg-surface-muted; }
|
||||
.btn-outline { @apply border border-surface-border text-ink-muted hover:text-ink hover:bg-surface-muted; }
|
||||
|
||||
/* Form inputs */
|
||||
.input {
|
||||
@apply bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink placeholder:text-ink-faint focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 outline-none transition-colors;
|
||||
}
|
||||
|
||||
/* Monospace data values */
|
||||
.mono {
|
||||
@apply font-mono text-xs;
|
||||
}
|
||||
|
||||
/* Stat cards with colored top borders */
|
||||
.stat-card {
|
||||
@apply bg-surface border border-surface-border rounded-md shadow-sm p-5 border-t-4;
|
||||
}
|
||||
.btn-primary { @apply bg-blue-600 hover:bg-blue-500 text-white; }
|
||||
.btn-ghost { @apply hover:bg-slate-700 text-slate-300; }
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ import AgentGroupsPage from './pages/AgentGroupsPage';
|
||||
import AuditPage from './pages/AuditPage';
|
||||
import ShortLivedPage from './pages/ShortLivedPage';
|
||||
import AgentFleetPage from './pages/AgentFleetPage';
|
||||
import DiscoveryPage from './pages/DiscoveryPage';
|
||||
import NetworkScanPage from './pages/NetworkScanPage';
|
||||
import './index.css';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
@@ -61,6 +63,8 @@ createRoot(document.getElementById('root')!).render(
|
||||
<Route path="agent-groups" element={<AgentGroupsPage />} />
|
||||
<Route path="audit" element={<AuditPage />} />
|
||||
<Route path="short-lived" element={<ShortLivedPage />} />
|
||||
<Route path="discovery" element={<DiscoveryPage />} />
|
||||
<Route path="network-scans" element={<NetworkScanPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
|
||||
@@ -8,9 +8,9 @@ import { formatDateTime, timeAgo } from '../api/utils';
|
||||
|
||||
function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex justify-between py-2 border-b border-slate-700/50">
|
||||
<span className="text-sm text-slate-400">{label}</span>
|
||||
<span className="text-sm text-slate-200">{value}</span>
|
||||
<div className="flex justify-between py-2 border-b border-surface-border/50">
|
||||
<span className="text-sm text-ink-muted">{label}</span>
|
||||
<span className="text-sm text-ink">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -47,7 +47,7 @@ export default function AgentDetailPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title="Agent" />
|
||||
<div className="flex items-center justify-center flex-1 text-slate-400">Loading...</div>
|
||||
<div className="flex items-center justify-center flex-1 text-ink-muted">Loading...</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -75,8 +75,8 @@ export default function AgentDetailPage() {
|
||||
<div className="flex-1 overflow-y-auto p-6 space-y-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Agent Info */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Agent Details</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Agent Details</h3>
|
||||
<InfoRow label="Health" value={<StatusBadge status={health} />} />
|
||||
<InfoRow label="Hostname" value={<span className="font-mono text-xs">{agent.hostname || '—'}</span>} />
|
||||
<InfoRow label="IP Address" value={<span className="font-mono text-xs">{agent.ip_address || '—'}</span>} />
|
||||
@@ -85,7 +85,7 @@ export default function AgentDetailPage() {
|
||||
agent.last_heartbeat ? (
|
||||
<span>
|
||||
{timeAgo(agent.last_heartbeat)}
|
||||
<span className="text-slate-500 ml-2 text-xs">{formatDateTime(agent.last_heartbeat)}</span>
|
||||
<span className="text-ink-faint ml-2 text-xs">{formatDateTime(agent.last_heartbeat)}</span>
|
||||
</span>
|
||||
) : '—'
|
||||
} />
|
||||
@@ -94,15 +94,15 @@ export default function AgentDetailPage() {
|
||||
</div>
|
||||
|
||||
{/* System Info */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">System Information</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">System Information</h3>
|
||||
<InfoRow label="Operating System" value={agent.os || '—'} />
|
||||
<InfoRow label="Architecture" value={agent.architecture || '—'} />
|
||||
<InfoRow label="IP Address" value={<span className="font-mono text-xs">{agent.ip_address || '—'}</span>} />
|
||||
<InfoRow label="Agent Version" value={agent.version || '—'} />
|
||||
{agent.capabilities?.length ? (
|
||||
<div className="mt-4">
|
||||
<p className="text-xs text-slate-400 mb-2">Capabilities</p>
|
||||
<p className="text-xs text-ink-muted mb-2">Capabilities</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{agent.capabilities.map((c) => (
|
||||
<span key={c} className="badge badge-info">{c}</span>
|
||||
@@ -112,7 +112,7 @@ export default function AgentDetailPage() {
|
||||
) : null}
|
||||
{agent.tags && Object.keys(agent.tags).length > 0 ? (
|
||||
<div className="mt-4">
|
||||
<p className="text-xs text-slate-400 mb-2">Tags</p>
|
||||
<p className="text-xs text-ink-muted mb-2">Tags</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(agent.tags).map(([k, v]) => (
|
||||
<span key={k} className="badge badge-neutral">{k}: {v}</span>
|
||||
@@ -124,20 +124,20 @@ export default function AgentDetailPage() {
|
||||
</div>
|
||||
|
||||
{/* Recent Jobs */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Recent Jobs</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Recent Jobs</h3>
|
||||
{!agentJobs.length ? (
|
||||
<p className="text-sm text-slate-500">No recent jobs</p>
|
||||
<p className="text-sm text-ink-faint">No recent jobs</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{agentJobs.map(j => (
|
||||
<div key={j.id} className="flex items-center justify-between py-2 px-3 rounded-lg hover:bg-slate-700/50 transition-colors">
|
||||
<div key={j.id} className="flex items-center justify-between py-2 px-3 rounded hover:bg-surface-muted transition-colors">
|
||||
<div>
|
||||
<div className="text-sm text-slate-200">{j.type}</div>
|
||||
<div className="text-xs text-slate-500 font-mono">{j.id}</div>
|
||||
<div className="text-sm text-ink">{j.type}</div>
|
||||
<div className="text-xs text-ink-faint font-mono">{j.id}</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs text-slate-400 font-mono">{j.certificate_id}</span>
|
||||
<span className="text-xs text-ink-muted font-mono">{j.certificate_id}</span>
|
||||
<StatusBadge status={j.status} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -147,16 +147,16 @@ export default function AgentDetailPage() {
|
||||
</div>
|
||||
|
||||
{/* Heartbeat Timeline */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Heartbeat Status</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Heartbeat Status</h3>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className={`w-3 h-3 rounded-full ${
|
||||
health === 'Online' ? 'bg-emerald-400 animate-pulse' :
|
||||
health === 'Stale' ? 'bg-amber-400' : 'bg-red-400'
|
||||
health === 'Online' ? 'bg-emerald-500 animate-pulse' :
|
||||
health === 'Stale' ? 'bg-amber-500' : 'bg-red-500'
|
||||
}`} />
|
||||
<div>
|
||||
<p className="text-sm text-slate-200">{health}</p>
|
||||
<p className="text-xs text-slate-400">
|
||||
<p className="text-sm text-ink">{health}</p>
|
||||
<p className="text-xs text-ink-muted">
|
||||
{health === 'Online' && 'Agent is responding to heartbeat checks'}
|
||||
{health === 'Stale' && 'Agent has not sent a heartbeat recently'}
|
||||
{health === 'Offline' && 'Agent is not responding'}
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { Agent } from '../api/types';
|
||||
|
||||
const OS_COLORS: Record<string, string> = {
|
||||
linux: '#f97316',
|
||||
darwin: '#3b82f6',
|
||||
darwin: '#2ea88f',
|
||||
windows: '#8b5cf6',
|
||||
unknown: '#64748b',
|
||||
};
|
||||
@@ -53,9 +53,9 @@ function groupAgents(agents: Agent[]): GroupedAgents[] {
|
||||
const CustomTooltip = ({ active, payload }: any) => {
|
||||
if (!active || !payload?.length) return null;
|
||||
return (
|
||||
<div className="bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-xs shadow-lg">
|
||||
<div className="bg-surface border border-surface-border rounded px-3 py-2 text-xs shadow-lg">
|
||||
{payload.map((entry: any, i: number) => (
|
||||
<p key={i} style={{ color: entry.payload?.fill || entry.color }}>
|
||||
<p key={i} style={{ color: entry.payload?.fill || entry.color }} className="font-medium">
|
||||
{entry.name}: {entry.value}
|
||||
</p>
|
||||
))}
|
||||
@@ -113,25 +113,25 @@ export default function AgentFleetPage() {
|
||||
<div className="flex-1 overflow-y-auto p-6 space-y-6">
|
||||
{/* Summary Cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div className="card p-5 text-center">
|
||||
<p className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Total Agents</p>
|
||||
<p className="text-3xl font-bold mt-2 text-blue-400">{totalAgents}</p>
|
||||
<div className="bg-surface border border-surface-border border-t-4 border-t-brand-400 rounded p-5 text-center shadow-sm">
|
||||
<p className="text-xs font-semibold text-ink-muted uppercase tracking-wider">Total Agents</p>
|
||||
<p className="text-3xl font-bold mt-2 text-brand-500">{totalAgents}</p>
|
||||
</div>
|
||||
<div className="card p-5 text-center">
|
||||
<p className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Online</p>
|
||||
<p className="text-3xl font-bold mt-2 text-emerald-400">{onlineAgents}</p>
|
||||
<div className="bg-surface border border-surface-border border-t-4 border-t-emerald-500 rounded p-5 text-center shadow-sm">
|
||||
<p className="text-xs font-semibold text-ink-muted uppercase tracking-wider">Online</p>
|
||||
<p className="text-3xl font-bold mt-2 text-emerald-600">{onlineAgents}</p>
|
||||
</div>
|
||||
<div className="card p-5 text-center">
|
||||
<p className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Offline</p>
|
||||
<p className="text-3xl font-bold mt-2 text-red-400">{offlineAgents}</p>
|
||||
<div className="bg-surface border border-surface-border border-t-4 border-t-red-500 rounded p-5 text-center shadow-sm">
|
||||
<p className="text-xs font-semibold text-ink-muted uppercase tracking-wider">Offline</p>
|
||||
<p className="text-3xl font-bold mt-2 text-red-600">{offlineAgents}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Charts */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* OS Distribution */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">OS Distribution</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">OS Distribution</h3>
|
||||
<div className="h-48">
|
||||
{osPieData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
@@ -145,14 +145,14 @@ export default function AgentFleetPage() {
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center text-sm text-slate-500">No data</div>
|
||||
<div className="h-full flex items-center justify-center text-sm text-ink-faint">No data</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Status Distribution */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Status Distribution</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Status Distribution</h3>
|
||||
<div className="h-48">
|
||||
{statusPieData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
@@ -166,33 +166,33 @@ export default function AgentFleetPage() {
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center text-sm text-slate-500">No data</div>
|
||||
<div className="h-full flex items-center justify-center text-sm text-ink-faint">No data</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Version Breakdown */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Agent Versions</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Agent Versions</h3>
|
||||
<div className="space-y-3">
|
||||
{Object.entries(versionCounts)
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.map(([version, count]) => (
|
||||
<div key={version} className="flex items-center justify-between">
|
||||
<span className="text-sm text-slate-300 font-mono">{version}</span>
|
||||
<span className="text-sm text-ink font-mono">{version}</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-24 bg-slate-700 rounded-full h-2">
|
||||
<div className="w-24 bg-surface-border rounded-full h-2">
|
||||
<div
|
||||
className="bg-blue-500 h-2 rounded-full"
|
||||
className="bg-brand-400 h-2 rounded-full"
|
||||
style={{ width: `${(count / totalAgents) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-xs text-slate-400 w-8 text-right">{count}</span>
|
||||
<span className="text-xs text-ink-muted w-8 text-right">{count}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{Object.keys(versionCounts).length === 0 && (
|
||||
<p className="text-sm text-slate-500">No version data</p>
|
||||
<p className="text-sm text-ink-faint">No version data</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -200,50 +200,50 @@ export default function AgentFleetPage() {
|
||||
|
||||
{/* Environment Groups */}
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Fleet by Platform</h3>
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Fleet by Platform</h3>
|
||||
{isLoading ? (
|
||||
<p className="text-sm text-slate-500">Loading fleet data...</p>
|
||||
<p className="text-sm text-ink-faint">Loading fleet data...</p>
|
||||
) : groups.length === 0 ? (
|
||||
<p className="text-sm text-slate-500">No agents registered</p>
|
||||
<p className="text-sm text-ink-faint">No agents registered</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{groups.map(group => (
|
||||
<div key={`${group.os}/${group.arch}`} className="card">
|
||||
<div className="px-5 py-4 border-b border-slate-700 flex items-center justify-between">
|
||||
<div key={`${group.os}/${group.arch}`} className="bg-surface border border-surface-border rounded overflow-hidden shadow-sm">
|
||||
<div className="px-5 py-4 border-b border-surface-border flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className="w-3 h-3 rounded-full"
|
||||
style={{ backgroundColor: OS_COLORS[group.os.toLowerCase()] || '#64748b' }}
|
||||
/>
|
||||
<h4 className="text-sm font-medium text-slate-200">
|
||||
<h4 className="text-sm font-medium text-ink">
|
||||
{group.os} / {group.arch}
|
||||
</h4>
|
||||
<span className="text-xs text-slate-500">
|
||||
<span className="text-xs text-ink-faint">
|
||||
{group.agents.length} agent{group.agents.length !== 1 ? 's' : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-xs">
|
||||
<span className="text-emerald-400">{group.online} online</span>
|
||||
{group.offline > 0 && <span className="text-red-400">{group.offline} offline</span>}
|
||||
<span className="text-emerald-600">{group.online} online</span>
|
||||
{group.offline > 0 && <span className="text-red-600">{group.offline} offline</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="divide-y divide-slate-700/50">
|
||||
<div className="divide-y divide-surface-border/50">
|
||||
{group.agents.map(agent => (
|
||||
<div
|
||||
key={agent.id}
|
||||
onClick={() => navigate(`/agents/${agent.id}`)}
|
||||
className="px-5 py-3 flex items-center justify-between hover:bg-slate-700/30 cursor-pointer transition-colors"
|
||||
className="px-5 py-3 flex items-center justify-between hover:bg-surface-muted cursor-pointer transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`w-2 h-2 rounded-full ${agent.status === 'Online' ? 'bg-emerald-400' : 'bg-red-400'}`} />
|
||||
<div className={`w-2 h-2 rounded-full ${agent.status === 'Online' ? 'bg-emerald-500' : 'bg-red-500'}`} />
|
||||
<div>
|
||||
<div className="text-sm text-slate-200">{agent.name || agent.hostname}</div>
|
||||
<div className="text-xs text-slate-500">{agent.ip_address || agent.id}</div>
|
||||
<div className="text-sm text-ink">{agent.name || agent.hostname}</div>
|
||||
<div className="text-xs text-ink-faint">{agent.ip_address || agent.id}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
{agent.version && (
|
||||
<span className="text-xs text-slate-500 font-mono">{agent.version}</span>
|
||||
<span className="text-xs text-ink-muted font-mono">{agent.version}</span>
|
||||
)}
|
||||
<StatusBadge status={agent.status} />
|
||||
</div>
|
||||
|
||||
@@ -27,10 +27,10 @@ export default function AgentGroupsPage() {
|
||||
label: 'Group',
|
||||
render: (g) => (
|
||||
<div>
|
||||
<div className="font-medium text-slate-200">{g.name}</div>
|
||||
<div className="text-xs text-slate-500 font-mono">{g.id}</div>
|
||||
<div className="font-medium text-ink">{g.name}</div>
|
||||
<div className="text-xs text-ink-faint font-mono">{g.id}</div>
|
||||
{g.description && (
|
||||
<div className="text-xs text-slate-400 mt-0.5 max-w-xs truncate">{g.description}</div>
|
||||
<div className="text-xs text-ink-muted mt-0.5 max-w-xs truncate">{g.description}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
@@ -51,7 +51,7 @@ export default function AgentGroupsPage() {
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-slate-500 text-xs">Manual only</span>
|
||||
<span className="text-ink-faint text-xs">Manual only</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -63,7 +63,7 @@ export default function AgentGroupsPage() {
|
||||
{
|
||||
key: 'created',
|
||||
label: 'Created',
|
||||
render: (g) => <span className="text-xs text-slate-400">{formatDateTime(g.created_at)}</span>,
|
||||
render: (g) => <span className="text-xs text-ink-muted">{formatDateTime(g.created_at)}</span>,
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
@@ -71,7 +71,7 @@ export default function AgentGroupsPage() {
|
||||
render: (g) => (
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete group ${g.name}?`)) deleteMutation.mutate(g.id); }}
|
||||
className="text-xs text-red-400 hover:text-red-300 transition-colors"
|
||||
className="text-xs text-red-600 hover:text-red-700 transition-colors"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
|
||||
@@ -31,8 +31,8 @@ export default function AgentsPage() {
|
||||
label: 'Agent',
|
||||
render: (a) => (
|
||||
<div>
|
||||
<div className="font-medium text-slate-200">{a.name}</div>
|
||||
<div className="text-xs text-slate-500">{a.id}</div>
|
||||
<div className="font-medium text-ink">{a.name}</div>
|
||||
<div className="text-xs text-ink-faint">{a.id}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -41,14 +41,14 @@ export default function AgentsPage() {
|
||||
label: 'Health',
|
||||
render: (a) => <StatusBadge status={a.status || heartbeatStatus(a.last_heartbeat)} />,
|
||||
},
|
||||
{ key: 'hostname', label: 'Hostname', render: (a) => <span className="text-slate-300 font-mono text-xs">{a.hostname || '—'}</span> },
|
||||
{ key: 'os', label: 'OS / Arch', render: (a) => <span className="text-slate-400 text-xs">{a.os && a.architecture ? `${a.os}/${a.architecture}` : a.os || '—'}</span> },
|
||||
{ key: 'ip', label: 'IP Address', render: (a) => <span className="text-slate-400 font-mono text-xs">{a.ip_address || '—'}</span> },
|
||||
{ key: 'version', label: 'Version', render: (a) => <span className="text-slate-400 text-xs">{a.version || '—'}</span> },
|
||||
{ key: 'hostname', label: 'Hostname', render: (a) => <span className="text-ink-muted font-mono text-xs">{a.hostname || '—'}</span> },
|
||||
{ key: 'os', label: 'OS / Arch', render: (a) => <span className="text-ink-muted text-xs">{a.os && a.architecture ? `${a.os}/${a.architecture}` : a.os || '—'}</span> },
|
||||
{ key: 'ip', label: 'IP Address', render: (a) => <span className="text-ink-muted font-mono text-xs">{a.ip_address || '—'}</span> },
|
||||
{ key: 'version', label: 'Version', render: (a) => <span className="text-ink-muted text-xs">{a.version || '—'}</span> },
|
||||
{
|
||||
key: 'heartbeat',
|
||||
label: 'Last Heartbeat',
|
||||
render: (a) => <span className="text-slate-400 text-xs">{timeAgo(a.last_heartbeat)}</span>,
|
||||
render: (a) => <span className="text-ink-muted text-xs">{timeAgo(a.last_heartbeat)}</span>,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -9,16 +9,16 @@ import { formatDateTime } from '../api/utils';
|
||||
import type { AuditEvent } from '../api/types';
|
||||
|
||||
const actionColors: Record<string, string> = {
|
||||
certificate_created: 'text-emerald-400',
|
||||
renewal_triggered: 'text-blue-400',
|
||||
renewal_job_created: 'text-blue-400',
|
||||
renewal_completed: 'text-emerald-400',
|
||||
deployment_completed: 'text-emerald-400',
|
||||
deployment_failed: 'text-red-400',
|
||||
expiration_alert_sent: 'text-amber-400',
|
||||
agent_registered: 'text-blue-400',
|
||||
policy_violated: 'text-red-400',
|
||||
certificate_revoked: 'text-red-400',
|
||||
certificate_created: 'text-emerald-600',
|
||||
renewal_triggered: 'text-brand-500',
|
||||
renewal_job_created: 'text-brand-500',
|
||||
renewal_completed: 'text-emerald-600',
|
||||
deployment_completed: 'text-emerald-600',
|
||||
deployment_failed: 'text-red-600',
|
||||
expiration_alert_sent: 'text-amber-600',
|
||||
agent_registered: 'text-brand-500',
|
||||
policy_violated: 'text-red-600',
|
||||
certificate_revoked: 'text-red-600',
|
||||
};
|
||||
|
||||
const RESOURCE_TYPES = ['', 'certificate', 'agent', 'job', 'notification', 'policy', 'target', 'issuer'];
|
||||
@@ -94,7 +94,7 @@ export default function AuditPage() {
|
||||
key: 'action',
|
||||
label: 'Action',
|
||||
render: (e) => (
|
||||
<span className={`text-sm font-medium ${actionColors[e.action] || 'text-slate-300'}`}>
|
||||
<span className={`text-sm font-medium ${actionColors[e.action] || 'text-ink'}`}>
|
||||
{e.action.replace(/_/g, ' ')}
|
||||
</span>
|
||||
),
|
||||
@@ -104,8 +104,8 @@ export default function AuditPage() {
|
||||
label: 'Actor',
|
||||
render: (e) => (
|
||||
<div>
|
||||
<div className="text-sm text-slate-200">{e.actor}</div>
|
||||
<div className="text-xs text-slate-500">{e.actor_type}</div>
|
||||
<div className="text-sm text-ink">{e.actor}</div>
|
||||
<div className="text-xs text-ink-faint">{e.actor_type}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -114,8 +114,8 @@ export default function AuditPage() {
|
||||
label: 'Resource',
|
||||
render: (e) => (
|
||||
<div>
|
||||
<div className="text-sm text-slate-300">{e.resource_type}</div>
|
||||
<div className="text-xs text-slate-500 font-mono">{e.resource_id}</div>
|
||||
<div className="text-sm text-ink">{e.resource_type}</div>
|
||||
<div className="text-xs text-ink-faint font-mono">{e.resource_id}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -123,15 +123,15 @@ export default function AuditPage() {
|
||||
key: 'details',
|
||||
label: 'Details',
|
||||
render: (e) => {
|
||||
if (!e.details || Object.keys(e.details).length === 0) return <span className="text-slate-500">—</span>;
|
||||
if (!e.details || Object.keys(e.details).length === 0) return <span className="text-ink-faint">—</span>;
|
||||
return (
|
||||
<span className="text-xs text-slate-400 font-mono truncate max-w-xs block">
|
||||
<span className="text-xs text-ink-muted font-mono truncate max-w-xs block">
|
||||
{JSON.stringify(e.details).slice(0, 60)}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{ key: 'time', label: 'Time', render: (e) => <span className="text-xs text-slate-400">{formatDateTime(e.timestamp)}</span> },
|
||||
{ key: 'time', label: 'Time', render: (e) => <span className="text-xs text-ink-muted">{formatDateTime(e.timestamp)}</span> },
|
||||
];
|
||||
|
||||
const hasFilters = resourceType || actorFilter || timeRange || actionFilter;
|
||||
@@ -144,21 +144,21 @@ export default function AuditPage() {
|
||||
action={
|
||||
filtered.length > 0 ? (
|
||||
<div className="flex gap-2">
|
||||
<button onClick={() => exportCSV(filtered)} className="btn btn-ghost text-xs border border-slate-600">
|
||||
<button onClick={() => exportCSV(filtered)} className="btn btn-ghost text-xs border border-surface-border">
|
||||
Export CSV
|
||||
</button>
|
||||
<button onClick={() => exportJSON(filtered)} className="btn btn-ghost text-xs border border-slate-600">
|
||||
<button onClick={() => exportJSON(filtered)} className="btn btn-ghost text-xs border border-surface-border">
|
||||
Export JSON
|
||||
</button>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
<div className="px-4 py-3 flex flex-wrap gap-3 border-b border-slate-700/50">
|
||||
<div className="px-4 py-3 flex flex-wrap gap-3 border-b border-surface-border/50">
|
||||
<select
|
||||
value={resourceType}
|
||||
onChange={(e) => setResourceType(e.target.value)}
|
||||
className="bg-slate-800 border border-slate-600 rounded px-3 py-1.5 text-xs text-slate-300 focus:outline-none focus:border-blue-500"
|
||||
className="bg-surface border border-surface-border rounded px-3 py-1.5 text-xs text-ink focus:outline-none focus:border-brand-400"
|
||||
>
|
||||
<option value="">All resources</option>
|
||||
{RESOURCE_TYPES.filter(Boolean).map((t) => (
|
||||
@@ -170,19 +170,19 @@ export default function AuditPage() {
|
||||
placeholder="Filter by actor..."
|
||||
value={actorFilter}
|
||||
onChange={(e) => setActorFilter(e.target.value)}
|
||||
className="bg-slate-800 border border-slate-600 rounded px-3 py-1.5 text-xs text-slate-300 placeholder-slate-500 focus:outline-none focus:border-blue-500 w-40"
|
||||
className="bg-surface border border-surface-border rounded px-3 py-1.5 text-xs text-ink placeholder-ink-faint focus:outline-none focus:border-brand-400 w-40"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Filter by action..."
|
||||
value={actionFilter}
|
||||
onChange={(e) => setActionFilter(e.target.value)}
|
||||
className="bg-slate-800 border border-slate-600 rounded px-3 py-1.5 text-xs text-slate-300 placeholder-slate-500 focus:outline-none focus:border-blue-500 w-40"
|
||||
className="bg-surface border border-surface-border rounded px-3 py-1.5 text-xs text-ink placeholder-ink-faint focus:outline-none focus:border-brand-400 w-40"
|
||||
/>
|
||||
<select
|
||||
value={timeRange}
|
||||
onChange={(e) => setTimeRange(e.target.value)}
|
||||
className="bg-slate-800 border border-slate-600 rounded px-3 py-1.5 text-xs text-slate-300 focus:outline-none focus:border-blue-500"
|
||||
className="bg-surface border border-surface-border rounded px-3 py-1.5 text-xs text-ink focus:outline-none focus:border-brand-400"
|
||||
>
|
||||
{TIME_RANGES.map((r) => (
|
||||
<option key={r.value} value={r.value}>{r.label}</option>
|
||||
@@ -191,7 +191,7 @@ export default function AuditPage() {
|
||||
{hasFilters && (
|
||||
<button
|
||||
onClick={() => { setResourceType(''); setActorFilter(''); setTimeRange(''); setActionFilter(''); }}
|
||||
className="text-xs text-slate-400 hover:text-slate-200 transition-colors"
|
||||
className="text-xs text-ink-muted hover:text-ink transition-colors"
|
||||
>
|
||||
Clear filters
|
||||
</button>
|
||||
|
||||
@@ -11,12 +11,12 @@ import type { Job } from '../api/types';
|
||||
|
||||
function InfoRow({ label, value, editable, onEdit }: { label: string; value: React.ReactNode; editable?: boolean; onEdit?: () => void }) {
|
||||
return (
|
||||
<div className="flex justify-between py-2 border-b border-slate-700/50 group">
|
||||
<span className="text-sm text-slate-400">{label}</span>
|
||||
<div className="flex justify-between py-2 border-b border-surface-border/50 group">
|
||||
<span className="text-sm text-ink-muted">{label}</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-slate-200">{value}</span>
|
||||
<span className="text-sm text-ink">{value}</span>
|
||||
{editable && onEdit && (
|
||||
<button onClick={onEdit} className="opacity-0 group-hover:opacity-100 transition-opacity text-xs text-blue-400 hover:text-blue-300">
|
||||
<button onClick={onEdit} className="opacity-0 group-hover:opacity-100 transition-opacity text-xs text-brand-400 hover:text-brand-500">
|
||||
Edit
|
||||
</button>
|
||||
)}
|
||||
@@ -28,22 +28,22 @@ function InfoRow({ label, value, editable, onEdit }: { label: string; value: Rea
|
||||
// Timeline step component for deployment status
|
||||
function TimelineStep({ label, status, time, isLast }: { label: string; status: 'completed' | 'active' | 'pending' | 'failed'; time?: string; isLast?: boolean }) {
|
||||
const dotStyles = {
|
||||
completed: 'bg-emerald-500 ring-emerald-500/30',
|
||||
active: 'bg-blue-500 ring-blue-500/30 animate-pulse',
|
||||
pending: 'bg-slate-600 ring-slate-600/30',
|
||||
failed: 'bg-red-500 ring-red-500/30',
|
||||
completed: 'bg-emerald-500 ring-emerald-200',
|
||||
active: 'bg-brand-400 ring-brand-200 animate-pulse',
|
||||
pending: 'bg-surface-muted ring-surface-border',
|
||||
failed: 'bg-red-500 ring-red-200',
|
||||
};
|
||||
const lineStyles = {
|
||||
completed: 'bg-emerald-500/50',
|
||||
active: 'bg-blue-500/30',
|
||||
pending: 'bg-slate-700',
|
||||
failed: 'bg-red-500/30',
|
||||
completed: 'bg-emerald-300',
|
||||
active: 'bg-brand-200',
|
||||
pending: 'bg-surface-border',
|
||||
failed: 'bg-red-300',
|
||||
};
|
||||
const textStyles = {
|
||||
completed: 'text-emerald-400',
|
||||
active: 'text-blue-400',
|
||||
pending: 'text-slate-500',
|
||||
failed: 'text-red-400',
|
||||
completed: 'text-emerald-600',
|
||||
active: 'text-brand-400',
|
||||
pending: 'text-ink-faint',
|
||||
failed: 'text-red-600',
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -54,7 +54,7 @@ function TimelineStep({ label, status, time, isLast }: { label: string; status:
|
||||
</div>
|
||||
<div className="pb-6">
|
||||
<div className={`text-sm font-medium ${textStyles[status]}`}>{label}</div>
|
||||
{time && <div className="text-xs text-slate-500 mt-0.5">{time}</div>}
|
||||
{time && <div className="text-xs text-ink-faint mt-0.5">{time}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -117,8 +117,8 @@ function DeploymentTimeline({ certId, certStatus, createdAt, issuedAt }: { certI
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Lifecycle Timeline</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Lifecycle Timeline</h3>
|
||||
<div className="pl-1">
|
||||
<TimelineStep label="Requested" status={getRequestedStatus()} time={getRequestedTime()} />
|
||||
<TimelineStep label="Issued" status={getIssuedStatus()} time={getIssuedTime()} />
|
||||
@@ -161,10 +161,10 @@ function InlinePolicyEditor({ certId, currentPolicyId, currentProfileId }: { cer
|
||||
|
||||
if (!editing) {
|
||||
return (
|
||||
<div className="card p-5">
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-sm font-semibold text-slate-300">Policy & Profile</h3>
|
||||
<button onClick={() => setEditing(true)} className="text-xs text-blue-400 hover:text-blue-300 transition-colors">
|
||||
<h3 className="text-sm font-semibold text-ink-muted">Policy & Profile</h3>
|
||||
<button onClick={() => setEditing(true)} className="text-xs text-brand-400 hover:text-brand-500 transition-colors">
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
@@ -175,28 +175,28 @@ function InlinePolicyEditor({ certId, currentPolicyId, currentProfileId }: { cer
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card p-5 border-blue-500/30">
|
||||
<div className="bg-surface border border-surface-border border-brand-400 rounded p-5 shadow-sm">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-sm font-semibold text-blue-400">Edit Policy & Profile</h3>
|
||||
<h3 className="text-sm font-semibold text-brand-500">Edit Policy & Profile</h3>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={() => { setEditing(false); setPolicyId(currentPolicyId); setProfileId(currentProfileId); }}
|
||||
className="text-xs text-slate-400 hover:text-slate-300">Cancel</button>
|
||||
className="text-xs text-ink-muted hover:text-ink">Cancel</button>
|
||||
<button onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending}
|
||||
className="text-xs text-blue-400 hover:text-blue-300 font-medium disabled:opacity-50">
|
||||
className="text-xs text-brand-400 hover:text-brand-500 font-medium disabled:opacity-50">
|
||||
{saveMutation.isPending ? 'Saving...' : 'Save'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{saveMutation.isError && (
|
||||
<div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-3 py-2 text-sm mb-3">
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 rounded px-3 py-2 text-sm mb-3">
|
||||
{saveMutation.error instanceof Error ? saveMutation.error.message : 'Failed to save'}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="text-xs text-slate-400 block mb-1">Renewal Policy</label>
|
||||
<label className="text-xs text-ink-muted block mb-1">Renewal Policy</label>
|
||||
<select value={policyId} onChange={e => setPolicyId(e.target.value)}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200">
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink">
|
||||
<option value="">None</option>
|
||||
{policies?.data?.map(p => (
|
||||
<option key={p.id} value={p.id}>{p.name} ({p.type})</option>
|
||||
@@ -204,9 +204,9 @@ function InlinePolicyEditor({ certId, currentPolicyId, currentProfileId }: { cer
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-slate-400 block mb-1">Certificate Profile</label>
|
||||
<label className="text-xs text-ink-muted block mb-1">Certificate Profile</label>
|
||||
<select value={profileId} onChange={e => setProfileId(e.target.value)}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200">
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink">
|
||||
<option value="">None</option>
|
||||
{profiles?.data?.map(p => (
|
||||
<option key={p.id} value={p.id}>{p.name} — max TTL {p.max_ttl_seconds ? `${Math.round(p.max_ttl_seconds / 86400)}d` : '∞'}</option>
|
||||
@@ -316,7 +316,7 @@ export default function CertificateDetailPage() {
|
||||
<button
|
||||
onClick={() => setShowDeploy(true)}
|
||||
disabled={isArchived || isRevoked}
|
||||
className="btn btn-ghost text-xs border border-slate-600 disabled:opacity-50"
|
||||
className="btn btn-ghost text-xs border border-surface-border disabled:opacity-50"
|
||||
>
|
||||
Deploy
|
||||
</button>
|
||||
@@ -349,53 +349,53 @@ export default function CertificateDetailPage() {
|
||||
/>
|
||||
<div className="flex-1 overflow-y-auto p-6 space-y-6">
|
||||
{renewMutation.isSuccess && (
|
||||
<div className="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 rounded-lg px-4 py-3 text-sm">
|
||||
<div className="bg-emerald-50 border border-emerald-200 text-emerald-700 rounded px-4 py-3 text-sm">
|
||||
Renewal triggered successfully. A renewal job has been created.
|
||||
</div>
|
||||
)}
|
||||
{renewMutation.isError && (
|
||||
<div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-4 py-3 text-sm">
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 rounded px-4 py-3 text-sm">
|
||||
Failed to trigger renewal: {renewMutation.error instanceof Error ? renewMutation.error.message : 'Unknown error'}
|
||||
</div>
|
||||
)}
|
||||
{deployMutation.isSuccess && (
|
||||
<div className="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 rounded-lg px-4 py-3 text-sm">
|
||||
<div className="bg-emerald-50 border border-emerald-200 text-emerald-700 rounded px-4 py-3 text-sm">
|
||||
Deployment triggered. A deployment job has been created.
|
||||
</div>
|
||||
)}
|
||||
{deployMutation.isError && (
|
||||
<div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-4 py-3 text-sm">
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 rounded px-4 py-3 text-sm">
|
||||
Failed to deploy: {deployMutation.error instanceof Error ? deployMutation.error.message : 'Unknown error'}
|
||||
</div>
|
||||
)}
|
||||
{archiveMutation.isError && (
|
||||
<div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-4 py-3 text-sm">
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 rounded px-4 py-3 text-sm">
|
||||
Failed to archive: {archiveMutation.error instanceof Error ? archiveMutation.error.message : 'Unknown error'}
|
||||
</div>
|
||||
)}
|
||||
{revokeMutation.isSuccess && (
|
||||
<div className="bg-amber-500/10 border border-amber-500/20 text-amber-400 rounded-lg px-4 py-3 text-sm">
|
||||
<div className="bg-amber-50 border border-amber-200 text-amber-700 rounded px-4 py-3 text-sm">
|
||||
Certificate revoked successfully. It has been added to the CRL.
|
||||
</div>
|
||||
)}
|
||||
{revokeMutation.isError && (
|
||||
<div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-4 py-3 text-sm">
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 rounded px-4 py-3 text-sm">
|
||||
Failed to revoke: {revokeMutation.error instanceof Error ? revokeMutation.error.message : 'Unknown error'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Revocation Banner */}
|
||||
{isRevoked && (
|
||||
<div className="bg-red-500/10 border border-red-500/30 rounded-lg px-4 py-3">
|
||||
<div className="bg-red-50 border border-red-200 rounded px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center flex-shrink-0">
|
||||
<svg className="w-4 h-4 text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<div className="w-8 h-8 rounded bg-red-100 flex items-center justify-center flex-shrink-0">
|
||||
<svg className="w-4 h-4 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm font-medium text-red-400">Certificate Revoked</div>
|
||||
<div className="text-xs text-slate-400 mt-0.5">
|
||||
<div className="text-sm font-medium text-red-700">Certificate Revoked</div>
|
||||
<div className="text-xs text-red-600 mt-0.5">
|
||||
Reason: {REVOCATION_REASONS.find(r => r.value === cert.revocation_reason)?.label || cert.revocation_reason || 'Unspecified'}
|
||||
{cert.revoked_at && <> · Revoked {formatDateTime(cert.revoked_at)}</>}
|
||||
</div>
|
||||
@@ -409,8 +409,8 @@ export default function CertificateDetailPage() {
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Certificate Info */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Certificate Details</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Certificate Details</h3>
|
||||
<InfoRow label="Status" value={<StatusBadge status={cert.status} />} />
|
||||
<InfoRow label="Common Name" value={cert.common_name} />
|
||||
<InfoRow label="SANs" value={cert.sans?.length ? cert.sans.join(', ') : '—'} />
|
||||
@@ -423,11 +423,11 @@ export default function CertificateDetailPage() {
|
||||
</div>
|
||||
|
||||
{/* Lifecycle */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Lifecycle</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Lifecycle</h3>
|
||||
<InfoRow label="Issued" value={formatDate(cert.issued_at)} />
|
||||
<InfoRow label="Expires" value={
|
||||
<span className={isRevoked ? 'text-red-400 line-through' : expiryColor(days)}>
|
||||
<span className={isRevoked ? 'text-red-600 line-through' : expiryColor(days)}>
|
||||
{formatDate(cert.expires_at)} ({days <= 0 ? 'expired' : `${days} days`})
|
||||
</span>
|
||||
} />
|
||||
@@ -438,10 +438,10 @@ export default function CertificateDetailPage() {
|
||||
{isRevoked && (
|
||||
<>
|
||||
<InfoRow label="Revoked At" value={
|
||||
<span className="text-red-400">{cert.revoked_at ? formatDateTime(cert.revoked_at) : '—'}</span>
|
||||
<span className="text-red-600">{cert.revoked_at ? formatDateTime(cert.revoked_at) : '—'}</span>
|
||||
} />
|
||||
<InfoRow label="Revocation Reason" value={
|
||||
<span className="text-red-400">
|
||||
<span className="text-red-600">
|
||||
{REVOCATION_REASONS.find(r => r.value === cert.revocation_reason)?.label || cert.revocation_reason || '—'}
|
||||
</span>
|
||||
} />
|
||||
@@ -461,8 +461,8 @@ export default function CertificateDetailPage() {
|
||||
|
||||
{/* Tags */}
|
||||
{cert.tags && Object.keys(cert.tags).length > 0 && (
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">Tags</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">Tags</h3>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(cert.tags).map(([k, v]) => (
|
||||
<span key={k} className="badge badge-neutral">{k}: {v}</span>
|
||||
@@ -472,32 +472,32 @@ export default function CertificateDetailPage() {
|
||||
)}
|
||||
|
||||
{/* Version History */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">
|
||||
Version History {versions?.data?.length ? `(${versions.data.length})` : ''}
|
||||
</h3>
|
||||
{!versions?.data?.length ? (
|
||||
<p className="text-sm text-slate-500">No versions yet</p>
|
||||
<p className="text-sm text-ink-faint">No versions yet</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{versions.data.map((v, idx) => (
|
||||
<div key={v.id} className="flex items-center justify-between py-2 border-b border-slate-700/50 last:border-0">
|
||||
<div key={v.id} className="flex items-center justify-between py-2 border-b border-surface-border/50 last:border-0">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-slate-200">Version {v.version}</span>
|
||||
{idx === 0 && <span className="text-xs bg-blue-500/20 text-blue-400 px-1.5 py-0.5 rounded">Current</span>}
|
||||
<span className="text-sm text-ink">Version {v.version}</span>
|
||||
{idx === 0 && <span className="text-xs bg-brand-100 text-brand-700 px-1.5 py-0.5 rounded">Current</span>}
|
||||
</div>
|
||||
<div className="text-xs text-slate-500 font-mono">{v.serial_number}</div>
|
||||
<div className="text-xs text-ink-faint font-mono">{v.serial_number}</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="text-right">
|
||||
<div className="text-sm text-slate-300">{formatDate(v.not_before)} — {formatDate(v.not_after)}</div>
|
||||
<div className="text-xs text-slate-500">{formatDateTime(v.created_at)}</div>
|
||||
<div className="text-sm text-ink-muted">{formatDate(v.not_before)} — {formatDate(v.not_after)}</div>
|
||||
<div className="text-xs text-ink-faint">{formatDateTime(v.created_at)}</div>
|
||||
</div>
|
||||
{idx > 0 && cert?.status !== 'Archived' && cert?.status !== 'Revoked' && (
|
||||
<button
|
||||
onClick={() => setShowDeploy(true)}
|
||||
className="text-xs text-amber-400 hover:text-amber-300 border border-amber-500/30 px-2 py-1 rounded hover:bg-amber-500/10 transition-colors"
|
||||
className="text-xs text-amber-600 hover:text-amber-700 border border-amber-300 px-2 py-1 rounded hover:bg-amber-50 transition-colors"
|
||||
title="Redeploy this version to targets"
|
||||
>
|
||||
Rollback
|
||||
@@ -513,19 +513,19 @@ export default function CertificateDetailPage() {
|
||||
|
||||
{/* Deploy Modal */}
|
||||
{showDeploy && (
|
||||
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={() => setShowDeploy(false)}>
|
||||
<div className="bg-slate-800 border border-slate-600 rounded-xl p-6 w-full max-w-md shadow-2xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-slate-200 mb-4">Deploy Certificate</h2>
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={() => setShowDeploy(false)}>
|
||||
<div className="bg-surface border border-surface-border rounded p-6 w-full max-w-md shadow-xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-ink mb-4">Deploy Certificate</h2>
|
||||
{deployMutation.isError && (
|
||||
<div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-3 py-2 text-sm mb-3">
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 rounded px-3 py-2 text-sm mb-3">
|
||||
{deployMutation.error instanceof Error ? deployMutation.error.message : 'Unknown error'}
|
||||
</div>
|
||||
)}
|
||||
<label className="text-xs text-slate-400 block mb-2">Select Target</label>
|
||||
<label className="text-xs text-ink-muted block mb-2">Select Target</label>
|
||||
<select
|
||||
value={deployTargetId}
|
||||
onChange={e => setDeployTargetId(e.target.value)}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 mb-4"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink mb-4"
|
||||
>
|
||||
<option value="">Choose a target...</option>
|
||||
{targets?.data?.map(t => (
|
||||
@@ -548,22 +548,22 @@ export default function CertificateDetailPage() {
|
||||
|
||||
{/* Revoke Modal */}
|
||||
{showRevoke && (
|
||||
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={() => setShowRevoke(false)}>
|
||||
<div className="bg-slate-800 border border-slate-600 rounded-xl p-6 w-full max-w-md shadow-2xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-red-400 mb-2">Revoke Certificate</h2>
|
||||
<p className="text-sm text-slate-400 mb-4">
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={() => setShowRevoke(false)}>
|
||||
<div className="bg-surface border border-surface-border rounded p-6 w-full max-w-md shadow-xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-red-700 mb-2">Revoke Certificate</h2>
|
||||
<p className="text-sm text-ink-muted mb-4">
|
||||
This action cannot be undone. The certificate will be added to the CRL and marked as revoked.
|
||||
</p>
|
||||
{revokeMutation.isError && (
|
||||
<div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-3 py-2 text-sm mb-3">
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 rounded px-3 py-2 text-sm mb-3">
|
||||
{revokeMutation.error instanceof Error ? revokeMutation.error.message : 'Unknown error'}
|
||||
</div>
|
||||
)}
|
||||
<label className="text-xs text-slate-400 block mb-2">Revocation Reason (RFC 5280)</label>
|
||||
<label className="text-xs text-ink-muted block mb-2">Revocation Reason (RFC 5280)</label>
|
||||
<select
|
||||
value={revokeReason}
|
||||
onChange={e => setRevokeReason(e.target.value)}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 mb-4"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink mb-4"
|
||||
>
|
||||
{REVOCATION_REASONS.map(r => (
|
||||
<option key={r.value} value={r.value}>{r.label}</option>
|
||||
|
||||
@@ -30,57 +30,57 @@ function CreateCertificateModal({ onClose, onSuccess }: { onClose: () => void; o
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={onClose}>
|
||||
<div className="bg-slate-800 border border-slate-600 rounded-xl p-6 w-full max-w-lg shadow-2xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-slate-200 mb-4">New Certificate</h2>
|
||||
{error && <div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-3 py-2 text-sm mb-4">{error}</div>}
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={onClose}>
|
||||
<div className="bg-surface border border-surface-border rounded p-6 w-full max-w-lg shadow-xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-ink mb-4">New Certificate</h2>
|
||||
{error && <div className="bg-red-50 border border-red-200 text-red-700 rounded px-3 py-2 text-sm mb-4">{error}</div>}
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="text-xs text-slate-400 block mb-1">ID (optional)</label>
|
||||
<label className="text-xs text-ink-muted block mb-1">ID (optional)</label>
|
||||
<input value={form.id} onChange={e => setForm(f => ({ ...f, id: e.target.value }))}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 focus:outline-none focus:border-blue-500"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400 focus:ring-1 focus:ring-brand-400/20"
|
||||
placeholder="mc-api-prod (auto-generated if empty)" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-slate-400 block mb-1">Common Name *</label>
|
||||
<label className="text-xs text-ink-muted block mb-1">Common Name *</label>
|
||||
<input value={form.common_name} onChange={e => setForm(f => ({ ...f, common_name: e.target.value }))}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 focus:outline-none focus:border-blue-500"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400 focus:ring-1 focus:ring-brand-400/20"
|
||||
placeholder="api.example.com" />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs text-slate-400 block mb-1">Environment</label>
|
||||
<label className="text-xs text-ink-muted block mb-1">Environment</label>
|
||||
<select value={form.environment} onChange={e => setForm(f => ({ ...f, environment: e.target.value }))}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200">
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink">
|
||||
<option value="production">Production</option>
|
||||
<option value="staging">Staging</option>
|
||||
<option value="development">Development</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-slate-400 block mb-1">Issuer ID *</label>
|
||||
<label className="text-xs text-ink-muted block mb-1">Issuer ID *</label>
|
||||
<input value={form.issuer_id} onChange={e => setForm(f => ({ ...f, issuer_id: e.target.value }))}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 focus:outline-none focus:border-blue-500"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400 focus:ring-1 focus:ring-brand-400/20"
|
||||
placeholder="iss-local" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div>
|
||||
<label className="text-xs text-slate-400 block mb-1">Owner ID</label>
|
||||
<label className="text-xs text-ink-muted block mb-1">Owner ID</label>
|
||||
<input value={form.owner_id} onChange={e => setForm(f => ({ ...f, owner_id: e.target.value }))}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 focus:outline-none focus:border-blue-500"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400 focus:ring-1 focus:ring-brand-400/20"
|
||||
placeholder="o-alice" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-slate-400 block mb-1">Team ID</label>
|
||||
<label className="text-xs text-ink-muted block mb-1">Team ID</label>
|
||||
<input value={form.team_id} onChange={e => setForm(f => ({ ...f, team_id: e.target.value }))}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 focus:outline-none focus:border-blue-500"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400 focus:ring-1 focus:ring-brand-400/20"
|
||||
placeholder="t-platform" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-slate-400 block mb-1">Policy ID</label>
|
||||
<label className="text-xs text-ink-muted block mb-1">Policy ID</label>
|
||||
<input value={form.renewal_policy_id} onChange={e => setForm(f => ({ ...f, renewal_policy_id: e.target.value }))}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 focus:outline-none focus:border-blue-500"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400 focus:ring-1 focus:ring-brand-400/20"
|
||||
placeholder="rp-standard" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -124,27 +124,27 @@ function BulkRevokeModal({ ids, onClose, onSuccess }: { ids: string[]; onClose:
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={onClose}>
|
||||
<div className="bg-slate-800 border border-slate-600 rounded-xl p-6 w-full max-w-md shadow-2xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-red-400 mb-2">Bulk Revoke</h2>
|
||||
<p className="text-sm text-slate-400 mb-4">
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={onClose}>
|
||||
<div className="bg-surface border border-surface-border rounded p-6 w-full max-w-md shadow-xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-red-700 mb-2">Bulk Revoke</h2>
|
||||
<p className="text-sm text-ink-muted mb-4">
|
||||
Revoke {ids.length} certificate{ids.length > 1 ? 's' : ''}. This cannot be undone.
|
||||
</p>
|
||||
{error && <div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-3 py-2 text-sm mb-3">{error}</div>}
|
||||
{error && <div className="bg-red-50 border border-red-200 text-red-700 rounded px-3 py-2 text-sm mb-3">{error}</div>}
|
||||
{running && (
|
||||
<div className="mb-3">
|
||||
<div className="flex justify-between text-xs text-slate-400 mb-1">
|
||||
<div className="flex justify-between text-xs text-ink-muted mb-1">
|
||||
<span>Progress</span>
|
||||
<span>{progress}/{ids.length}</span>
|
||||
</div>
|
||||
<div className="w-full bg-slate-700 rounded-full h-2">
|
||||
<div className="w-full bg-surface-border rounded-full h-2">
|
||||
<div className="bg-red-500 h-2 rounded-full transition-all" style={{ width: `${(progress / ids.length) * 100}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<label className="text-xs text-slate-400 block mb-2">Revocation Reason (RFC 5280)</label>
|
||||
<label className="text-xs text-ink-muted block mb-2">Revocation Reason (RFC 5280)</label>
|
||||
<select value={reason} onChange={e => setReason(e.target.value)}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 mb-4"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink mb-4"
|
||||
disabled={running}
|
||||
>
|
||||
{REVOCATION_REASONS.map(r => (
|
||||
@@ -193,27 +193,27 @@ function BulkReassignModal({ ids, onClose, onSuccess }: { ids: string[]; onClose
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={onClose}>
|
||||
<div className="bg-slate-800 border border-slate-600 rounded-xl p-6 w-full max-w-md shadow-2xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-slate-200 mb-2">Reassign Owner</h2>
|
||||
<p className="text-sm text-slate-400 mb-4">
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={onClose}>
|
||||
<div className="bg-surface border border-surface-border rounded p-6 w-full max-w-md shadow-xl" onClick={e => e.stopPropagation()}>
|
||||
<h2 className="text-lg font-semibold text-ink mb-2">Reassign Owner</h2>
|
||||
<p className="text-sm text-ink-muted mb-4">
|
||||
Reassign {ids.length} certificate{ids.length > 1 ? 's' : ''} to a new owner.
|
||||
</p>
|
||||
{error && <div className="bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-3 py-2 text-sm mb-3">{error}</div>}
|
||||
{error && <div className="bg-red-50 border border-red-200 text-red-700 rounded px-3 py-2 text-sm mb-3">{error}</div>}
|
||||
{running && (
|
||||
<div className="mb-3">
|
||||
<div className="flex justify-between text-xs text-slate-400 mb-1">
|
||||
<div className="flex justify-between text-xs text-ink-muted mb-1">
|
||||
<span>Progress</span>
|
||||
<span>{progress}/{ids.length}</span>
|
||||
</div>
|
||||
<div className="w-full bg-slate-700 rounded-full h-2">
|
||||
<div className="bg-blue-500 h-2 rounded-full transition-all" style={{ width: `${(progress / ids.length) * 100}%` }} />
|
||||
<div className="w-full bg-surface-border rounded-full h-2">
|
||||
<div className="bg-brand-400 h-2 rounded-full transition-all" style={{ width: `${(progress / ids.length) * 100}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<label className="text-xs text-slate-400 block mb-2">New Owner</label>
|
||||
<label className="text-xs text-ink-muted block mb-2">New Owner</label>
|
||||
<select value={ownerId} onChange={e => setOwnerId(e.target.value)}
|
||||
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-slate-200 mb-4"
|
||||
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink mb-4"
|
||||
disabled={running}
|
||||
>
|
||||
<option value="">Select owner...</option>
|
||||
@@ -276,8 +276,8 @@ export default function CertificatesPage() {
|
||||
label: 'Certificate',
|
||||
render: (c) => (
|
||||
<div>
|
||||
<div className="font-medium text-slate-200">{c.common_name}</div>
|
||||
<div className="text-xs text-slate-500 mt-0.5">{c.id}</div>
|
||||
<div className="font-medium text-ink">{c.common_name}</div>
|
||||
<div className="text-xs text-ink-faint mt-0.5">{c.id}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -290,14 +290,14 @@ export default function CertificatesPage() {
|
||||
return (
|
||||
<div>
|
||||
<div className={expiryColor(days)}>{formatDate(c.expires_at)}</div>
|
||||
<div className="text-xs text-slate-500">{days <= 0 ? 'Expired' : `${days} days`}</div>
|
||||
<div className="text-xs text-ink-faint">{days <= 0 ? 'Expired' : `${days} days`}</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{ key: 'env', label: 'Environment', render: (c) => <span className="text-slate-300">{c.environment || '—'}</span> },
|
||||
{ key: 'issuer', label: 'Issuer', render: (c) => <span className="text-slate-400 text-xs">{c.issuer_id}</span> },
|
||||
{ key: 'owner', label: 'Owner', render: (c) => <span className="text-slate-400 text-xs">{c.owner_id}</span> },
|
||||
{ key: 'env', label: 'Environment', render: (c) => <span className="text-ink-muted">{c.environment || '—'}</span> },
|
||||
{ key: 'issuer', label: 'Issuer', render: (c) => <span className="text-ink-muted text-xs">{c.issuer_id}</span> },
|
||||
{ key: 'owner', label: 'Owner', render: (c) => <span className="text-ink-muted text-xs">{c.owner_id}</span> },
|
||||
];
|
||||
|
||||
const selectedArray = Array.from(selectedIds);
|
||||
@@ -317,8 +317,8 @@ export default function CertificatesPage() {
|
||||
|
||||
{/* Bulk Action Bar */}
|
||||
{hasSelection && (
|
||||
<div className="px-6 py-3 bg-blue-500/10 border-b border-blue-500/20 flex items-center justify-between">
|
||||
<span className="text-sm text-blue-400 font-medium">{selectedArray.length} selected</span>
|
||||
<div className="px-6 py-3 bg-brand-50 border-b border-brand-200 flex items-center justify-between">
|
||||
<span className="text-sm text-brand-600 font-medium">{selectedArray.length} selected</span>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={handleBulkRenewal} disabled={bulkRenewProgress?.running}
|
||||
className="btn btn-primary text-xs disabled:opacity-50">
|
||||
@@ -331,11 +331,11 @@ export default function CertificatesPage() {
|
||||
Revoke
|
||||
</button>
|
||||
<button onClick={() => setShowBulkReassign(true)}
|
||||
className="btn btn-ghost text-xs text-blue-400 hover:text-blue-300 border border-blue-600/50">
|
||||
className="btn btn-ghost text-xs text-brand-400 hover:text-brand-300 border border-brand-600/50">
|
||||
Reassign Owner
|
||||
</button>
|
||||
<button onClick={() => setSelectedIds(new Set())}
|
||||
className="btn btn-ghost text-xs text-slate-400">
|
||||
className="btn btn-ghost text-xs text-ink-muted">
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
@@ -344,18 +344,18 @@ export default function CertificatesPage() {
|
||||
|
||||
{/* Bulk Renewal Success */}
|
||||
{bulkRenewProgress && !bulkRenewProgress.running && (
|
||||
<div className="px-6 py-2 bg-emerald-500/10 border-b border-emerald-500/20">
|
||||
<span className="text-sm text-emerald-400">
|
||||
<div className="px-6 py-2 bg-emerald-50 border-b border-emerald-200">
|
||||
<span className="text-sm text-emerald-700">
|
||||
Triggered renewal for {bulkRenewProgress.done} certificate{bulkRenewProgress.done > 1 ? 's' : ''}.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="px-6 py-3 flex gap-3 border-b border-slate-700/50">
|
||||
<div className="px-6 py-3 flex gap-3 border-b border-surface-border/50">
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={e => setStatusFilter(e.target.value)}
|
||||
className="bg-slate-800 border border-slate-600 rounded-lg px-3 py-1.5 text-sm text-slate-300"
|
||||
className="bg-white border border-surface-border rounded px-3 py-1.5 text-sm text-ink"
|
||||
>
|
||||
<option value="">All statuses</option>
|
||||
<option value="Active">Active</option>
|
||||
@@ -368,7 +368,7 @@ export default function CertificatesPage() {
|
||||
<select
|
||||
value={envFilter}
|
||||
onChange={e => setEnvFilter(e.target.value)}
|
||||
className="bg-slate-800 border border-slate-600 rounded-lg px-3 py-1.5 text-sm text-slate-300"
|
||||
className="bg-white border border-surface-border rounded px-3 py-1.5 text-sm text-ink"
|
||||
>
|
||||
<option value="">All environments</option>
|
||||
<option value="production">Production</option>
|
||||
|
||||
@@ -13,34 +13,38 @@ import PageHeader from '../components/PageHeader';
|
||||
import StatusBadge from '../components/StatusBadge';
|
||||
import { daysUntil, expiryColor, formatDate } from '../api/utils';
|
||||
|
||||
// Convert PascalCase status like "RenewalInProgress" to "Renewal In Progress"
|
||||
const formatStatus = (s: string) => s.replace(/([a-z])([A-Z])/g, '$1 $2');
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
Active: '#10b981',
|
||||
Expiring: '#f59e0b',
|
||||
Expired: '#ef4444',
|
||||
Revoked: '#8b5cf6',
|
||||
Pending: '#6366f1',
|
||||
RenewalInProgress: '#3b82f6',
|
||||
RenewalInProgress: '#2ea88f',
|
||||
Failed: '#f43f5e',
|
||||
Archived: '#64748b',
|
||||
};
|
||||
|
||||
function StatCard({ label, value, icon, color }: { label: string; value: string | number; icon: string; color: string }) {
|
||||
const colorMap: Record<string, string> = {
|
||||
success: 'bg-emerald-500/10 text-emerald-400',
|
||||
warning: 'bg-amber-500/10 text-amber-400',
|
||||
danger: 'bg-red-500/10 text-red-400',
|
||||
info: 'bg-blue-500/10 text-blue-400',
|
||||
const colorMap: Record<string, { bg: string; border: string; text: string }> = {
|
||||
success: { bg: 'bg-emerald-50', border: 'border-t-emerald-500', text: 'text-emerald-700' },
|
||||
warning: { bg: 'bg-amber-50', border: 'border-t-amber-500', text: 'text-amber-700' },
|
||||
danger: { bg: 'bg-red-50', border: 'border-t-red-500', text: 'text-red-700' },
|
||||
info: { bg: 'bg-blue-50', border: 'border-t-brand-400', text: 'text-brand-500' },
|
||||
};
|
||||
const config = colorMap[color] || colorMap.info;
|
||||
return (
|
||||
<div className="card p-5 flex items-start gap-4 hover:border-blue-500/30 transition-colors">
|
||||
<div className={`w-10 h-10 rounded-lg flex items-center justify-center shrink-0 ${colorMap[color] || colorMap.info}`}>
|
||||
<div className={`bg-surface border border-surface-border border-t-4 ${config.border} rounded p-5 flex items-start gap-4 hover:bg-surface-muted transition-colors shadow-sm`}>
|
||||
<div className={`w-10 h-10 rounded flex items-center justify-center shrink-0 ${config.bg} ${config.text}`}>
|
||||
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d={icon} />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-slate-400 uppercase tracking-wider">{label}</p>
|
||||
<p className="text-2xl font-bold mt-1">{value}</p>
|
||||
<p className="text-xs font-semibold text-ink-muted uppercase tracking-wider">{label}</p>
|
||||
<p className="text-2xl font-bold mt-1 text-ink">{value}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -48,8 +52,8 @@ function StatCard({ label, value, icon, color }: { label: string; value: string
|
||||
|
||||
function ChartCard({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-slate-300 mb-4">{title}</h3>
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-ink-muted mb-4">{title}</h3>
|
||||
<div className="h-64">
|
||||
{children}
|
||||
</div>
|
||||
@@ -60,8 +64,8 @@ function ChartCard({ title, children }: { title: string; children: React.ReactNo
|
||||
const CustomTooltip = ({ active, payload, label }: any) => {
|
||||
if (!active || !payload?.length) return null;
|
||||
return (
|
||||
<div className="bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-xs shadow-lg">
|
||||
<p className="text-slate-300 mb-1">{label}</p>
|
||||
<div className="bg-surface border border-surface-border rounded px-3 py-2 text-xs shadow-lg">
|
||||
<p className="text-ink mb-1">{label}</p>
|
||||
{payload.map((entry: any, i: number) => (
|
||||
<p key={i} style={{ color: entry.color }}>
|
||||
{entry.name}: {typeof entry.value === 'number' && entry.name?.includes('rate') ? `${entry.value.toFixed(1)}%` : entry.value}
|
||||
@@ -148,7 +152,7 @@ export default function DashboardPage() {
|
||||
outerRadius={90}
|
||||
paddingAngle={2}
|
||||
dataKey="value"
|
||||
label={({ name, value }) => `${name}: ${value}`}
|
||||
label={({ name, value }) => `${formatStatus(name || '')}: ${value}`}
|
||||
labelLine={false}
|
||||
>
|
||||
{pieData.map((entry, index) => (
|
||||
@@ -159,12 +163,12 @@ export default function DashboardPage() {
|
||||
<Legend
|
||||
verticalAlign="bottom"
|
||||
height={36}
|
||||
formatter={(value: string) => <span className="text-xs text-slate-400">{value}</span>}
|
||||
formatter={(value: string) => <span className="text-xs text-ink-muted">{formatStatus(value)}</span>}
|
||||
/>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center text-sm text-slate-500">No certificate data</div>
|
||||
<div className="h-full flex items-center justify-center text-sm text-ink-faint">No certificate data</div>
|
||||
)}
|
||||
</ChartCard>
|
||||
|
||||
@@ -173,15 +177,15 @@ export default function DashboardPage() {
|
||||
{weeklyExpiration.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={weeklyExpiration}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#334155" />
|
||||
<XAxis dataKey="week" tick={{ fill: '#94a3b8', fontSize: 11 }} tickFormatter={formatShortDate} />
|
||||
<YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} allowDecimals={false} />
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
|
||||
<XAxis dataKey="week" tick={{ fill: '#64748b', fontSize: 11 }} tickFormatter={formatShortDate} />
|
||||
<YAxis tick={{ fill: '#64748b', fontSize: 11 }} allowDecimals={false} />
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Bar dataKey="count" name="Expiring certs" fill="#f59e0b" radius={[4, 4, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center text-sm text-slate-500">No expiration data</div>
|
||||
<div className="h-full flex items-center justify-center text-sm text-ink-faint">No expiration data</div>
|
||||
)}
|
||||
</ChartCard>
|
||||
</div>
|
||||
@@ -193,17 +197,17 @@ export default function DashboardPage() {
|
||||
{(jobTrends || []).length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<LineChart data={jobTrends}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#334155" />
|
||||
<XAxis dataKey="date" tick={{ fill: '#94a3b8', fontSize: 11 }} tickFormatter={formatShortDate} />
|
||||
<YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} allowDecimals={false} />
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
|
||||
<XAxis dataKey="date" tick={{ fill: '#64748b', fontSize: 11 }} tickFormatter={formatShortDate} />
|
||||
<YAxis tick={{ fill: '#64748b', fontSize: 11 }} allowDecimals={false} />
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Legend formatter={(value: string) => <span className="text-xs text-slate-400">{value}</span>} />
|
||||
<Legend formatter={(value: string) => <span className="text-xs text-ink-muted">{value}</span>} />
|
||||
<Line type="monotone" dataKey="completed_count" name="Completed" stroke="#10b981" strokeWidth={2} dot={false} />
|
||||
<Line type="monotone" dataKey="failed_count" name="Failed" stroke="#ef4444" strokeWidth={2} dot={false} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center text-sm text-slate-500">No job trend data</div>
|
||||
<div className="h-full flex items-center justify-center text-sm text-ink-faint">No job trend data</div>
|
||||
)}
|
||||
</ChartCard>
|
||||
|
||||
@@ -212,28 +216,28 @@ export default function DashboardPage() {
|
||||
{(issuanceRate || []).length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={issuanceRate}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#334155" />
|
||||
<XAxis dataKey="date" tick={{ fill: '#94a3b8', fontSize: 11 }} tickFormatter={formatShortDate} />
|
||||
<YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} allowDecimals={false} />
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
|
||||
<XAxis dataKey="date" tick={{ fill: '#64748b', fontSize: 11 }} tickFormatter={formatShortDate} />
|
||||
<YAxis tick={{ fill: '#64748b', fontSize: 11 }} allowDecimals={false} />
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Bar dataKey="issued_count" name="Issued" fill="#3b82f6" radius={[4, 4, 0, 0]} />
|
||||
<Bar dataKey="issued_count" name="Issued" fill="#2ea88f" radius={[4, 4, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center text-sm text-slate-500">No issuance data</div>
|
||||
<div className="h-full flex items-center justify-center text-sm text-ink-faint">No issuance data</div>
|
||||
)}
|
||||
</ChartCard>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Expiring Certificates */}
|
||||
<div className="card p-5">
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-sm font-semibold text-slate-300">Certificates Expiring Soon</h3>
|
||||
<button onClick={() => navigate('/certificates')} className="text-xs text-blue-400 hover:text-blue-300">View all</button>
|
||||
<h3 className="text-sm font-semibold text-ink-muted">Certificates Expiring Soon</h3>
|
||||
<button onClick={() => navigate('/certificates')} className="text-xs text-brand-400 hover:text-brand-500">View all</button>
|
||||
</div>
|
||||
{!certs?.data?.length ? (
|
||||
<p className="text-sm text-slate-500">No certificates</p>
|
||||
<p className="text-sm text-ink-faint">No certificates</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{certs.data
|
||||
@@ -246,17 +250,17 @@ export default function DashboardPage() {
|
||||
<div
|
||||
key={c.id}
|
||||
onClick={() => navigate(`/certificates/${c.id}`)}
|
||||
className="flex items-center justify-between py-2 px-3 rounded-lg hover:bg-slate-700/50 cursor-pointer transition-colors"
|
||||
className="flex items-center justify-between py-2 px-3 rounded hover:bg-surface-muted cursor-pointer transition-colors"
|
||||
>
|
||||
<div>
|
||||
<div className="text-sm text-slate-200">{c.common_name}</div>
|
||||
<div className="text-xs text-slate-500">{c.environment || 'no env'}</div>
|
||||
<div className="text-sm text-ink">{c.common_name}</div>
|
||||
<div className="text-xs text-ink-faint">{c.environment || 'no env'}</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className={`text-sm ${expiryColor(days)}`}>
|
||||
{days <= 0 ? 'Expired' : `${days} days`}
|
||||
</div>
|
||||
<div className="text-xs text-slate-500">{formatDate(c.expires_at)}</div>
|
||||
<div className="text-xs text-ink-faint">{formatDate(c.expires_at)}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -266,20 +270,20 @@ export default function DashboardPage() {
|
||||
</div>
|
||||
|
||||
{/* Recent Jobs */}
|
||||
<div className="card p-5">
|
||||
<div className="bg-surface border border-surface-border rounded p-5 shadow-sm">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-sm font-semibold text-slate-300">Recent Jobs</h3>
|
||||
<button onClick={() => navigate('/jobs')} className="text-xs text-blue-400 hover:text-blue-300">View all</button>
|
||||
<h3 className="text-sm font-semibold text-ink-muted">Recent Jobs</h3>
|
||||
<button onClick={() => navigate('/jobs')} className="text-xs text-brand-400 hover:text-brand-500">View all</button>
|
||||
</div>
|
||||
{!jobs?.data?.length ? (
|
||||
<p className="text-sm text-slate-500">No jobs</p>
|
||||
<p className="text-sm text-ink-faint">No jobs</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{jobs.data.slice(0, 5).map(j => (
|
||||
<div key={j.id} className="flex items-center justify-between py-2 px-3 rounded-lg hover:bg-slate-700/50 transition-colors">
|
||||
<div key={j.id} className="flex items-center justify-between py-2 px-3 rounded hover:bg-surface-muted transition-colors">
|
||||
<div>
|
||||
<div className="text-sm text-slate-200">{j.type}</div>
|
||||
<div className="text-xs text-slate-500 font-mono">{j.certificate_id}</div>
|
||||
<div className="text-sm text-ink">{j.type}</div>
|
||||
<div className="text-xs text-ink-faint font-mono">{j.certificate_id}</div>
|
||||
</div>
|
||||
<StatusBadge status={j.status} />
|
||||
</div>
|
||||
@@ -291,10 +295,10 @@ export default function DashboardPage() {
|
||||
|
||||
{/* Pending Jobs Banner */}
|
||||
{pendingJobs > 0 && (
|
||||
<div className="bg-blue-500/10 border border-blue-500/20 rounded-lg px-5 py-4 flex items-center justify-between">
|
||||
<div className="bg-brand-50 border border-brand-200 rounded px-5 py-4 flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-blue-400">{pendingJobs} pending job{pendingJobs > 1 ? 's' : ''}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">Jobs are waiting to be processed</p>
|
||||
<p className="text-sm font-medium text-brand-600">{pendingJobs} pending job{pendingJobs > 1 ? 's' : ''}</p>
|
||||
<p className="text-xs text-brand-600/70 mt-0.5">Jobs are waiting to be processed</p>
|
||||
</div>
|
||||
<button onClick={() => navigate('/jobs')} className="btn btn-primary text-xs">View Jobs</button>
|
||||
</div>
|
||||
|
||||