mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 21:21:40 +00:00
Compare commits
59 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f146e08d6 | |||
| e6088c79a3 | |||
| e19b8c95fe | |||
| 995b72df05 | |||
| 9954fd1100 | |||
| 2a14a1da01 | |||
| 5a53b648b1 | |||
| cb72292b83 | |||
| 3a11e447cf | |||
| bad02e6f23 | |||
| 4c3b7cbb16 | |||
| e8c64b47dd | |||
| 9feb6c796d | |||
| fd05bacb76 | |||
| f51571297d | |||
| 9a41d0ca39 | |||
| 8b52da6aef | |||
| adfb682754 | |||
| 0822f748a5 | |||
| 368ea681a5 | |||
| b059ec930f | |||
| 2238f28610 | |||
| bbba618beb | |||
| cfc4d3f3e8 | |||
| c06d23dd7a | |||
| 6c8d4eca40 | |||
| 836534f2a7 | |||
| 648e2f7ab1 | |||
| 6375909591 | |||
| 3e5ff4b9c3 | |||
| 76d0ce2a0f | |||
| 207f2c6879 | |||
| 46a58d518a | |||
| c5be6d059f | |||
| ec209c9736 | |||
| d4f02c5f4b | |||
| 2409f2e464 | |||
| 225c7141b8 | |||
| 8807a7303d | |||
| a6515b4323 | |||
| 11173a74c6 | |||
| ec0e7a3560 | |||
| a0b9285323 | |||
| 2655493ac8 | |||
| a8fc177118 | |||
| 20378ea7bb | |||
| bcf2c3ae92 | |||
| 5f81de3219 | |||
| 397d2a1588 | |||
| 65567d0d83 | |||
| 0abd984285 | |||
| ec21c9bb29 | |||
| cb2ef9d0e7 | |||
| da79dde611 | |||
| 935ea1bf9f | |||
| 11e752ac01 | |||
| 03472072b8 | |||
| 63e6f3ef91 | |||
| a00bb349c4 |
@@ -125,3 +125,20 @@ jobs:
|
||||
- name: Build Frontend
|
||||
working-directory: web
|
||||
run: npx vite build
|
||||
|
||||
helm-lint:
|
||||
name: Helm Chart Validation
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Helm
|
||||
uses: azure/setup-helm@v4
|
||||
with:
|
||||
version: '3.13.0'
|
||||
|
||||
- name: Lint Helm Chart
|
||||
run: helm lint deploy/helm/certctl/
|
||||
|
||||
- name: Template Helm Chart
|
||||
run: helm template certctl deploy/helm/certctl/ > /dev/null
|
||||
|
||||
@@ -7,9 +7,74 @@ on:
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
GO_VERSION: '1.22'
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
# Cross-compile agent and server binaries for multiple platforms
|
||||
build-binaries:
|
||||
name: Build Cross-Platform Binaries
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
# Agent binaries (4 platforms)
|
||||
- os: linux
|
||||
arch: amd64
|
||||
binary: agent
|
||||
- os: linux
|
||||
arch: arm64
|
||||
binary: agent
|
||||
- os: darwin
|
||||
arch: amd64
|
||||
binary: agent
|
||||
- os: darwin
|
||||
arch: arm64
|
||||
binary: agent
|
||||
# Server binaries (2 platforms)
|
||||
- os: linux
|
||||
arch: amd64
|
||||
binary: server
|
||||
- os: linux
|
||||
arch: arm64
|
||||
binary: server
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
|
||||
- name: Extract version from tag
|
||||
id: version
|
||||
run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Build ${{ matrix.binary }} binary (${{ matrix.os }}-${{ matrix.arch }})
|
||||
env:
|
||||
GOOS: ${{ matrix.os }}
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
CGO_ENABLED: 0
|
||||
run: |
|
||||
OUTPUT_NAME="certctl-${{ matrix.binary }}-${{ matrix.os }}-${{ matrix.arch }}"
|
||||
go build -ldflags="-w -s -X main.Version=${{ steps.version.outputs.VERSION }}" \
|
||||
-o "dist/${OUTPUT_NAME}" \
|
||||
"./cmd/${{ matrix.binary }}"
|
||||
ls -lh "dist/${OUTPUT_NAME}"
|
||||
|
||||
- name: Upload binaries to release
|
||||
uses: softprops/action-gh-release@v2
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
files: |
|
||||
dist/certctl-agent-*
|
||||
dist/certctl-server-*
|
||||
|
||||
# Build and push Docker images
|
||||
build-and-push-docker:
|
||||
name: Build & Push Docker Images
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -57,19 +122,67 @@ jobs:
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: Create GitHub Release
|
||||
# Create release notes with all artifacts
|
||||
create-release:
|
||||
name: Create Release Notes
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build-binaries, build-and-push-docker]
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Extract version from tag
|
||||
id: version
|
||||
run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create release with notes
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
generate_release_notes: true
|
||||
body: |
|
||||
## Docker Images
|
||||
## Installation
|
||||
|
||||
### Quick Install (Linux/macOS)
|
||||
|
||||
```bash
|
||||
docker pull shankar0123.docker.scarf.sh/certctl-server:${{ steps.version.outputs.VERSION }}
|
||||
docker pull shankar0123.docker.scarf.sh/certctl-agent:${{ steps.version.outputs.VERSION }}
|
||||
curl -sSL https://raw.githubusercontent.com/shankar0123/certctl/master/install-agent.sh | bash
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
### Manual Binary Download
|
||||
|
||||
Download the appropriate binary for your OS and architecture:
|
||||
|
||||
- **Linux x86_64**: `certctl-agent-linux-amd64`
|
||||
- **Linux ARM64**: `certctl-agent-linux-arm64`
|
||||
- **macOS x86_64**: `certctl-agent-darwin-amd64`
|
||||
- **macOS ARM64 (Apple Silicon)**: `certctl-agent-darwin-arm64`
|
||||
|
||||
Then make it executable and start the service:
|
||||
|
||||
```bash
|
||||
chmod +x certctl-agent-linux-amd64
|
||||
sudo mv certctl-agent-linux-amd64 /usr/local/bin/certctl-agent
|
||||
```
|
||||
|
||||
## Docker Images
|
||||
|
||||
Pull pre-built Docker images for server and agent:
|
||||
|
||||
```bash
|
||||
docker pull ghcr.io/shankar0123/certctl-server:${{ steps.version.outputs.VERSION }}
|
||||
docker pull ghcr.io/shankar0123/certctl-agent:${{ steps.version.outputs.VERSION }}
|
||||
```
|
||||
|
||||
Or use the latest tag:
|
||||
|
||||
```bash
|
||||
docker pull ghcr.io/shankar0123/certctl-server:latest
|
||||
docker pull ghcr.io/shankar0123/certctl-agent:latest
|
||||
```
|
||||
|
||||
## Docker Compose Quick Start
|
||||
|
||||
```bash
|
||||
git clone https://github.com/shankar0123/certctl.git
|
||||
@@ -77,3 +190,22 @@ jobs:
|
||||
cp deploy/.env.example deploy/.env
|
||||
docker compose -f deploy/docker-compose.yml up -d
|
||||
```
|
||||
|
||||
## Server Binaries
|
||||
|
||||
Pre-compiled server binaries are also available for direct installation:
|
||||
|
||||
- **Linux x86_64**: `certctl-server-linux-amd64`
|
||||
- **Linux ARM64**: `certctl-server-linux-arm64`
|
||||
|
||||
## Helm Chart
|
||||
|
||||
Deploy certctl to Kubernetes using Helm:
|
||||
|
||||
```bash
|
||||
helm repo add certctl https://github.com/shankar0123/certctl/tree/master/deploy/helm
|
||||
helm repo update
|
||||
helm install certctl certctl/certctl
|
||||
```
|
||||
|
||||
See `deploy/helm/certctl/` for values customization.
|
||||
|
||||
@@ -43,6 +43,11 @@ vendor/
|
||||
tmp/
|
||||
temp/
|
||||
*.log
|
||||
*.bak
|
||||
|
||||
# Private keys (agent-generated, never commit)
|
||||
cmd/agent/*.key
|
||||
cmd/agent/*.pem
|
||||
|
||||
# Database
|
||||
*.db
|
||||
@@ -57,6 +62,7 @@ certctl-agent
|
||||
certctl-cli
|
||||
/server
|
||||
/agent
|
||||
/cli
|
||||
|
||||
# Private strategy docs
|
||||
roadmap.md
|
||||
|
||||
@@ -19,7 +19,7 @@ Change Date: March 14, 2033
|
||||
Change License: Apache License, Version 2.0
|
||||
|
||||
For information about alternative licensing arrangements for the Licensed Work,
|
||||
please contact: skreddy040@gmail.com
|
||||
please contact: certctl@proton.me
|
||||
|
||||
Notice
|
||||
|
||||
|
||||
@@ -7,61 +7,70 @@
|
||||
|
||||
# certctl — Self-Hosted Certificate Lifecycle Platform
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
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)
|
||||
[](https://github.com/shankar0123/certctl/releases)
|
||||
[](https://github.com/shankar0123/certctl/stargazers)
|
||||
|
||||
## Documentation
|
||||
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.
|
||||
|
||||
| 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 |
|
||||
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. It's free, self-hosted, and covers the same lifecycle that enterprise platforms charge $100K+/year for.
|
||||
|
||||
```mermaid
|
||||
gantt
|
||||
title TLS Certificate Maximum Lifespan — CA/Browser Forum Ballot SC-081v3
|
||||
dateFormat YYYY-MM-DD
|
||||
axisFormat
|
||||
todayMarker off
|
||||
section 2015
|
||||
5 years (1825 days) :done, 2020-01-01, 1825d
|
||||
section 2018
|
||||
825 days :done, 2020-01-01, 825d
|
||||
section 2020
|
||||
398 days :active, 2020-01-01, 398d
|
||||
section 2026
|
||||
200 days :crit, 2020-01-01, 200d
|
||||
section 2027
|
||||
100 days :crit, 2020-01-01, 100d
|
||||
section 2029
|
||||
47 days :crit, 2020-01-01, 47d
|
||||
```
|
||||
|
||||
> **Actively maintained — shipping weekly.** Found something? [Open a GitHub issue](https://github.com/shankar0123/certctl/issues) — issues get triaged same-day. CI runs the full test suite with race detection, static analysis, and vulnerability scanning on every commit.
|
||||
|
||||
## 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.
|
||||
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, IIS on Windows, 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.
|
||||
certctl fills that gap. It's **CA-agnostic** — plug in any certificate authority: Let's Encrypt via ACME, Smallstep step-ca, HashiCorp Vault PKI, DigiCert CertCentral, your enterprise ADCS via sub-CA mode, or any custom CA through a shell script adapter. Run multiple issuers simultaneously for different certificate types.
|
||||
|
||||
It's also **target-agnostic**. Agents deploy certificates to NGINX, Apache, HAProxy, Traefik, and Caddy — 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.
|
||||
It's **target-agnostic**. Agents deploy certificates to NGINX, Apache, HAProxy, Traefik, Caddy, Envoy, Postfix, Dovecot, and IIS (local PowerShell or remote WinRM) — all using the same pluggable connector model. 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)
|
||||
For a detailed comparison with CertKit, KeyTalk, and enterprise platforms, see [Why certctl?](docs/why-certctl.md)
|
||||
|
||||
## Who Is This For
|
||||
|
||||
**Platform engineering and DevOps teams** managing 10–500+ certificates across mixed infrastructure who need automated renewal, deployment, and a single dashboard for visibility. If you're currently running certbot cron jobs, manually renewing certs, or stitching together scripts — certctl replaces all of that.
|
||||
|
||||
**Security and compliance teams** who need an immutable audit trail, certificate ownership tracking, policy enforcement, and evidence for SOC 2, PCI-DSS 4.0, or NIST SP 800-57 audits.
|
||||
|
||||
**Small teams without enterprise budgets** who need the lifecycle automation that Venafi and Keyfactor provide but can't justify six-figure licensing for a 50-server environment.
|
||||
|
||||
## What It Does
|
||||
|
||||
certctl gives you a single pane of glass for every TLS certificate in your organization:
|
||||
- **Certificates renew and deploy themselves.** The scheduler monitors expiration, creates renewal jobs, issues certificates through your CA, and deploys them to target servers — all without human intervention. ACME ARI (RFC 9702) lets your CA tell certctl exactly when to renew.
|
||||
|
||||
- **Web dashboard** — full certificate inventory with status, ownership, expiration heatmaps, and bulk operations
|
||||
- **REST API** — 93 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
|
||||
- **You see everything in one place.** A 25-page operational dashboard shows every certificate across every server: status, ownership, expiration timeline, deployment history with TLS verification, discovery triage, and real-time agent fleet health. Bulk operations (renew, revoke, reassign) work across selections.
|
||||
|
||||
For the full capability breakdown — revocation infrastructure, policy engine, observability, EST enrollment, and more — see the [Feature Inventory](docs/features.md).
|
||||
- **Private keys never leave your servers.** Agents generate ECDSA P-256 keys locally and submit only the CSR. The control plane never touches private keys. Post-deployment TLS verification confirms the right certificate is actually being served.
|
||||
|
||||
- **Discover what you don't know about.** Agents scan filesystems for existing PEM/DER certificates. The network scanner probes TLS endpoints across CIDR ranges without requiring agents. Both feed into a triage workflow where you claim, dismiss, or import discovered certificates.
|
||||
|
||||
- **Everything is auditable.** Immutable append-only audit trail records every lifecycle action, every API call, and every approval decision. Certificate digest emails deliver daily briefings. Prometheus metrics endpoint for Grafana dashboards.
|
||||
|
||||
- **Multiple interfaces for different workflows.** REST API (97 endpoints) for automation, CLI for scripting, MCP server for AI assistants (Claude, Cursor, Windsurf), EST server (RFC 7030) for device enrollment, Helm chart for Kubernetes, and the web dashboard for day-to-day operations.
|
||||
|
||||
For the full capability breakdown — revocation infrastructure (CRL + OCSP), policy engine, certificate profiles, S/MIME support, approval workflows, and more — see the [Feature Inventory](docs/features.md).
|
||||
|
||||
## Supported Integrations
|
||||
|
||||
@@ -73,8 +82,12 @@ For the full capability breakdown — revocation infrastructure, policy engine,
|
||||
| ACME EAB (ZeroSSL, Google Trust) | Implemented (auto-fetch EAB from ZeroSSL) | `ACME` |
|
||||
| step-ca | Implemented | `StepCA` |
|
||||
| OpenSSL / Custom CA | Implemented | `OpenSSL` |
|
||||
| Vault PKI | Future | — |
|
||||
| DigiCert | Future | — |
|
||||
| Vault PKI | Beta | `VaultPKI` |
|
||||
| DigiCert CertCentral | Beta | `DigiCert` |
|
||||
| Sectigo SCM | Beta | `Sectigo` |
|
||||
| Google CAS | Beta | `GoogleCAS` |
|
||||
|
||||
**Vault PKI, DigiCert, Sectigo, and Google CAS connectors are in beta.** If you hit any bugs or unexpected behavior, please [open a GitHub issue](https://github.com/shankar0123/certctl/issues) -- we're actively testing these and want to hear from real users.
|
||||
|
||||
**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.
|
||||
|
||||
@@ -86,8 +99,11 @@ For the full capability breakdown — revocation infrastructure, policy engine,
|
||||
| HAProxy | Implemented | `HAProxy` |
|
||||
| Traefik | Implemented | `Traefik` |
|
||||
| Caddy | Implemented | `Caddy` |
|
||||
| F5 BIG-IP | Interface only | `F5` |
|
||||
| Microsoft IIS | Interface only | `IIS` |
|
||||
| Envoy | Implemented | `Envoy` |
|
||||
| Postfix | Implemented | `Postfix` |
|
||||
| Dovecot | Implemented | `Dovecot` |
|
||||
| Microsoft IIS | Implemented (local + WinRM) | `IIS` |
|
||||
| F5 BIG-IP | Beta | `F5` |
|
||||
|
||||
### Notifiers
|
||||
| Notifier | Status | Type |
|
||||
@@ -117,10 +133,10 @@ All connectors are pluggable — build your own by implementing the [connector i
|
||||
<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>
|
||||
<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, Vault PKI, DigiCert</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, Traefik, Caddy deployment</sub></td>
|
||||
<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, Traefik, Caddy, IIS 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>
|
||||
@@ -133,13 +149,6 @@ All connectors are pluggable — build your own by implementing the [connector i
|
||||
|
||||
## 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
|
||||
@@ -150,43 +159,48 @@ docker compose -f deploy/docker-compose.yml up -d --build
|
||||
|
||||
Wait ~30 seconds, then open **http://localhost:8443** in your browser.
|
||||
|
||||
The dashboard comes pre-loaded with 15 demo certificates, 5 agents, policy rules, audit events, and notifications — a realistic snapshot of a certificate inventory so you can explore immediately.
|
||||
The dashboard comes pre-loaded with 32 demo certificates across 7 issuers, 8 agents, 180 days of job history, discovery scan data, and network scan targets — a realistic snapshot of a certificate inventory that looks like it's been running for months.
|
||||
|
||||
Verify the API:
|
||||
```bash
|
||||
curl http://localhost:8443/health
|
||||
# {"status":"healthy"}
|
||||
|
||||
curl -s http://localhost:8443/api/v1/certificates | jq '.total'
|
||||
# 15
|
||||
# 32
|
||||
```
|
||||
|
||||
### Manual Build
|
||||
### Agent Install (One-Liner)
|
||||
|
||||
```bash
|
||||
# Prerequisites: Go 1.25+, PostgreSQL 16+
|
||||
go mod download
|
||||
make build
|
||||
|
||||
# Set up database
|
||||
export CERTCTL_DATABASE_URL="postgres://certctl:certctl@localhost:5432/certctl?sslmode=disable"
|
||||
export CERTCTL_AUTH_TYPE=none
|
||||
make migrate-up
|
||||
|
||||
# Start server
|
||||
./bin/server
|
||||
|
||||
# Start agent (separate terminal)
|
||||
export CERTCTL_SERVER_URL=http://localhost:8443
|
||||
export CERTCTL_API_KEY=change-me-in-production
|
||||
export CERTCTL_AGENT_NAME=local-agent
|
||||
export CERTCTL_AGENT_ID=agent-local-01
|
||||
./bin/agent --agent-id=agent-local-01
|
||||
curl -sSL https://raw.githubusercontent.com/shankar0123/certctl/master/install-agent.sh | bash
|
||||
```
|
||||
|
||||
Detects your OS and architecture, downloads the binary, configures systemd (Linux) or launchd (macOS), and starts the agent. See [install-agent.sh](install-agent.sh) for details.
|
||||
|
||||
### Docker Pull
|
||||
|
||||
```bash
|
||||
docker pull shankar0123.docker.scarf.sh/certctl-server
|
||||
docker pull shankar0123.docker.scarf.sh/certctl-agent
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
Pick the scenario closest to your setup and have it running in 2 minutes.
|
||||
|
||||
| Example | Scenario |
|
||||
|---------|----------|
|
||||
| [`examples/acme-nginx/`](examples/acme-nginx/) | Let's Encrypt + NGINX, HTTP-01 challenges |
|
||||
| [`examples/acme-wildcard-dns01/`](examples/acme-wildcard-dns01/) | Wildcard certs via DNS-01 (Cloudflare hook included) |
|
||||
| [`examples/private-ca-traefik/`](examples/private-ca-traefik/) | Local CA (self-signed or sub-CA) + Traefik file provider |
|
||||
| [`examples/step-ca-haproxy/`](examples/step-ca-haproxy/) | Smallstep step-ca + HAProxy combined PEM |
|
||||
| [`examples/multi-issuer/`](examples/multi-issuer/) | ACME for public + Local CA for internal, one dashboard |
|
||||
|
||||
Each directory contains a `docker-compose.yml` and a `README.md` explaining the scenario, prerequisites, and customization.
|
||||
|
||||
## Architecture
|
||||
|
||||
**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.
|
||||
**Control plane** (Go 1.25 net/http) → **PostgreSQL 16** (21 tables, TEXT primary keys) → **Agents** (key generation, CSR submission, cert deployment). For Windows servers without a local agent, a proxy agent in the same network zone handles deployment via WinRM. Background scheduler runs 7 loops: renewal checks (1h), job processing (30s), agent health (2m), notifications (1m), short-lived cert expiry (30s), network scanning (6h), certificate digest (24h). See [Architecture Guide](docs/architecture.md) for full system diagrams and data flow.
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
@@ -195,200 +209,20 @@ export CERTCTL_AGENT_ID=agent-local-01
|
||||
- **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.
|
||||
|
||||
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.
|
||||
## Documentation
|
||||
|
||||
## Configuration
|
||||
|
||||
All environment variables use the `CERTCTL_` prefix. Full reference below (39 variables across server, agent, and connector config).
|
||||
|
||||
### Server — Core
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_SERVER_HOST` | `127.0.0.1` | Server bind address |
|
||||
| `CERTCTL_SERVER_PORT` | `8080` | Server listen port (1–65535) |
|
||||
| `CERTCTL_DATABASE_URL` | `postgres://localhost/certctl` | PostgreSQL connection string (required) |
|
||||
| `CERTCTL_DATABASE_MAX_CONNS` | `25` | PostgreSQL connection pool size (min 1) |
|
||||
| `CERTCTL_DATABASE_MIGRATIONS_PATH` | `./migrations` | Path to migration SQL files |
|
||||
| `CERTCTL_MAX_BODY_SIZE` | `1048576` | Max HTTP request body in bytes (default 1MB) |
|
||||
| `CERTCTL_LOG_LEVEL` | `info` | Log verbosity: `debug`, `info`, `warn`, `error` |
|
||||
| `CERTCTL_LOG_FORMAT` | `json` | Log format: `json` (structured) or `text` (human-readable) |
|
||||
|
||||
### Server — Auth, CORS, Rate Limiting
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_AUTH_TYPE` | `api-key` | Auth mode: `api-key`, `jwt`, or `none` (demo only) |
|
||||
| `CERTCTL_AUTH_SECRET` | — | Required for `api-key` and `jwt` auth types |
|
||||
| `CERTCTL_CORS_ORIGINS` | *(empty = deny all)* | Comma-separated allowed origins, or `*` for dev |
|
||||
| `CERTCTL_RATE_LIMIT_ENABLED` | `true` | Enable token bucket rate limiting |
|
||||
| `CERTCTL_RATE_LIMIT_RPS` | `50` | Requests per second per client |
|
||||
| `CERTCTL_RATE_LIMIT_BURST` | `100` | Max burst size |
|
||||
| `CERTCTL_KEYGEN_MODE` | `agent` | Key generation: `agent` (production) or `server` (demo only) |
|
||||
|
||||
### Server — Scheduler
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_SCHEDULER_RENEWAL_CHECK_INTERVAL` | `1h` | How often to check expiring certs (min 1m) |
|
||||
| `CERTCTL_SCHEDULER_JOB_PROCESSOR_INTERVAL` | `30s` | How often to process pending jobs (min 1s) |
|
||||
| `CERTCTL_SCHEDULER_AGENT_HEALTH_CHECK_INTERVAL` | `2m` | Agent heartbeat check frequency (min 1s) |
|
||||
| `CERTCTL_SCHEDULER_NOTIFICATION_PROCESS_INTERVAL` | `1m` | Notification send frequency (min 1s) |
|
||||
|
||||
### Server — Sub-CA Mode
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_CA_CERT_PATH` | — | PEM-encoded CA certificate for sub-CA mode |
|
||||
| `CERTCTL_CA_KEY_PATH` | — | PEM-encoded CA private key (RSA, ECDSA, PKCS#8) |
|
||||
|
||||
### Server — Feature Flags
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_EST_ENABLED` | `false` | Enable RFC 7030 EST enrollment endpoints |
|
||||
| `CERTCTL_EST_ISSUER_ID` | `iss-local` | Which issuer processes EST enrollments |
|
||||
| `CERTCTL_EST_PROFILE_ID` | — | Constrain EST to a specific certificate profile |
|
||||
| `CERTCTL_NETWORK_SCAN_ENABLED` | `false` | Enable server-side TLS network scanning |
|
||||
| `CERTCTL_NETWORK_SCAN_INTERVAL` | `6h` | How often scheduled scans run |
|
||||
| `CERTCTL_VERIFY_DEPLOYMENT` | `true` | TLS verification after certificate deployment |
|
||||
| `CERTCTL_VERIFY_TIMEOUT` | `10s` | TLS probe timeout |
|
||||
| `CERTCTL_VERIFY_DELAY` | `2s` | Delay before verification probe |
|
||||
|
||||
### Server — Notification Connectors
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_SLACK_WEBHOOK_URL` | — | Slack incoming webhook URL (enables Slack) |
|
||||
| `CERTCTL_SLACK_CHANNEL` | — | Override default webhook channel |
|
||||
| `CERTCTL_SLACK_USERNAME` | `certctl` | Bot display name |
|
||||
| `CERTCTL_TEAMS_WEBHOOK_URL` | — | Microsoft Teams webhook URL (enables Teams) |
|
||||
| `CERTCTL_PAGERDUTY_ROUTING_KEY` | — | PagerDuty Events API v2 key (enables PagerDuty) |
|
||||
| `CERTCTL_PAGERDUTY_SEVERITY` | `warning` | Event severity: `info`, `warning`, `error`, `critical` |
|
||||
| `CERTCTL_OPSGENIE_API_KEY` | — | OpsGenie Alert API key (enables OpsGenie) |
|
||||
| `CERTCTL_OPSGENIE_PRIORITY` | `P3` | Alert priority: `P1`–`P5` |
|
||||
|
||||
### Agent
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_SERVER_URL` | `http://localhost:8080` | Control plane URL |
|
||||
| `CERTCTL_API_KEY` | — | Agent API key for authentication |
|
||||
| `CERTCTL_AGENT_ID` | — | Registered agent ID (required) |
|
||||
| `CERTCTL_KEY_DIR` | `/var/lib/certctl/keys` | Private key storage directory (0600 perms) |
|
||||
| `CERTCTL_DISCOVERY_DIRS` | — | Directories to scan for existing certs (comma-separated) |
|
||||
|
||||
Docker Compose overrides for the demo stack are in `deploy/docker-compose.yml`.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
# Install dev tools (golangci-lint, migrate CLI, air)
|
||||
make install-tools
|
||||
|
||||
# Run tests
|
||||
make test
|
||||
|
||||
# Run tests with race detection (same as CI)
|
||||
go test -race ./internal/service/... ./internal/api/handler/... ./internal/api/middleware/... ./internal/scheduler/... ./internal/connector/... ./internal/domain/... ./internal/validation/...
|
||||
|
||||
# Run with coverage
|
||||
make test-coverage
|
||||
|
||||
# Lint (runs golangci-lint with project config)
|
||||
make lint
|
||||
|
||||
# Vulnerability scan
|
||||
govulncheck ./...
|
||||
|
||||
# Format
|
||||
make fmt
|
||||
```
|
||||
|
||||
### CI Pipeline
|
||||
|
||||
Every push and PR runs: `go vet`, `go test -race` (race detection), `golangci-lint` (11 linters including gosec and bodyclose), `govulncheck` (dependency CVE scanning), and per-layer coverage thresholds (service 60%, handler 60%, domain 40%, middleware 50%). Frontend CI runs TypeScript type checking, Vitest tests, and Vite production build. See `.github/workflows/ci.yml` for details.
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
make docker-up # Start stack (server + postgres + agent)
|
||||
make docker-down # Stop stack
|
||||
make docker-logs-server # Server logs
|
||||
make docker-logs-agent # Agent logs
|
||||
make docker-clean # Stop + remove volumes
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
### Private Key Management
|
||||
- **Agent keygen mode (default)**: Agents generate ECDSA P-256 keys locally and store them with 0600 permissions in `CERTCTL_KEY_DIR` (default `/var/lib/certctl/keys`). Only the CSR (public key) is sent to the control plane. Private keys never leave agent infrastructure.
|
||||
- **Server keygen mode (demo only)**: Set `CERTCTL_KEYGEN_MODE=server` for development/demo with Local CA. The control plane generates RSA-2048 keys server-side. A log warning is emitted at startup.
|
||||
|
||||
### Authentication
|
||||
- Agent-to-server: API key (registered at agent creation)
|
||||
- API key and JWT auth types supported; `none` for demo/development
|
||||
- Auth type and secret configured via `CERTCTL_AUTH_TYPE` and `CERTCTL_AUTH_SECRET`
|
||||
|
||||
### CORS
|
||||
- **Deny-by-default**: Empty `CERTCTL_CORS_ORIGINS` blocks all cross-origin requests. Operators must explicitly list allowed origins (comma-separated) or set `*` for development.
|
||||
|
||||
### Input Validation
|
||||
- Shell command injection prevention on all connector scripts (strict character whitelist, no metacharacters)
|
||||
- RFC 1123 domain name validation, base64url ACME token validation
|
||||
- SSRF protection in network scanner (loopback, link-local, multicast, broadcast ranges filtered)
|
||||
|
||||
### Concurrency Safety
|
||||
- Scheduler loops protected by `sync/atomic.Bool` idempotency guards — duplicate ticks are skipped
|
||||
- Graceful shutdown waits up to 30 seconds for in-flight work before database close
|
||||
|
||||
### Audit Trail
|
||||
- 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
|
||||
|
||||
## API Overview
|
||||
|
||||
93 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).
|
||||
|
||||
### Key Endpoints
|
||||
```
|
||||
# Certificate lifecycle
|
||||
GET /api/v1/certificates List (filter, sort, cursor, sparse fields)
|
||||
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
|
||||
|
||||
# Post-deployment verification
|
||||
POST /api/v1/jobs/{id}/verify Submit TLS verification result
|
||||
GET /api/v1/jobs/{id}/verification Get verification status
|
||||
|
||||
# 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)
|
||||
```
|
||||
|
||||
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.
|
||||
| Guide | Description |
|
||||
|-------|-------------|
|
||||
| [Why certctl?](docs/why-certctl.md) | How certctl compares to ACME clients, agent-based SaaS, and enterprise platforms |
|
||||
| [Concepts](docs/concepts.md) | TLS certificates explained from scratch — for beginners who know nothing about certs |
|
||||
| [Quick Start](docs/quickstart.md) | 5-minute setup — dashboard, API, CLI, discovery, stakeholder demo flow |
|
||||
| [Deployment Examples](docs/examples.md) | 5 turnkey scenarios (ACME+NGINX, wildcard DNS-01, private CA, step-ca, multi-issuer) with migration guides |
|
||||
| [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 |
|
||||
| [Connector Reference](docs/connectors.md) | Configuration for all 7 issuers, 10 targets, and 5 notifier connectors |
|
||||
| [Compliance Mapping](docs/compliance.md) | SOC 2 Type II, PCI-DSS 4.0, NIST SP 800-57 alignment guides |
|
||||
| [OpenAPI 3.1 Spec](api/openapi.yaml) | 97 operations, full request/response schemas |
|
||||
|
||||
## CLI
|
||||
|
||||
@@ -400,38 +234,26 @@ go install github.com/shankar0123/certctl/cmd/cli@latest
|
||||
export CERTCTL_SERVER_URL=http://localhost:8443
|
||||
export CERTCTL_API_KEY=your-api-key
|
||||
|
||||
# Certificate commands
|
||||
# Usage
|
||||
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 jobs list # List jobs
|
||||
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
|
||||
|
||||
# Output formats
|
||||
certctl-cli certs list --format json # JSON output (default: table)
|
||||
```
|
||||
|
||||
## MCP Server (AI Integration)
|
||||
|
||||
certctl ships a standalone MCP (Model Context Protocol) server that exposes all 78 API endpoints as tools for AI assistants — Claude, Cursor, Windsurf, OpenClaw, VS Code Copilot, and any MCP-compatible client.
|
||||
certctl ships a standalone MCP (Model Context Protocol) server that exposes all API endpoints as tools for AI assistants — Claude, Cursor, Windsurf, OpenClaw, VS Code Copilot, and any MCP-compatible client.
|
||||
|
||||
```bash
|
||||
# Install
|
||||
# Install and run
|
||||
go install github.com/shankar0123/certctl/cmd/mcp-server@latest
|
||||
|
||||
# Configure
|
||||
export CERTCTL_SERVER_URL=http://localhost:8443
|
||||
export CERTCTL_API_KEY=your-api-key
|
||||
|
||||
# Run (stdio transport — add to your AI client config)
|
||||
mcp-server
|
||||
```
|
||||
|
||||
@@ -450,46 +272,44 @@ mcp-server
|
||||
}
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
certctl is designed with a security-first architecture. Agents generate ECDSA P-256 keys locally — private keys never touch the control plane. API key auth is enforced by default with SHA-256 hashing and constant-time comparison. CORS is deny-by-default. All connector scripts are validated against shell injection. The network scanner filters reserved IP ranges (SSRF protection). Scheduler loops use atomic idempotency guards. Every API call is recorded to an immutable audit trail with actor attribution, SHA-256 body hash, and latency tracking. See the [Architecture Guide](docs/architecture.md) for the full security model.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
make build # Build server + agent binaries
|
||||
make test # Run tests
|
||||
make lint # golangci-lint (11 linters)
|
||||
govulncheck ./... # Vulnerability scan
|
||||
make docker-up # Start Docker Compose stack
|
||||
```
|
||||
|
||||
CI runs on every push: `go vet`, `go test -race`, `golangci-lint`, `govulncheck`, and per-layer coverage thresholds (service 55%, handler 60%, domain 40%, middleware 30%). Frontend CI runs TypeScript type checking, Vitest tests, and Vite production build.
|
||||
|
||||
## Roadmap
|
||||
|
||||
### V1 (v1.0.0)
|
||||
### V1 (v1.0.0) — Shipped
|
||||
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
|
||||
### V2: Operational Maturity — Shipped
|
||||
30+ milestones, extensively tested with CI-enforced coverage gates. Sub-CA mode, ACME DNS-01/DNS-PERSIST-01, step-ca, Vault PKI, DigiCert CertCentral, OpenSSL/Custom CA issuers. NGINX, Apache, HAProxy, Traefik, Caddy, Envoy, Postfix, Dovecot, IIS targets. RFC 5280 revocation with CRL + OCSP. Certificate profiles, ownership tracking, approval workflows. Filesystem and network certificate discovery. Prometheus metrics, dashboard charts, agent fleet overview. EST server (RFC 7030), ACME ARI (RFC 9702), certificate export, S/MIME support, Helm chart, MCP server, CLI, scheduled digest emails. Slack, Teams, PagerDuty, OpsGenie, SMTP notifications. Compliance mapping (SOC 2, PCI-DSS 4.0, NIST SP 800-57). See the [Feature Inventory](docs/features.md) for details.
|
||||
|
||||
18 milestones complete, 1100+ 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
|
||||
|
||||
- **Post-Deployment TLS Verification** — agent-side TLS probe confirms the target is serving the correct certificate by SHA-256 fingerprint match
|
||||
- **Traefik + Caddy Targets** — Traefik (file provider, auto-reload) and Caddy (Admin API hot-reload or file-based)
|
||||
|
||||
**Coming next:**
|
||||
|
||||
- **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
|
||||
**Coming in v2.1.0:** Dynamic issuer and target configuration via GUI (no env var restarts), first-run onboarding wizard.
|
||||
|
||||
### 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.
|
||||
Team access controls and identity provider integration (OIDC/SSO). Role-based access control with profile-gating. Event-driven architecture (NATS) with real-time operational views. Advanced search DSL, compliance and risk scoring, bulk fleet operations.
|
||||
|
||||
### V4+: Cloud, Scale & Passive Discovery
|
||||
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).
|
||||
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 (Google CAS, EJBCA, Sectigo), and platform-scale features (Terraform provider, multi-tenancy, HSM support).
|
||||
|
||||
## License
|
||||
|
||||
Certctl is licensed under the [Business Source License 1.1](LICENSE). The source code is publicly available and free to use, modify, and self-host. The one restriction: you may not offer certctl as a managed/hosted certificate management service to third parties.
|
||||
Certctl is licensed under the [Business Source License 1.1](LICENSE). The source code is publicly available and free to use, modify, and self-host. The one restriction: you may not offer certctl as a managed/hosted certificate management service to third parties. The BSL 1.1 license converts automatically to Apache 2.0 on March 1, 2033, providing perpetual freedom.
|
||||
|
||||
For licensing inquiries: certctl@proton.me
|
||||
|
||||
---
|
||||
|
||||
If certctl solves a problem you have, [star the repo](https://github.com/shankar0123/certctl) to help others find it. Questions, bugs, or feature requests — [open an issue](https://github.com/shankar0123/certctl/issues).
|
||||
|
||||
+166
-2
@@ -62,6 +62,8 @@ tags:
|
||||
description: Certificate discovery — filesystem scanning by agents and network TLS probing
|
||||
- name: Network Scan
|
||||
description: Network scan target management for active TLS certificate discovery
|
||||
- name: Digest
|
||||
description: Scheduled certificate digest email notifications
|
||||
|
||||
paths:
|
||||
# ─── Health & Auth ───────────────────────────────────────────────────
|
||||
@@ -248,6 +250,8 @@ paths:
|
||||
$ref: "#/components/schemas/ManagedCertificate"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
delete:
|
||||
@@ -259,6 +263,8 @@ paths:
|
||||
responses:
|
||||
"204":
|
||||
description: Certificate archived
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
@@ -304,6 +310,12 @@ paths:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatusResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
"409":
|
||||
$ref: "#/components/responses/Conflict"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
@@ -367,6 +379,84 @@ paths:
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
# ─── Certificate Export ──────────────────────────────────────────────
|
||||
/api/v1/certificates/{id}/export/pem:
|
||||
get:
|
||||
tags: [Certificates]
|
||||
summary: Export certificate as PEM
|
||||
description: |
|
||||
Returns the certificate and its chain in PEM format. By default returns JSON
|
||||
with cert_pem, chain_pem, and full_pem fields. Add ?download=true to get the
|
||||
full PEM chain as a file download with Content-Disposition headers.
|
||||
operationId: exportCertificatePEM
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/resourceId"
|
||||
- name: download
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
enum: ["true"]
|
||||
description: Set to "true" to get a file download instead of JSON.
|
||||
responses:
|
||||
"200":
|
||||
description: PEM export
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
cert_pem:
|
||||
type: string
|
||||
description: Leaf certificate PEM
|
||||
chain_pem:
|
||||
type: string
|
||||
description: Intermediate/root chain PEM
|
||||
full_pem:
|
||||
type: string
|
||||
description: Full PEM chain (cert + intermediates)
|
||||
application/x-pem-file:
|
||||
schema:
|
||||
type: string
|
||||
format: binary
|
||||
description: Full PEM file (when download=true)
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/api/v1/certificates/{id}/export/pkcs12:
|
||||
post:
|
||||
tags: [Certificates]
|
||||
summary: Export certificate as PKCS#12
|
||||
description: |
|
||||
Returns a PKCS#12 (.p12) bundle containing the certificate and chain.
|
||||
Private keys are NOT included — they live on agents and never touch the control plane.
|
||||
The bundle is encrypted with the provided password (or empty password if omitted).
|
||||
operationId: exportCertificatePKCS12
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/resourceId"
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
password:
|
||||
type: string
|
||||
description: Password to encrypt the PKCS#12 bundle (can be empty)
|
||||
responses:
|
||||
"200":
|
||||
description: PKCS#12 binary
|
||||
content:
|
||||
application/x-pkcs12:
|
||||
schema:
|
||||
type: string
|
||||
format: binary
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
# ─── CRL & OCSP ─────────────────────────────────────────────────────
|
||||
/api/v1/crl:
|
||||
get:
|
||||
@@ -740,6 +830,8 @@ paths:
|
||||
$ref: "#/components/schemas/Agent"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"409":
|
||||
$ref: "#/components/responses/Conflict"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
@@ -797,6 +889,8 @@ paths:
|
||||
$ref: "#/components/schemas/StatusResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
@@ -2294,6 +2388,56 @@ paths:
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
# ─── Digest ────────────────────────────────────────────────────────
|
||||
/api/v1/digest/preview:
|
||||
get:
|
||||
tags: [Digest]
|
||||
summary: Preview digest email
|
||||
description: |
|
||||
Returns an HTML preview of the scheduled certificate digest email.
|
||||
This includes a summary of certificate status, pending jobs, and expiring certificates.
|
||||
operationId: previewDigest
|
||||
responses:
|
||||
"200":
|
||||
description: HTML digest email preview
|
||||
content:
|
||||
text/html:
|
||||
schema:
|
||||
type: string
|
||||
example: "<html>...</html>"
|
||||
"503":
|
||||
description: Digest service not configured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatusMessageResponse"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/api/v1/digest/send:
|
||||
post:
|
||||
tags: [Digest]
|
||||
summary: Send digest email
|
||||
description: |
|
||||
Triggers immediate sending of the certificate digest email to configured recipients.
|
||||
If no explicit recipients are configured, sends to certificate owners.
|
||||
operationId: sendDigest
|
||||
responses:
|
||||
"200":
|
||||
description: Digest sent successfully
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatusMessageResponse"
|
||||
"503":
|
||||
description: Digest service not configured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatusMessageResponse"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════
|
||||
components:
|
||||
securitySchemes:
|
||||
@@ -2339,6 +2483,12 @@ components:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorResponse"
|
||||
Conflict:
|
||||
description: Resource conflict
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorResponse"
|
||||
InternalError:
|
||||
description: Internal server error
|
||||
content:
|
||||
@@ -2441,6 +2591,13 @@ components:
|
||||
updated_at:
|
||||
type: string
|
||||
format: date-time
|
||||
required:
|
||||
- name
|
||||
- common_name
|
||||
- renewal_policy_id
|
||||
- issuer_id
|
||||
- owner_id
|
||||
- team_id
|
||||
|
||||
CertificateVersion:
|
||||
type: object
|
||||
@@ -2486,7 +2643,7 @@ components:
|
||||
# ─── Issuers ─────────────────────────────────────────────────────
|
||||
IssuerType:
|
||||
type: string
|
||||
enum: [ACME, GenericCA, StepCA]
|
||||
enum: [ACME, GenericCA, StepCA, VaultPKI, DigiCert, Sectigo, GoogleCAS]
|
||||
|
||||
Issuer:
|
||||
type: object
|
||||
@@ -2512,7 +2669,7 @@ components:
|
||||
# ─── Targets ─────────────────────────────────────────────────────
|
||||
TargetType:
|
||||
type: string
|
||||
enum: [NGINX, Apache, HAProxy, F5, IIS]
|
||||
enum: [NGINX, Apache, HAProxy, Traefik, Caddy, Envoy, Postfix, Dovecot, IIS, F5]
|
||||
|
||||
DeploymentTarget:
|
||||
type: object
|
||||
@@ -2712,8 +2869,15 @@ components:
|
||||
type: integer
|
||||
allowed_ekus:
|
||||
type: array
|
||||
description: Extended Key Usages to include in issued certificates
|
||||
items:
|
||||
type: string
|
||||
enum:
|
||||
- serverAuth
|
||||
- clientAuth
|
||||
- codeSigning
|
||||
- emailProtection
|
||||
- timeStamping
|
||||
required_san_patterns:
|
||||
type: array
|
||||
items:
|
||||
|
||||
@@ -0,0 +1,830 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestAgent_Heartbeat_Success tests that heartbeat sends correct metadata and handles 200 response.
|
||||
func TestAgent_Heartbeat_Success(t *testing.T) {
|
||||
// Create mock server to validate heartbeat request
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Verify correct endpoint and method
|
||||
if r.URL.Path != "/api/v1/agents/a-test-agent/heartbeat" {
|
||||
t.Errorf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
t.Errorf("unexpected method: %s, expected POST", r.Method)
|
||||
}
|
||||
|
||||
// Verify auth header
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth != "Bearer test-key" {
|
||||
t.Errorf("unexpected auth header: %s", auth)
|
||||
}
|
||||
|
||||
// Verify request body contains required fields
|
||||
var payload map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
t.Fatalf("failed to decode payload: %v", err)
|
||||
}
|
||||
|
||||
// Check required fields
|
||||
if _, ok := payload["version"]; !ok {
|
||||
t.Error("missing version in heartbeat")
|
||||
}
|
||||
if _, ok := payload["hostname"]; !ok {
|
||||
t.Error("missing hostname in heartbeat")
|
||||
}
|
||||
if _, ok := payload["os"]; !ok {
|
||||
t.Error("missing os in heartbeat")
|
||||
}
|
||||
if _, ok := payload["architecture"]; !ok {
|
||||
t.Error("missing architecture in heartbeat")
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test-agent",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
// Should not panic
|
||||
agent.sendHeartbeat(context.Background())
|
||||
}
|
||||
|
||||
// TestAgent_Heartbeat_ServerError tests that heartbeat handles 500 response gracefully.
|
||||
func TestAgent_Heartbeat_ServerError(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("server error"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test-agent",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
// Should increment consecutive failures
|
||||
failureBefore := agent.consecutiveFailures
|
||||
agent.sendHeartbeat(context.Background())
|
||||
failureAfter := agent.consecutiveFailures
|
||||
|
||||
if failureAfter != failureBefore+1 {
|
||||
t.Errorf("expected consecutive failures to increment, got %d, want %d", failureAfter, failureBefore+1)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAgent_Heartbeat_ConnectionError tests that heartbeat handles connection error.
|
||||
func TestAgent_Heartbeat_ConnectionError(t *testing.T) {
|
||||
// Use an invalid address that will fail immediately
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://invalid-host-that-does-not-exist.local:9999",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test-agent",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
// Should fail due to connection error
|
||||
agent.sendHeartbeat(context.Background())
|
||||
|
||||
if agent.consecutiveFailures != 1 {
|
||||
t.Errorf("expected consecutive failures to be 1, got %d", agent.consecutiveFailures)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAgent_PollWork_NoWork tests that work polling handles empty work list.
|
||||
func TestAgent_PollWork_NoWork(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/agents/a-test-agent/work" {
|
||||
t.Errorf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
if r.Method != http.MethodGet {
|
||||
t.Errorf("unexpected method: %s", r.Method)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(WorkResponse{
|
||||
Jobs: []JobItem{},
|
||||
Count: 0,
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test-agent",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
// Should not panic
|
||||
agent.pollForWork(context.Background())
|
||||
}
|
||||
|
||||
// TestAgent_PollWork_Success tests that work polling parses and returns jobs correctly.
|
||||
func TestAgent_PollWork_Success(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
workResp := WorkResponse{
|
||||
Count: 2,
|
||||
Jobs: []JobItem{
|
||||
{
|
||||
ID: "j-csr-001",
|
||||
Type: "Issuance",
|
||||
CertificateID: "mc-001",
|
||||
CommonName: "example.com",
|
||||
SANs: []string{"www.example.com"},
|
||||
Status: "AwaitingCSR",
|
||||
},
|
||||
{
|
||||
ID: "j-deploy-001",
|
||||
Type: "Deployment",
|
||||
CertificateID: "mc-001",
|
||||
TargetID: strPtr("t-nginx-1"),
|
||||
TargetType: "NGINX",
|
||||
TargetConfig: json.RawMessage(`{"cert_path":"/etc/nginx/cert.pem"}`),
|
||||
Status: "Pending",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(workResp)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test-agent",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
// Should not panic; work items are processed in separate gorines in real usage
|
||||
agent.pollForWork(context.Background())
|
||||
}
|
||||
|
||||
// TestSplitPEMChain tests PEM chain splitting into cert and chain.
|
||||
func TestSplitPEMChain(t *testing.T) {
|
||||
// Create two test certificates
|
||||
cert1, _ := generateTestCertWithCN("cert1.example.com")
|
||||
cert2, _ := generateTestCertWithCN("cert2.example.com")
|
||||
|
||||
block1 := &pem.Block{Type: "CERTIFICATE", Bytes: cert1.Raw}
|
||||
block2 := &pem.Block{Type: "CERTIFICATE", Bytes: cert2.Raw}
|
||||
|
||||
cert1PEM := string(pem.EncodeToMemory(block1))
|
||||
cert2PEM := string(pem.EncodeToMemory(block2))
|
||||
|
||||
chainPEM := cert1PEM + "\n" + cert2PEM
|
||||
|
||||
// Split
|
||||
certOnly, chain := splitPEMChain(chainPEM)
|
||||
|
||||
// Verify cert part
|
||||
if !bytes.Contains([]byte(certOnly), []byte("-----BEGIN CERTIFICATE-----")) {
|
||||
t.Error("cert part missing BEGIN marker")
|
||||
}
|
||||
|
||||
// Verify chain part
|
||||
if !bytes.Contains([]byte(chain), []byte("-----BEGIN CERTIFICATE-----")) {
|
||||
t.Error("chain part missing BEGIN marker")
|
||||
}
|
||||
|
||||
// Verify they're different
|
||||
if certOnly == chain {
|
||||
t.Error("cert and chain should be different")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSplitPEMChain_SingleCert tests PEM chain splitting with single certificate.
|
||||
func TestSplitPEMChain_SingleCert(t *testing.T) {
|
||||
cert, _ := generateTestCertWithCN("example.com")
|
||||
block := &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}
|
||||
certPEM := string(pem.EncodeToMemory(block))
|
||||
|
||||
certOnly, chain := splitPEMChain(certPEM)
|
||||
|
||||
if certOnly != certPEM {
|
||||
t.Error("single cert should be returned as-is")
|
||||
}
|
||||
if chain != "" {
|
||||
t.Error("chain should be empty for single cert")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSplitPEMChain_InvalidPEM tests PEM chain splitting with invalid PEM.
|
||||
func TestSplitPEMChain_InvalidPEM(t *testing.T) {
|
||||
invalidPEM := "not a valid pem"
|
||||
|
||||
certOnly, chain := splitPEMChain(invalidPEM)
|
||||
|
||||
if certOnly != invalidPEM {
|
||||
t.Error("invalid PEM should be returned as-is in cert part")
|
||||
}
|
||||
if chain != "" {
|
||||
t.Error("chain should be empty for invalid PEM")
|
||||
}
|
||||
}
|
||||
|
||||
// TestParsePEMFile tests parsing a PEM file with certificates.
|
||||
func TestParsePEMFile(t *testing.T) {
|
||||
// Create a temporary file with a PEM certificate
|
||||
tmpdir := t.TempDir()
|
||||
certPath := filepath.Join(tmpdir, "cert.pem")
|
||||
|
||||
cert, _ := generateTestCert()
|
||||
block := &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}
|
||||
certPEM := pem.EncodeToMemory(block)
|
||||
|
||||
if err := os.WriteFile(certPath, certPEM, 0644); err != nil {
|
||||
t.Fatalf("failed to write test cert: %v", err)
|
||||
}
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://localhost:8443",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
// Parse the file
|
||||
entries := agent.parsePEMFile(certPath)
|
||||
|
||||
if len(entries) != 1 {
|
||||
t.Errorf("expected 1 certificate, got %d", len(entries))
|
||||
return
|
||||
}
|
||||
|
||||
entry := entries[0]
|
||||
if entry.CommonName != "test.example.com" {
|
||||
t.Errorf("expected CN 'test.example.com', got '%s'", entry.CommonName)
|
||||
}
|
||||
if entry.SourceFormat != "PEM" {
|
||||
t.Errorf("expected format 'PEM', got '%s'", entry.SourceFormat)
|
||||
}
|
||||
if entry.SourcePath != certPath {
|
||||
t.Errorf("expected path '%s', got '%s'", certPath, entry.SourcePath)
|
||||
}
|
||||
|
||||
// Verify fingerprint is non-empty and correct length (SHA256 hex = 64 chars)
|
||||
if len(entry.FingerprintSHA256) != 64 {
|
||||
t.Errorf("expected 64-char fingerprint, got %d", len(entry.FingerprintSHA256))
|
||||
}
|
||||
}
|
||||
|
||||
// TestParsePEMFile_MultipleCerts tests parsing a PEM file with multiple certificates.
|
||||
func TestParsePEMFile_MultipleCerts(t *testing.T) {
|
||||
tmpdir := t.TempDir()
|
||||
certPath := filepath.Join(tmpdir, "chain.pem")
|
||||
|
||||
cert1, _ := generateTestCertWithCN("cert1.example.com")
|
||||
cert2, _ := generateTestCertWithCN("cert2.example.com")
|
||||
|
||||
block1 := &pem.Block{Type: "CERTIFICATE", Bytes: cert1.Raw}
|
||||
block2 := &pem.Block{Type: "CERTIFICATE", Bytes: cert2.Raw}
|
||||
|
||||
certPEM := append(pem.EncodeToMemory(block1), pem.EncodeToMemory(block2)...)
|
||||
|
||||
if err := os.WriteFile(certPath, certPEM, 0644); err != nil {
|
||||
t.Fatalf("failed to write test cert: %v", err)
|
||||
}
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://localhost:8443",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
entries := agent.parsePEMFile(certPath)
|
||||
|
||||
if len(entries) != 2 {
|
||||
t.Errorf("expected 2 certificates, got %d", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseDERFile tests parsing a DER-encoded certificate file.
|
||||
func TestParseDERFile(t *testing.T) {
|
||||
tmpdir := t.TempDir()
|
||||
derPath := filepath.Join(tmpdir, "cert.der")
|
||||
|
||||
cert, _ := generateTestCertWithCN("test.example.com")
|
||||
if err := os.WriteFile(derPath, cert.Raw, 0644); err != nil {
|
||||
t.Fatalf("failed to write test cert: %v", err)
|
||||
}
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://localhost:8443",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
entry, err := agent.parseDERFile(derPath)
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if entry.CommonName != "test.example.com" {
|
||||
t.Errorf("expected CN 'test.example.com', got '%s'", entry.CommonName)
|
||||
}
|
||||
if entry.SourceFormat != "DER" {
|
||||
t.Errorf("expected format 'DER', got '%s'", entry.SourceFormat)
|
||||
}
|
||||
if len(entry.FingerprintSHA256) != 64 {
|
||||
t.Errorf("expected 64-char fingerprint, got %d", len(entry.FingerprintSHA256))
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseDERFile_Invalid tests parsing an invalid DER file.
|
||||
func TestParseDERFile_Invalid(t *testing.T) {
|
||||
tmpdir := t.TempDir()
|
||||
derPath := filepath.Join(tmpdir, "invalid.der")
|
||||
|
||||
if err := os.WriteFile(derPath, []byte("not a valid der file"), 0644); err != nil {
|
||||
t.Fatalf("failed to write test file: %v", err)
|
||||
}
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://localhost:8443",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
_, err := agent.parseDERFile(derPath)
|
||||
if err == nil {
|
||||
t.Error("expected error for invalid DER file")
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanDirectory tests scanning a directory for certificate files.
|
||||
func TestScanDirectory(t *testing.T) {
|
||||
tmpdir := t.TempDir()
|
||||
|
||||
// Create subdirectory
|
||||
subdir := filepath.Join(tmpdir, "subdir")
|
||||
if err := os.MkdirAll(subdir, 0755); err != nil {
|
||||
t.Fatalf("failed to create subdir: %v", err)
|
||||
}
|
||||
|
||||
// Create certificates with various extensions
|
||||
cert1, _ := generateTestCertWithCN("cert1.example.com")
|
||||
cert2, _ := generateTestCertWithCN("cert2.example.com")
|
||||
|
||||
// Write cert1.pem
|
||||
block1 := &pem.Block{Type: "CERTIFICATE", Bytes: cert1.Raw}
|
||||
if err := os.WriteFile(filepath.Join(tmpdir, "cert1.pem"), pem.EncodeToMemory(block1), 0644); err != nil {
|
||||
t.Fatalf("failed to write cert1: %v", err)
|
||||
}
|
||||
|
||||
// Write cert2.crt in subdir
|
||||
block2 := &pem.Block{Type: "CERTIFICATE", Bytes: cert2.Raw}
|
||||
if err := os.WriteFile(filepath.Join(subdir, "cert2.crt"), pem.EncodeToMemory(block2), 0644); err != nil {
|
||||
t.Fatalf("failed to write cert2: %v", err)
|
||||
}
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://localhost:8443",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
DiscoveryDirs: []string{tmpdir},
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
// Simulate directory walk manually (as runDiscoveryScan does)
|
||||
var certs []discoveredCertEntry
|
||||
filepath.Walk(tmpdir, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
ext := filepath.Ext(path)
|
||||
switch ext {
|
||||
case ".pem", ".crt":
|
||||
found := agent.parsePEMFile(path)
|
||||
certs = append(certs, found...)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if len(certs) != 2 {
|
||||
t.Errorf("expected 2 certificates from directory scan, got %d", len(certs))
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateTargetConnector_NGINX tests connector creation for NGINX target.
|
||||
func TestCreateTargetConnector_NGINX(t *testing.T) {
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://localhost:8443",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
configJSON := json.RawMessage(`{"cert_path":"/etc/nginx/cert.pem"}`)
|
||||
connector, err := agent.createTargetConnector("NGINX", configJSON)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
if connector == nil {
|
||||
t.Error("expected connector to be non-nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateTargetConnector_Unsupported tests connector creation for unsupported type.
|
||||
func TestCreateTargetConnector_Unsupported(t *testing.T) {
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://localhost:8443",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
_, err := agent.createTargetConnector("UnsupportedType", nil)
|
||||
|
||||
if err == nil {
|
||||
t.Error("expected error for unsupported target type")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchCertificate_Success tests fetching a certificate from the control plane.
|
||||
func TestFetchCertificate_Success(t *testing.T) {
|
||||
cert, _ := generateTestCertWithCN("test.example.com")
|
||||
block := &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}
|
||||
expectedCertPEM := string(pem.EncodeToMemory(block))
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/agents/a-test/certificates/mc-001" {
|
||||
t.Errorf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"certificate_pem": expectedCertPEM,
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
certPEM, err := agent.fetchCertificate(context.Background(), "mc-001")
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
if certPEM != expectedCertPEM {
|
||||
t.Error("certificate PEM mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchCertificate_NotFound tests fetching a non-existent certificate.
|
||||
func TestFetchCertificate_NotFound(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte("not found"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
_, err := agent.fetchCertificate(context.Background(), "mc-nonexistent")
|
||||
if err == nil {
|
||||
t.Error("expected error for non-existent certificate")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReportJobStatus_Success tests reporting job status to the control plane.
|
||||
func TestReportJobStatus_Success(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/agents/a-test/jobs/j-001/status" {
|
||||
t.Errorf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
t.Errorf("unexpected method: %s", r.Method)
|
||||
}
|
||||
|
||||
var payload map[string]string
|
||||
json.NewDecoder(r.Body).Decode(&payload)
|
||||
|
||||
if payload["status"] != "Completed" {
|
||||
t.Errorf("expected status 'Completed', got '%s'", payload["status"])
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
err := agent.reportJobStatus(context.Background(), "j-001", "Completed", "")
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReportJobStatus_WithError tests reporting job status with error message.
|
||||
func TestReportJobStatus_WithError(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var payload map[string]string
|
||||
json.NewDecoder(r.Body).Decode(&payload)
|
||||
|
||||
if payload["status"] != "Failed" {
|
||||
t.Errorf("expected status 'Failed', got '%s'", payload["status"])
|
||||
}
|
||||
if payload["error"] != "deployment failed" {
|
||||
t.Errorf("expected error 'deployment failed', got '%s'", payload["error"])
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
err := agent.reportJobStatus(context.Background(), "j-001", "Failed", "deployment failed")
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMakeRequest_Success tests making an authenticated HTTP request.
|
||||
func TestMakeRequest_Success(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Verify auth header
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth != "Bearer test-key" {
|
||||
t.Errorf("unexpected auth: %s", auth)
|
||||
}
|
||||
|
||||
// Verify content-type
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if ct != "application/json" {
|
||||
t.Errorf("unexpected content-type: %s", ct)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: server.URL,
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
resp, err := agent.makeRequest(context.Background(), http.MethodPost, "/test", map[string]string{"key": "value"})
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("unexpected status: %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMakeRequest_InvalidURL tests making a request with invalid URL.
|
||||
func TestMakeRequest_InvalidURL(t *testing.T) {
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://invalid-host-that-does-not-exist.local:9999",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
_, err := agent.makeRequest(context.Background(), http.MethodGet, "/test", nil)
|
||||
if err == nil {
|
||||
t.Error("expected error for unreachable host")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCertKeyInfo tests extraction of key algorithm and size from certificates.
|
||||
func TestCertKeyInfo(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
genKey func() interface{}
|
||||
expectedAlg string
|
||||
minBitSize int
|
||||
}{
|
||||
{
|
||||
name: "ECDSA P-256",
|
||||
genKey: func() interface{} {
|
||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
return key.Public()
|
||||
},
|
||||
expectedAlg: "ECDSA",
|
||||
minBitSize: 256,
|
||||
},
|
||||
{
|
||||
name: "RSA 2048",
|
||||
genKey: func() interface{} {
|
||||
key, _ := rsa.GenerateKey(rand.Reader, 2048)
|
||||
return key.Public()
|
||||
},
|
||||
expectedAlg: "RSA",
|
||||
minBitSize: 2048,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pubKey := tt.genKey()
|
||||
|
||||
// Create certificate with this key
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{
|
||||
CommonName: "test.com",
|
||||
},
|
||||
NotBefore: time.Now(),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
BasicConstraintsValid: true,
|
||||
}
|
||||
|
||||
var privKey interface{}
|
||||
if ecdsaPub, ok := pubKey.(*ecdsa.PublicKey); ok {
|
||||
key, _ := ecdsa.GenerateKey(ecdsaPub.Curve, rand.Reader)
|
||||
privKey = key
|
||||
} else if rsaPub, ok := pubKey.(*rsa.PublicKey); ok {
|
||||
key, _ := rsa.GenerateKey(rand.Reader, rsaPub.N.BitLen())
|
||||
privKey = key
|
||||
}
|
||||
|
||||
certDER, _ := x509.CreateCertificate(rand.Reader, template, template, pubKey, privKey)
|
||||
cert, _ := x509.ParseCertificate(certDER)
|
||||
|
||||
alg, bitSize := certKeyInfo(cert)
|
||||
if alg != tt.expectedAlg {
|
||||
t.Errorf("expected algorithm %s, got %s", tt.expectedAlg, alg)
|
||||
}
|
||||
if bitSize < tt.minBitSize {
|
||||
t.Errorf("expected bitsize >= %d, got %d", tt.minBitSize, bitSize)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewAgent tests agent initialization.
|
||||
func TestNewAgent(t *testing.T) {
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://localhost:8443",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
if agent.config != cfg {
|
||||
t.Error("config not set correctly")
|
||||
}
|
||||
if agent.heartbeatInterval != 60*time.Second {
|
||||
t.Errorf("expected heartbeat interval 60s, got %v", agent.heartbeatInterval)
|
||||
}
|
||||
if agent.pollInterval != 30*time.Second {
|
||||
t.Errorf("expected poll interval 30s, got %v", agent.pollInterval)
|
||||
}
|
||||
if agent.client == nil {
|
||||
t.Error("HTTP client not initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewAgent_WithLogger tests agent initialization with logger.
|
||||
func TestNewAgent_WithLogger(t *testing.T) {
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
cfg := &AgentConfig{
|
||||
ServerURL: "http://localhost:8443",
|
||||
APIKey: "test-key",
|
||||
AgentID: "a-test",
|
||||
Hostname: "test-host",
|
||||
}
|
||||
|
||||
agent := NewAgent(cfg, logger)
|
||||
|
||||
if agent.logger != logger {
|
||||
t.Error("logger not set correctly")
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to create test certificates with specific CN
|
||||
func generateTestCertWithCN(commonName string) (*x509.Certificate, error) {
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{
|
||||
CommonName: commonName,
|
||||
},
|
||||
NotBefore: time.Now(),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
BasicConstraintsValid: true,
|
||||
DNSNames: []string{commonName},
|
||||
}
|
||||
|
||||
certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return x509.ParseCertificate(certDER)
|
||||
}
|
||||
|
||||
// Helper to create string pointer
|
||||
func strPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
+50
-3
@@ -29,6 +29,8 @@ import (
|
||||
"github.com/shankar0123/certctl/internal/connector/target"
|
||||
"github.com/shankar0123/certctl/internal/connector/target/apache"
|
||||
"github.com/shankar0123/certctl/internal/connector/target/caddy"
|
||||
"github.com/shankar0123/certctl/internal/connector/target/envoy"
|
||||
pf "github.com/shankar0123/certctl/internal/connector/target/postfix"
|
||||
"github.com/shankar0123/certctl/internal/connector/target/f5"
|
||||
"github.com/shankar0123/certctl/internal/connector/target/haproxy"
|
||||
"github.com/shankar0123/certctl/internal/connector/target/iis"
|
||||
@@ -344,11 +346,23 @@ func (a *Agent) executeCSRJob(ctx context.Context, job JobItem) {
|
||||
}
|
||||
|
||||
// Step 3: Create CSR with common name and SANs
|
||||
// Split SANs into DNS names and email addresses for proper CSR encoding
|
||||
var dnsNames []string
|
||||
var emailAddresses []string
|
||||
for _, san := range job.SANs {
|
||||
if strings.Contains(san, "@") {
|
||||
emailAddresses = append(emailAddresses, san)
|
||||
} else {
|
||||
dnsNames = append(dnsNames, san)
|
||||
}
|
||||
}
|
||||
|
||||
csrTemplate := &x509.CertificateRequest{
|
||||
Subject: pkix.Name{
|
||||
CommonName: job.CommonName,
|
||||
},
|
||||
DNSNames: job.SANs,
|
||||
DNSNames: dnsNames,
|
||||
EmailAddresses: emailAddresses,
|
||||
}
|
||||
|
||||
csrDER, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, privKey)
|
||||
@@ -571,7 +585,11 @@ func (a *Agent) createTargetConnector(targetType string, configJSON json.RawMess
|
||||
return nil, fmt.Errorf("invalid F5 config: %w", err)
|
||||
}
|
||||
}
|
||||
return f5.New(&cfg, a.logger), nil
|
||||
conn, err := f5.New(&cfg, a.logger)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create F5 connector: %w", err)
|
||||
}
|
||||
return conn, nil
|
||||
|
||||
case "IIS":
|
||||
var cfg iis.Config
|
||||
@@ -580,7 +598,7 @@ func (a *Agent) createTargetConnector(targetType string, configJSON json.RawMess
|
||||
return nil, fmt.Errorf("invalid IIS config: %w", err)
|
||||
}
|
||||
}
|
||||
return iis.New(&cfg, a.logger), nil
|
||||
return iis.New(&cfg, a.logger)
|
||||
|
||||
case "Traefik":
|
||||
var cfg traefik.Config
|
||||
@@ -600,6 +618,35 @@ func (a *Agent) createTargetConnector(targetType string, configJSON json.RawMess
|
||||
}
|
||||
return caddy.New(&cfg, a.logger), nil
|
||||
|
||||
case "Envoy":
|
||||
var cfg envoy.Config
|
||||
if len(configJSON) > 0 {
|
||||
if err := json.Unmarshal(configJSON, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("invalid Envoy config: %w", err)
|
||||
}
|
||||
}
|
||||
return envoy.New(&cfg, a.logger), nil
|
||||
|
||||
case "Postfix":
|
||||
var cfg pf.Config
|
||||
cfg.Mode = "postfix"
|
||||
if len(configJSON) > 0 {
|
||||
if err := json.Unmarshal(configJSON, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("invalid Postfix config: %w", err)
|
||||
}
|
||||
}
|
||||
return pf.New(&cfg, a.logger), nil
|
||||
|
||||
case "Dovecot":
|
||||
var cfg pf.Config
|
||||
cfg.Mode = "dovecot"
|
||||
if len(configJSON) > 0 {
|
||||
if err := json.Unmarshal(configJSON, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("invalid Dovecot config: %w", err)
|
||||
}
|
||||
}
|
||||
return pf.New(&cfg, a.logger), nil
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported target type: %s", targetType)
|
||||
}
|
||||
|
||||
+102
-86
@@ -16,11 +16,9 @@ import (
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
"github.com/shankar0123/certctl/internal/api/router"
|
||||
"github.com/shankar0123/certctl/internal/config"
|
||||
"github.com/shankar0123/certctl/internal/crypto"
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
acmeissuer "github.com/shankar0123/certctl/internal/connector/issuer/acme"
|
||||
"github.com/shankar0123/certctl/internal/connector/issuer/local"
|
||||
opensslissuer "github.com/shankar0123/certctl/internal/connector/issuer/openssl"
|
||||
stepcaissuer "github.com/shankar0123/certctl/internal/connector/issuer/stepca"
|
||||
notifyemail "github.com/shankar0123/certctl/internal/connector/notifier/email"
|
||||
notifyopsgenie "github.com/shankar0123/certctl/internal/connector/notifier/opsgenie"
|
||||
notifypagerduty "github.com/shankar0123/certctl/internal/connector/notifier/pagerduty"
|
||||
notifyslack "github.com/shankar0123/certctl/internal/connector/notifier/slack"
|
||||
@@ -80,71 +78,18 @@ func main() {
|
||||
ownerRepo := postgres.NewOwnerRepository(db)
|
||||
logger.Info("initialized all repositories")
|
||||
|
||||
// Initialize Local CA issuer connector.
|
||||
// In sub-CA mode (CERTCTL_CA_CERT_PATH + CERTCTL_CA_KEY_PATH set), loads a pre-signed
|
||||
// CA cert+key from disk. All issued certs chain to the upstream root (e.g., ADCS).
|
||||
// Otherwise, generates an ephemeral self-signed CA for development/demo.
|
||||
localCAConfig := &local.Config{}
|
||||
if cfg.CA.CertPath != "" && cfg.CA.KeyPath != "" {
|
||||
localCAConfig.CACertPath = cfg.CA.CertPath
|
||||
localCAConfig.CAKeyPath = cfg.CA.KeyPath
|
||||
logger.Info("Local CA configured in sub-CA mode",
|
||||
"cert_path", cfg.CA.CertPath,
|
||||
"key_path", cfg.CA.KeyPath)
|
||||
// Initialize dynamic issuer registry.
|
||||
// Issuers are loaded from the database (with AES-GCM encrypted config).
|
||||
// On first boot with an empty database, env var issuers are seeded automatically.
|
||||
var encryptionKey []byte
|
||||
if cfg.Encryption.ConfigEncryptionKey != "" {
|
||||
encryptionKey = crypto.DeriveKey(cfg.Encryption.ConfigEncryptionKey)
|
||||
logger.Info("config encryption enabled (AES-256-GCM)")
|
||||
} else {
|
||||
logger.Info("Local CA configured in self-signed mode (ephemeral)")
|
||||
logger.Warn("CERTCTL_CONFIG_ENCRYPTION_KEY not set — issuer configs stored in plaintext (not recommended for production)")
|
||||
}
|
||||
localCA := local.New(localCAConfig, logger)
|
||||
logger.Info("initialized Local CA issuer connector")
|
||||
|
||||
// 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"),
|
||||
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")
|
||||
|
||||
// Initialize step-ca issuer connector (for Smallstep private CA).
|
||||
// Uses the native /sign API with JWK provisioner authentication.
|
||||
stepcaConnector := stepcaissuer.New(&stepcaissuer.Config{
|
||||
CAURL: os.Getenv("CERTCTL_STEPCA_URL"),
|
||||
ProvisionerName: os.Getenv("CERTCTL_STEPCA_PROVISIONER"),
|
||||
ProvisionerKeyPath: os.Getenv("CERTCTL_STEPCA_KEY_PATH"),
|
||||
ProvisionerPassword: os.Getenv("CERTCTL_STEPCA_PASSWORD"),
|
||||
}, logger)
|
||||
logger.Info("initialized step-ca issuer connector")
|
||||
|
||||
// Initialize OpenSSL/Custom CA issuer connector (for script-based CA integrations).
|
||||
// Delegates certificate signing to user-provided scripts.
|
||||
opensslConnector := opensslissuer.New(&opensslissuer.Config{
|
||||
SignScript: os.Getenv("CERTCTL_OPENSSL_SIGN_SCRIPT"),
|
||||
RevokeScript: os.Getenv("CERTCTL_OPENSSL_REVOKE_SCRIPT"),
|
||||
CRLScript: os.Getenv("CERTCTL_OPENSSL_CRL_SCRIPT"),
|
||||
TimeoutSeconds: getEnvIntDefault(os.Getenv("CERTCTL_OPENSSL_TIMEOUT_SECONDS"), 30),
|
||||
}, logger)
|
||||
logger.Info("initialized OpenSSL/Custom CA issuer connector")
|
||||
|
||||
// Build issuer registry: maps issuer IDs (from database) to connector implementations.
|
||||
// "iss-local" matches the seed data issuer ID for the Local CA.
|
||||
// "iss-acme-staging" and "iss-acme-prod" are conventional IDs for ACME issuers.
|
||||
// "iss-stepca" is the step-ca private CA connector.
|
||||
// "iss-openssl" is the custom CA/OpenSSL connector.
|
||||
issuerRegistry := map[string]service.IssuerConnector{
|
||||
"iss-local": service.NewIssuerConnectorAdapter(localCA),
|
||||
"iss-acme-staging": service.NewIssuerConnectorAdapter(acmeConnector),
|
||||
"iss-acme-prod": service.NewIssuerConnectorAdapter(acmeConnector),
|
||||
"iss-stepca": service.NewIssuerConnectorAdapter(stepcaConnector),
|
||||
"iss-openssl": service.NewIssuerConnectorAdapter(opensslConnector),
|
||||
}
|
||||
logger.Info("issuer registry configured", "issuers", len(issuerRegistry))
|
||||
issuerRegistry := service.NewIssuerRegistry(logger)
|
||||
|
||||
// Initialize revocation repository
|
||||
revocationRepo := postgres.NewRevocationRepository(db)
|
||||
@@ -189,6 +134,25 @@ func main() {
|
||||
logger.Info("OpsGenie notifier enabled")
|
||||
}
|
||||
|
||||
// Wire email notifier if SMTP is configured
|
||||
var emailAdapter *notifyemail.NotifierAdapter
|
||||
if cfg.Notifiers.SMTPHost != "" && cfg.Notifiers.SMTPFromAddress != "" {
|
||||
emailConnector := notifyemail.New(¬ifyemail.Config{
|
||||
SMTPHost: cfg.Notifiers.SMTPHost,
|
||||
SMTPPort: cfg.Notifiers.SMTPPort,
|
||||
Username: cfg.Notifiers.SMTPUsername,
|
||||
Password: cfg.Notifiers.SMTPPassword,
|
||||
FromAddress: cfg.Notifiers.SMTPFromAddress,
|
||||
UseTLS: cfg.Notifiers.SMTPUseTLS,
|
||||
}, logger)
|
||||
emailAdapter = notifyemail.NewNotifierAdapter(emailConnector)
|
||||
notifierRegistry["Email"] = emailAdapter
|
||||
logger.Info("Email notifier enabled",
|
||||
"smtp_host", cfg.Notifiers.SMTPHost,
|
||||
"smtp_port", cfg.Notifiers.SMTPPort,
|
||||
"from", cfg.Notifiers.SMTPFromAddress)
|
||||
}
|
||||
|
||||
notificationService := service.NewNotificationService(notificationRepo, notifierRegistry)
|
||||
notificationService.SetOwnerRepo(ownerRepo)
|
||||
|
||||
@@ -205,12 +169,23 @@ func main() {
|
||||
certificateService.SetRevocationSvc(revocationSvc)
|
||||
certificateService.SetCAOperationsSvc(caOperationsSvc)
|
||||
certificateService.SetTargetRepo(targetRepo)
|
||||
certificateService.SetJobRepo(jobRepo)
|
||||
certificateService.SetKeygenMode(cfg.Keygen.Mode)
|
||||
renewalService := service.NewRenewalService(certificateRepo, jobRepo, renewalPolicyRepo, profileRepo, auditService, notificationService, issuerRegistry, cfg.Keygen.Mode)
|
||||
renewalService.SetTargetRepo(targetRepo)
|
||||
deploymentService := service.NewDeploymentService(jobRepo, targetRepo, agentRepo, certificateRepo, auditService, notificationService)
|
||||
jobService := service.NewJobService(jobRepo, renewalService, deploymentService, logger)
|
||||
agentService := service.NewAgentService(agentRepo, certificateRepo, jobRepo, targetRepo, auditService, issuerRegistry, renewalService)
|
||||
issuerService := service.NewIssuerService(issuerRepo, auditService)
|
||||
targetService := service.NewTargetService(targetRepo, auditService)
|
||||
agentService.SetProfileRepo(profileRepo)
|
||||
issuerService := service.NewIssuerService(issuerRepo, auditService, issuerRegistry, encryptionKey, logger)
|
||||
|
||||
// Seed issuers from env vars on first boot (empty database only), then build registry
|
||||
issuerService.SeedFromEnvVars(context.Background(), cfg)
|
||||
if err := issuerService.BuildRegistry(context.Background()); err != nil {
|
||||
logger.Error("failed to build issuer registry from database", "error", err)
|
||||
}
|
||||
logger.Info("issuer registry loaded", "issuers", issuerRegistry.Len())
|
||||
targetService := service.NewTargetService(targetRepo, auditService, agentRepo, encryptionKey, logger)
|
||||
profileService := service.NewProfileService(profileRepo, auditService)
|
||||
teamService := service.NewTeamService(teamRepo, auditService)
|
||||
ownerService := service.NewOwnerService(ownerRepo, auditService)
|
||||
@@ -262,6 +237,28 @@ func main() {
|
||||
networkScanHandler := handler.NewNetworkScanHandler(networkScanService)
|
||||
verificationService := service.NewVerificationService(jobRepo, auditService, logger)
|
||||
verificationHandler := handler.NewVerificationHandler(verificationService)
|
||||
exportService := service.NewExportService(certificateRepo, auditService)
|
||||
exportHandler := handler.NewExportHandler(exportService)
|
||||
|
||||
// Initialize digest service (requires email notifier)
|
||||
var digestService *service.DigestService
|
||||
var digestHandler *handler.DigestHandler
|
||||
if cfg.Digest.Enabled && emailAdapter != nil {
|
||||
digestService = service.NewDigestService(
|
||||
statsService, certificateRepo, ownerRepo, emailAdapter, cfg.Digest.Recipients, logger,
|
||||
)
|
||||
digestHandler = handler.NewDigestHandler(digestService)
|
||||
logger.Info("digest service enabled",
|
||||
"interval", cfg.Digest.Interval.String(),
|
||||
"recipients", len(cfg.Digest.Recipients))
|
||||
} else {
|
||||
// Create a no-op digest handler for route registration
|
||||
digestHandler = handler.NewDigestHandler(nil)
|
||||
if cfg.Digest.Enabled && emailAdapter == nil {
|
||||
logger.Warn("digest enabled but SMTP not configured — digest emails will not be sent")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Info("initialized all handlers")
|
||||
|
||||
// Create context with cancellation
|
||||
@@ -287,6 +284,11 @@ func main() {
|
||||
sched.SetNetworkScanInterval(cfg.NetworkScan.ScanInterval)
|
||||
logger.Info("network scanning enabled", "interval", cfg.NetworkScan.ScanInterval.String())
|
||||
}
|
||||
if digestService != nil {
|
||||
sched.SetDigestService(digestService)
|
||||
sched.SetDigestInterval(cfg.Digest.Interval)
|
||||
logger.Info("digest scheduler enabled", "interval", cfg.Digest.Interval.String())
|
||||
}
|
||||
|
||||
// Start scheduler
|
||||
logger.Info("starting scheduler")
|
||||
@@ -315,10 +317,12 @@ func main() {
|
||||
Discovery: discoveryHandler,
|
||||
NetworkScan: networkScanHandler,
|
||||
Verification: verificationHandler,
|
||||
Export: exportHandler,
|
||||
Digest: *digestHandler,
|
||||
})
|
||||
// Register EST (RFC 7030) handlers if enabled
|
||||
if cfg.EST.Enabled {
|
||||
issuerConn, ok := issuerRegistry[cfg.EST.IssuerID]
|
||||
issuerConn, ok := issuerRegistry.Get(cfg.EST.IssuerID)
|
||||
if !ok {
|
||||
logger.Error("EST issuer not found in registry", "issuer_id", cfg.EST.IssuerID)
|
||||
os.Exit(1)
|
||||
@@ -417,13 +421,28 @@ func main() {
|
||||
if _, err := os.Stat(webDir + "/index.html"); err != nil {
|
||||
webDir = "./web"
|
||||
}
|
||||
// Health/ready routes bypass the full middleware stack (no auth required).
|
||||
// These are registered on the inner router without auth, but the outer
|
||||
// middleware chain wraps everything. Route them directly to the inner router.
|
||||
noAuthHandler := middleware.Chain(apiRouter,
|
||||
middleware.RequestID,
|
||||
structuredLogger,
|
||||
middleware.Recovery,
|
||||
)
|
||||
|
||||
if _, err := os.Stat(webDir + "/index.html"); err == nil {
|
||||
fileServer := http.FileServer(http.Dir(webDir))
|
||||
finalHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
// API, health, and EST routes go to the API handler
|
||||
if path == "/health" || path == "/ready" ||
|
||||
(len(path) >= 8 && path[:8] == "/api/v1/") ||
|
||||
// Health/ready and auth/info bypass auth middleware.
|
||||
// Health/ready: Docker/K8s health probes don't carry Bearer tokens.
|
||||
// auth/info: React app calls this before login to detect auth mode.
|
||||
if path == "/health" || path == "/ready" || path == "/api/v1/auth/info" {
|
||||
noAuthHandler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
// All other API and EST routes go through the full middleware stack (with auth)
|
||||
if (len(path) >= 8 && path[:8] == "/api/v1/") ||
|
||||
(len(path) >= 16 && path[:16] == "/.well-known/est") {
|
||||
apiHandler.ServeHTTP(w, r)
|
||||
return
|
||||
@@ -438,7 +457,15 @@ func main() {
|
||||
})
|
||||
logger.Info("dashboard available at /", "web_dir", webDir)
|
||||
} else {
|
||||
finalHandler = apiHandler
|
||||
// No dashboard: route health/auth-info without auth, everything else through full stack
|
||||
finalHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
if path == "/health" || path == "/ready" || path == "/api/v1/auth/info" {
|
||||
noAuthHandler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
apiHandler.ServeHTTP(w, r)
|
||||
})
|
||||
logger.Info("dashboard directory not found, serving API only")
|
||||
}
|
||||
|
||||
@@ -447,9 +474,9 @@ func main() {
|
||||
httpServer := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: finalHandler,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
WriteTimeout: 120 * time.Second, // Must accommodate ACME issuance (order + challenge + finalize)
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
@@ -493,14 +520,3 @@ func main() {
|
||||
logger.Info("certctl server stopped")
|
||||
}
|
||||
|
||||
// getEnvIntDefault parses an integer from a string with a default fallback.
|
||||
func getEnvIntDefault(s string, defaultVal int) int {
|
||||
if s == "" {
|
||||
return defaultVal
|
||||
}
|
||||
val, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
return defaultVal
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# Demo mode: pre-populated dashboard with 15 certificates, 5 agents, issuers, etc.
|
||||
# Use this to showcase certctl's dashboard with realistic data.
|
||||
#
|
||||
# Usage:
|
||||
# docker compose -f docker-compose.yml -f docker-compose.demo.yml up --build
|
||||
#
|
||||
# To start fresh (wipe previous data):
|
||||
# docker compose -f docker-compose.yml -f docker-compose.demo.yml down -v
|
||||
# docker compose -f docker-compose.yml -f docker-compose.demo.yml up --build
|
||||
|
||||
services:
|
||||
postgres:
|
||||
volumes:
|
||||
- ../migrations/seed_demo.sql:/docker-entrypoint-initdb.d/030_seed_demo.sql
|
||||
@@ -0,0 +1,311 @@
|
||||
# =============================================================================
|
||||
# certctl Testing Environment — Docker Compose
|
||||
# =============================================================================
|
||||
#
|
||||
# Spins up the full certctl platform with real CA backends for manual QA:
|
||||
#
|
||||
# 1. PostgreSQL 16 — database (clean, no demo data)
|
||||
# 2. certctl-server — control plane API + web dashboard on :8443
|
||||
# 3. certctl-agent — polls for work, deploys certs to NGINX
|
||||
# 4. step-ca — private CA (JWK provisioner, auto-bootstraps)
|
||||
# 5. Pebble — ACME test server (simulates Let's Encrypt)
|
||||
# 6. pebble-challtestsrv — DNS/HTTP challenge test server for Pebble
|
||||
# 7. NGINX — TLS target server on :8080 (HTTP) / :8444 (HTTPS)
|
||||
#
|
||||
# Usage:
|
||||
# cd deploy
|
||||
# docker compose -f docker-compose.test.yml up --build
|
||||
#
|
||||
# Dashboard: http://localhost:8443
|
||||
# API key: test-key-2026
|
||||
# NGINX: https://localhost:8444 (self-signed placeholder until cert deployed)
|
||||
#
|
||||
# See docs/test-env.md for the full walkthrough.
|
||||
# =============================================================================
|
||||
|
||||
services:
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database
|
||||
# ---------------------------------------------------------------------------
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: certctl-test-postgres
|
||||
environment:
|
||||
POSTGRES_DB: certctl
|
||||
POSTGRES_USER: certctl
|
||||
POSTGRES_PASSWORD: testpass
|
||||
volumes:
|
||||
- test_postgres_data:/var/lib/postgresql/data
|
||||
- ../migrations/000001_initial_schema.up.sql:/docker-entrypoint-initdb.d/001_schema.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/000008_verification.up.sql:/docker-entrypoint-initdb.d/008_verification.sql
|
||||
- ../migrations/000009_issuer_config.up.sql:/docker-entrypoint-initdb.d/009_issuer_config.sql
|
||||
- ../migrations/000010_target_config.up.sql:/docker-entrypoint-initdb.d/010_target_config.sql
|
||||
- ../migrations/seed.sql:/docker-entrypoint-initdb.d/020_seed.sql
|
||||
- ../migrations/seed_test.sql:/docker-entrypoint-initdb.d/025_seed_test.sql
|
||||
# No seed_demo.sql — start with a clean database for real testing
|
||||
networks:
|
||||
certctl-test:
|
||||
ipv4_address: 10.30.50.2
|
||||
ports:
|
||||
- "5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U certctl -d certctl"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
restart: unless-stopped
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pebble — ACME test server (simulates Let's Encrypt)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pebble is the official ACME test server from Let's Encrypt (RFC 8555).
|
||||
# It validates challenges via the companion challtestsrv.
|
||||
# Root CA cert available at https://pebble:15000/roots/0 (management API).
|
||||
pebble-challtestsrv:
|
||||
image: ghcr.io/letsencrypt/pebble-challtestsrv:latest
|
||||
container_name: certctl-test-challtestsrv
|
||||
# ENTRYPOINT is /app (the binary). command: provides only the FLAGS.
|
||||
# Matches the official Pebble docker-compose format.
|
||||
# -doh "" disables DoH (default :8443 would conflict with certctl server).
|
||||
# defaultIPv4 must point to the certctl-server (10.30.50.6) because that's where
|
||||
# the ACME HTTP-01 challenge server runs (port 80 inside the container).
|
||||
# Pebble resolves domains via challtestsrv, then connects to this IP to validate.
|
||||
command: -defaultIPv4 10.30.50.6 -defaultIPv6 "" -doh ""
|
||||
networks:
|
||||
certctl-test:
|
||||
ipv4_address: 10.30.50.3
|
||||
restart: unless-stopped
|
||||
|
||||
pebble:
|
||||
image: ghcr.io/letsencrypt/pebble:latest
|
||||
container_name: certctl-test-pebble
|
||||
depends_on:
|
||||
- pebble-challtestsrv
|
||||
environment:
|
||||
PEBBLE_VA_NOSLEEP: 1
|
||||
PEBBLE_VA_ALWAYS_VALID: 0
|
||||
# ENTRYPOINT is /app (the binary). command: provides only the FLAGS.
|
||||
command:
|
||||
- -config
|
||||
- /test/config/pebble-config.json
|
||||
- -dnsserver
|
||||
- "10.30.50.3:8053"
|
||||
- -strict
|
||||
volumes:
|
||||
- ./test/pebble-config.json:/test/config/pebble-config.json:ro
|
||||
networks:
|
||||
certctl-test:
|
||||
ipv4_address: 10.30.50.4
|
||||
restart: unless-stopped
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# step-ca — Private CA (Smallstep)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Auto-bootstraps on first run: generates root CA + JWK provisioner "admin".
|
||||
# Root cert: /home/step/certs/root_ca.crt (inside stepca_data volume)
|
||||
# Provisioner key: /home/step/secrets/provisioner_key (encrypted JWK)
|
||||
step-ca:
|
||||
image: smallstep/step-ca:latest
|
||||
container_name: certctl-test-stepca
|
||||
environment:
|
||||
DOCKER_STEPCA_INIT_NAME: "certctl-test-ca"
|
||||
DOCKER_STEPCA_INIT_DNS_NAMES: "step-ca,localhost"
|
||||
DOCKER_STEPCA_INIT_PROVISIONER_NAME: "admin"
|
||||
DOCKER_STEPCA_INIT_PASSWORD: "password123"
|
||||
DOCKER_STEPCA_INIT_ADDRESS: ":9000"
|
||||
volumes:
|
||||
- stepca_data:/home/step
|
||||
networks:
|
||||
certctl-test:
|
||||
ipv4_address: 10.30.50.5
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fk", "https://localhost:9000/health"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
start_period: 15s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# certctl Server (Control Plane)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Connects to PostgreSQL, Pebble (ACME), step-ca, and Local CA.
|
||||
#
|
||||
# TLS trust problem: Pebble and step-ca use self-signed root CAs that
|
||||
# aren't in Alpine's trust store. The ACME and step-ca connectors use
|
||||
# Go's default http.Client (no InsecureSkipVerify), so they need the
|
||||
# CA certs in the system trust store.
|
||||
#
|
||||
# Solution: setup-trust.sh runs as root, fetches Pebble CA from its
|
||||
# management API, copies step-ca root cert from the shared volume,
|
||||
# runs update-ca-certificates, then execs the server binary.
|
||||
certctl-server:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: Dockerfile
|
||||
container_name: certctl-test-server
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
pebble:
|
||||
condition: service_started
|
||||
step-ca:
|
||||
condition: service_healthy
|
||||
# Run as root so update-ca-certificates can write to /etc/ssl/certs.
|
||||
# Container isolation provides the security boundary.
|
||||
user: "0:0"
|
||||
entrypoint: ["/bin/sh", "/app/setup-trust.sh"]
|
||||
environment:
|
||||
# Database
|
||||
CERTCTL_DATABASE_URL: postgres://certctl:testpass@postgres:5432/certctl?sslmode=disable
|
||||
|
||||
# Server
|
||||
CERTCTL_SERVER_HOST: 0.0.0.0
|
||||
CERTCTL_SERVER_PORT: 8443
|
||||
CERTCTL_LOG_LEVEL: debug
|
||||
|
||||
# Auth — API key required (production-like)
|
||||
CERTCTL_AUTH_TYPE: api-key
|
||||
CERTCTL_AUTH_SECRET: test-key-2026
|
||||
|
||||
# Key generation — agent-side (production-like)
|
||||
CERTCTL_KEYGEN_MODE: agent
|
||||
|
||||
# Local CA issuer (iss-local) — self-signed mode (no CA cert/key paths)
|
||||
# This is the simplest issuer, always available.
|
||||
|
||||
# ACME issuer (iss-acme-staging) — pointed at Pebble
|
||||
CERTCTL_ACME_DIRECTORY_URL: https://pebble:14000/dir
|
||||
CERTCTL_ACME_EMAIL: test@certctl.dev
|
||||
CERTCTL_ACME_CHALLENGE_TYPE: http-01
|
||||
CERTCTL_ACME_INSECURE: "true"
|
||||
|
||||
# step-ca issuer (iss-stepca)
|
||||
CERTCTL_STEPCA_URL: https://step-ca:9000
|
||||
CERTCTL_STEPCA_ROOT_CERT: /stepca-data/certs/root_ca.crt
|
||||
CERTCTL_STEPCA_PROVISIONER: admin
|
||||
CERTCTL_STEPCA_PASSWORD: password123
|
||||
CERTCTL_STEPCA_KEY_PATH: /stepca-data/secrets/provisioner_key
|
||||
|
||||
# EST server (RFC 7030) — uses Local CA by default
|
||||
CERTCTL_EST_ENABLED: "true"
|
||||
CERTCTL_EST_ISSUER_ID: iss-local
|
||||
|
||||
# Network scanning
|
||||
CERTCTL_NETWORK_SCAN_ENABLED: "true"
|
||||
|
||||
# Post-deployment TLS verification
|
||||
CERTCTL_VERIFY_DEPLOYMENT: "true"
|
||||
CERTCTL_VERIFY_TIMEOUT: "10s"
|
||||
CERTCTL_VERIFY_DELAY: "3s"
|
||||
ports:
|
||||
- "8443:8443"
|
||||
volumes:
|
||||
- ./test/setup-trust.sh:/app/setup-trust.sh:ro
|
||||
# step-ca data volume (root cert at /certs/root_ca.crt, key at /secrets/provisioner_key)
|
||||
- stepca_data:/stepca-data:ro
|
||||
networks:
|
||||
certctl-test:
|
||||
ipv4_address: 10.30.50.6
|
||||
healthcheck:
|
||||
# /health requires auth when CERTCTL_AUTH_TYPE=api-key, so include the Bearer token
|
||||
test: ["CMD", "curl", "-f", "-H", "Authorization: Bearer test-key-2026", "http://localhost:8443/health"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
start_period: 30s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# NGINX — TLS Target Server
|
||||
# ---------------------------------------------------------------------------
|
||||
# The agent deploys certificates here via the shared nginx_certs volume.
|
||||
# nginx-entrypoint.sh generates a self-signed placeholder cert so NGINX
|
||||
# can boot before the agent deploys a real cert.
|
||||
#
|
||||
# Ports: 8080 (HTTP) / 8444 (HTTPS) — offset to avoid conflict with server.
|
||||
nginx:
|
||||
image: nginx:alpine
|
||||
container_name: certctl-test-nginx
|
||||
entrypoint: ["/bin/sh", "/entrypoint.sh"]
|
||||
volumes:
|
||||
- ./test/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
- ./test/nginx-entrypoint.sh:/entrypoint.sh:ro
|
||||
- nginx_certs:/etc/nginx/certs
|
||||
ports:
|
||||
- "8080:80"
|
||||
- "8444:443"
|
||||
networks:
|
||||
certctl-test:
|
||||
ipv4_address: 10.30.50.7
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fk https://localhost/health || exit 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
start_period: 15s
|
||||
retries: 5
|
||||
restart: unless-stopped
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# certctl Agent
|
||||
# ---------------------------------------------------------------------------
|
||||
# Polls the server for work, generates ECDSA P-256 keys locally,
|
||||
# deploys certs to NGINX via the shared volume, and discovers existing
|
||||
# certs in the NGINX cert directory.
|
||||
certctl-agent:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: Dockerfile.agent
|
||||
container_name: certctl-test-agent
|
||||
depends_on:
|
||||
certctl-server:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
CERTCTL_SERVER_URL: http://certctl-server:8443
|
||||
CERTCTL_API_KEY: test-key-2026
|
||||
CERTCTL_AGENT_NAME: test-agent-01
|
||||
CERTCTL_AGENT_ID: agent-test-01
|
||||
CERTCTL_KEYGEN_MODE: agent
|
||||
CERTCTL_LOG_LEVEL: debug
|
||||
CERTCTL_DISCOVERY_DIRS: /nginx-certs
|
||||
volumes:
|
||||
- agent_keys:/var/lib/certctl/keys
|
||||
- nginx_certs:/nginx-certs
|
||||
networks:
|
||||
certctl-test:
|
||||
ipv4_address: 10.30.50.8
|
||||
restart: unless-stopped
|
||||
|
||||
# =============================================================================
|
||||
# Network
|
||||
# =============================================================================
|
||||
# Static IPs are required because:
|
||||
# - Pebble needs to know the challtestsrv DNS server address (10.30.50.3)
|
||||
# - challtestsrv resolves all domains to certctl-server (10.30.50.6) for HTTP-01 challenges
|
||||
# - Avoids DNS race conditions during startup
|
||||
networks:
|
||||
certctl-test:
|
||||
driver: bridge
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 10.30.50.0/24
|
||||
|
||||
# =============================================================================
|
||||
# Volumes
|
||||
# =============================================================================
|
||||
volumes:
|
||||
test_postgres_data:
|
||||
driver: local
|
||||
stepca_data:
|
||||
driver: local
|
||||
agent_keys:
|
||||
driver: local
|
||||
nginx_certs:
|
||||
driver: local
|
||||
@@ -18,8 +18,10 @@ services:
|
||||
- ../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
|
||||
- ../migrations/000008_verification.up.sql:/docker-entrypoint-initdb.d/008_verification.sql
|
||||
- ../migrations/000009_issuer_config.up.sql:/docker-entrypoint-initdb.d/009_issuer_config.sql
|
||||
- ../migrations/000010_target_config.up.sql:/docker-entrypoint-initdb.d/010_target_config.sql
|
||||
- ../migrations/seed.sql:/docker-entrypoint-initdb.d/020_seed.sql
|
||||
networks:
|
||||
- certctl-network
|
||||
healthcheck:
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
# Certctl Helm Chart - Complete Summary
|
||||
|
||||
## Overview
|
||||
|
||||
A production-ready Helm chart for deploying certctl (self-hosted certificate lifecycle management platform) on Kubernetes. The chart provides:
|
||||
|
||||
- High availability support with multi-replica deployments
|
||||
- Persistent PostgreSQL database with automatic schema migration
|
||||
- DaemonSet or Deployment-based agent deployment
|
||||
- Comprehensive security contexts and RBAC
|
||||
- Multiple deployment scenarios (dev, prod, HA, external DB)
|
||||
- Full documentation and examples
|
||||
|
||||
## Chart Metadata
|
||||
|
||||
- **Name**: certctl
|
||||
- **Chart Version**: 0.1.0
|
||||
- **App Version**: 2.1.0
|
||||
- **Type**: application
|
||||
- **License**: BSL-1.1 (converts to Apache 2.0 in 2033)
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
deploy/helm/
|
||||
├── README.md # Main Helm chart documentation
|
||||
├── DEPLOYMENT_GUIDE.md # Step-by-step deployment guide
|
||||
├── CHART_SUMMARY.md # This file
|
||||
│
|
||||
├── certctl/
|
||||
│ ├── Chart.yaml # Chart metadata
|
||||
│ ├── values.yaml # Default configuration values
|
||||
│ ├── .helmignore # Files to ignore when building chart
|
||||
│ │
|
||||
│ └── templates/
|
||||
│ ├── _helpers.tpl # Helm template helper functions
|
||||
│ ├── NOTES.txt # Post-deployment notes
|
||||
│ │
|
||||
│ ├── server-deployment.yaml # Certctl API server deployment
|
||||
│ ├── server-service.yaml # Server Kubernetes service
|
||||
│ ├── server-configmap.yaml # Server configuration
|
||||
│ ├── server-secret.yaml # Server secrets (API key, DB password, etc)
|
||||
│ │
|
||||
│ ├── postgres-statefulset.yaml # PostgreSQL database statefulset
|
||||
│ ├── postgres-service.yaml # PostgreSQL headless service
|
||||
│ ├── postgres-secret.yaml # Database credentials secret
|
||||
│ │
|
||||
│ ├── agent-daemonset.yaml # Certctl agent daemonset/deployment
|
||||
│ ├── agent-configmap.yaml # Agent configuration
|
||||
│ │
|
||||
│ ├── ingress.yaml # Optional ingress resource
|
||||
│ └── serviceaccount.yaml # ServiceAccount and RBAC
|
||||
│
|
||||
└── examples/
|
||||
├── values-dev.yaml # Development/testing configuration
|
||||
├── values-prod-ha.yaml # Production HA configuration
|
||||
├── values-external-db.yaml # External PostgreSQL (RDS, Cloud SQL)
|
||||
└── values-acme-dns01.yaml # ACME with DNS-01 (Let's Encrypt)
|
||||
```
|
||||
|
||||
## Key Components
|
||||
|
||||
### 1. Server Deployment
|
||||
|
||||
**File**: `templates/server-deployment.yaml`
|
||||
|
||||
- Manages certctl API server instances
|
||||
- Configurable replicas (default: 1)
|
||||
- Health checks (liveness & readiness probes)
|
||||
- Security context: non-root user, read-only filesystem
|
||||
- Resource limits (default: 500m CPU, 512Mi memory)
|
||||
- Automatic restart on failure
|
||||
|
||||
**Values**:
|
||||
```yaml
|
||||
server:
|
||||
replicas: 1
|
||||
port: 8443
|
||||
auth:
|
||||
type: api-key
|
||||
apiKey: "REQUIRED"
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 128Mi}
|
||||
limits: {cpu: 500m, memory: 512Mi}
|
||||
```
|
||||
|
||||
### 2. PostgreSQL StatefulSet
|
||||
|
||||
**File**: `templates/postgres-statefulset.yaml`
|
||||
|
||||
- Persistent database storage
|
||||
- Automatic schema migrations on startup
|
||||
- Single replica (can be extended with external HA tools)
|
||||
- Health checks via pg_isready
|
||||
- Configurable storage size and class
|
||||
- Security context: non-root user (UID 999)
|
||||
|
||||
**Values**:
|
||||
```yaml
|
||||
postgresql:
|
||||
enabled: true
|
||||
storage:
|
||||
size: 10Gi
|
||||
storageClass: "" # Use default
|
||||
auth:
|
||||
database: certctl
|
||||
username: certctl
|
||||
password: "REQUIRED"
|
||||
```
|
||||
|
||||
### 3. Agent DaemonSet/Deployment
|
||||
|
||||
**File**: `templates/agent-daemonset.yaml`
|
||||
|
||||
- DaemonSet mode: one agent per Kubernetes node
|
||||
- Deployment mode: custom number of agent replicas
|
||||
- Local key storage with secure permissions (0600)
|
||||
- Health checks and automatic restart
|
||||
- Optional certificate discovery from filesystem
|
||||
|
||||
**Values**:
|
||||
```yaml
|
||||
agent:
|
||||
enabled: true
|
||||
kind: DaemonSet # or Deployment
|
||||
replicas: 1 # for Deployment only
|
||||
keyDir: /var/lib/certctl/keys
|
||||
discoveryDirs: "/etc/ssl/certs" # optional
|
||||
```
|
||||
|
||||
### 4. Ingress (Optional)
|
||||
|
||||
**File**: `templates/ingress.yaml`
|
||||
|
||||
- Optional HTTPS ingress
|
||||
- cert-manager integration for automatic TLS
|
||||
- Multiple host support
|
||||
- Path-based routing
|
||||
|
||||
**Values**:
|
||||
```yaml
|
||||
ingress:
|
||||
enabled: false
|
||||
className: nginx
|
||||
annotations:
|
||||
cert-manager.io/cluster-issuer: letsencrypt-prod
|
||||
hosts:
|
||||
- host: certctl.example.com
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
```
|
||||
|
||||
### 5. ConfigMaps and Secrets
|
||||
|
||||
**Files**:
|
||||
- `server-configmap.yaml` - Non-secret server configuration
|
||||
- `server-secret.yaml` - API key, database URL, SMTP password
|
||||
- `postgres-secret.yaml` - Database credentials
|
||||
- `agent-configmap.yaml` - Agent configuration
|
||||
|
||||
All secrets are base64-encoded and stored in Kubernetes Secrets.
|
||||
|
||||
### 6. ServiceAccount and RBAC
|
||||
|
||||
**File**: `templates/serviceaccount.yaml`
|
||||
|
||||
- Optional ServiceAccount creation
|
||||
- Optional RBAC (ClusterRole, ClusterRoleBinding)
|
||||
- Namespace-scoped by default
|
||||
|
||||
## Deployment Scenarios
|
||||
|
||||
### Development Setup
|
||||
|
||||
Use `examples/values-dev.yaml`:
|
||||
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--values examples/values-dev.yaml \
|
||||
--set server.auth.apiKey="dev-key" \
|
||||
--set postgresql.auth.password="dev-password"
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- Single server replica
|
||||
- Demo auth (no API key required)
|
||||
- Small database (5Gi)
|
||||
- LoadBalancer service for easy access
|
||||
- Debug logging level
|
||||
|
||||
### Production HA Setup
|
||||
|
||||
Use `examples/values-prod-ha.yaml`:
|
||||
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--values examples/values-prod-ha.yaml \
|
||||
--set server.auth.apiKey="$(openssl rand -base64 32)" \
|
||||
--set postgresql.auth.password="$(openssl rand -base64 32)"
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- 3 server replicas with pod anti-affinity
|
||||
- Large database storage (100Gi)
|
||||
- Pod disruption budgets
|
||||
- Prometheus monitoring enabled
|
||||
- Production resource limits
|
||||
|
||||
### External PostgreSQL
|
||||
|
||||
Use `examples/values-external-db.yaml`:
|
||||
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--values examples/values-external-db.yaml \
|
||||
--set postgresql.enabled=false \
|
||||
--set 'server.env.CERTCTL_DATABASE_URL=postgres://...'
|
||||
```
|
||||
|
||||
**Use cases**:
|
||||
- AWS RDS
|
||||
- Google Cloud SQL
|
||||
- Azure Database for PostgreSQL
|
||||
- External self-managed PostgreSQL
|
||||
|
||||
### ACME with DNS-01
|
||||
|
||||
Use `examples/values-acme-dns01.yaml`:
|
||||
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--values examples/values-acme-dns01.yaml
|
||||
```
|
||||
|
||||
**Enables**:
|
||||
- Automatic certificate issuance from Let's Encrypt
|
||||
- DNS-01 challenge (wildcard support)
|
||||
- Custom DNS provider scripts
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### Server Configuration
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------|---------|-------------|
|
||||
| `server.replicas` | 1 | Number of server replicas |
|
||||
| `server.port` | 8443 | Server port |
|
||||
| `server.auth.type` | api-key | Authentication type |
|
||||
| `server.auth.apiKey` | "" | API key (REQUIRED) |
|
||||
| `server.logging.level` | info | Log level |
|
||||
| `server.logging.format` | json | Log format |
|
||||
|
||||
### PostgreSQL Configuration
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------|---------|-------------|
|
||||
| `postgresql.enabled` | true | Enable internal PostgreSQL |
|
||||
| `postgresql.storage.size` | 10Gi | Database storage size |
|
||||
| `postgresql.storage.storageClass` | "" | Storage class name |
|
||||
| `postgresql.auth.password` | "" | Database password (REQUIRED) |
|
||||
|
||||
### Agent Configuration
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------|---------|-------------|
|
||||
| `agent.enabled` | true | Deploy agents |
|
||||
| `agent.kind` | DaemonSet | DaemonSet or Deployment |
|
||||
| `agent.replicas` | 1 | Replicas (Deployment only) |
|
||||
| `agent.keyDir` | /var/lib/certctl/keys | Key storage directory |
|
||||
|
||||
### Issuer Configuration
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------|---------|-------------|
|
||||
| `server.issuer.local.enabled` | true | Enable Local CA |
|
||||
| `server.issuer.acme.enabled` | false | Enable ACME |
|
||||
| `server.issuer.acme.directoryURL` | "" | ACME directory URL |
|
||||
| `server.issuer.acme.email` | "" | ACME email |
|
||||
| `server.issuer.acme.challengeType` | http-01 | Challenge type |
|
||||
|
||||
See `values.yaml` for complete configuration options.
|
||||
|
||||
## Helm Template Functions
|
||||
|
||||
Defined in `templates/_helpers.tpl`:
|
||||
|
||||
| Function | Purpose |
|
||||
|----------|---------|
|
||||
| `certctl.name` | Chart name |
|
||||
| `certctl.fullname` | Full release name |
|
||||
| `certctl.chart` | Chart name and version |
|
||||
| `certctl.labels` | Common labels |
|
||||
| `certctl.selectorLabels` | Selector labels |
|
||||
| `certctl.serverSelectorLabels` | Server selector labels |
|
||||
| `certctl.agentSelectorLabels` | Agent selector labels |
|
||||
| `certctl.postgresSelectorLabels` | PostgreSQL selector labels |
|
||||
| `certctl.serviceAccountName` | ServiceAccount name |
|
||||
| `certctl.serverImage` | Server image URI |
|
||||
| `certctl.agentImage` | Agent image URI |
|
||||
| `certctl.postgresImage` | PostgreSQL image URI |
|
||||
| `certctl.databaseURL` | Database connection string |
|
||||
| `certctl.serverURL` | Server URL for agents |
|
||||
|
||||
## Security Features
|
||||
|
||||
### Pod Security
|
||||
|
||||
- Non-root users (UID 1000 for app, UID 999 for PostgreSQL)
|
||||
- Read-only root filesystems
|
||||
- No privilege escalation
|
||||
- Dropped capabilities (ALL)
|
||||
- Resource limits to prevent DoS
|
||||
|
||||
### Secrets Management
|
||||
|
||||
- All sensitive data in Kubernetes Secrets
|
||||
- Base64 encoded at rest
|
||||
- Can be integrated with:
|
||||
- sealed-secrets
|
||||
- external-secrets
|
||||
- Vault
|
||||
- AWS Secrets Manager
|
||||
|
||||
### RBAC
|
||||
|
||||
- ServiceAccount per release
|
||||
- Optional ClusterRole/ClusterRoleBinding
|
||||
- Extensible for custom permissions
|
||||
|
||||
### Network Security
|
||||
|
||||
- Support for Kubernetes NetworkPolicies
|
||||
- Service-to-service communication via internal DNS
|
||||
- Optional Ingress with TLS
|
||||
|
||||
## Monitoring and Observability
|
||||
|
||||
### Health Checks
|
||||
|
||||
- Liveness probes (detect dead containers)
|
||||
- Readiness probes (detect not-ready services)
|
||||
- HTTP endpoints: `/health`, `/readyz`
|
||||
|
||||
### Logging
|
||||
|
||||
- Structured JSON logging
|
||||
- Request ID propagation
|
||||
- Configurable log levels (debug, info, warn, error)
|
||||
|
||||
### Metrics
|
||||
|
||||
- Prometheus metrics endpoint: `/api/v1/metrics/prometheus`
|
||||
- Optional ServiceMonitor for Prometheus Operator
|
||||
- Built-in metrics:
|
||||
- Certificate counts by status
|
||||
- Agent counts and status
|
||||
- Job completion/failure rates
|
||||
- Server uptime
|
||||
|
||||
## Installation Quick Reference
|
||||
|
||||
```bash
|
||||
# Development
|
||||
helm install certctl certctl/ \
|
||||
--set server.auth.apiKey=dev \
|
||||
--set postgresql.auth.password=dev
|
||||
|
||||
# Production HA
|
||||
helm install certctl certctl/ \
|
||||
--values examples/values-prod-ha.yaml \
|
||||
--set server.auth.apiKey="$(openssl rand -base64 32)" \
|
||||
--set postgresql.auth.password="$(openssl rand -base64 32)"
|
||||
|
||||
# External database
|
||||
helm install certctl certctl/ \
|
||||
--values examples/values-external-db.yaml \
|
||||
--set postgresql.enabled=false \
|
||||
--set 'server.env.CERTCTL_DATABASE_URL=postgres://...'
|
||||
|
||||
# ACME with Let's Encrypt
|
||||
helm install certctl certctl/ \
|
||||
--set server.issuer.acme.enabled=true \
|
||||
--set server.issuer.acme.directoryURL=https://acme-v02.api.letsencrypt.org/directory
|
||||
|
||||
# Check status
|
||||
kubectl get pods -l app.kubernetes.io/instance=certctl
|
||||
kubectl logs -l app.kubernetes.io/component=server -f
|
||||
|
||||
# Upgrade
|
||||
helm upgrade certctl certctl/ -f new-values.yaml
|
||||
|
||||
# Uninstall
|
||||
helm uninstall certctl
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Use Secrets Management
|
||||
|
||||
```bash
|
||||
# Use sealed-secrets
|
||||
kubectl create secret generic certctl-secrets \
|
||||
--from-literal=api-key="$(openssl rand -base64 32)" \
|
||||
--dry-run=client -o yaml | kubeseal -f - | kubectl apply -f -
|
||||
```
|
||||
|
||||
### 2. Configure Resource Limits
|
||||
|
||||
Match limits to your cluster capacity:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
resources:
|
||||
requests: {cpu: 250m, memory: 256Mi}
|
||||
limits: {cpu: 1000m, memory: 512Mi}
|
||||
```
|
||||
|
||||
### 3. Enable HA for Production
|
||||
|
||||
```yaml
|
||||
server:
|
||||
replicas: 3
|
||||
podAntiAffinity:
|
||||
requiredDuringSchedulingIgnoredDuringExecution: [...]
|
||||
```
|
||||
|
||||
### 4. Use Persistent Storage
|
||||
|
||||
```yaml
|
||||
postgresql:
|
||||
storage:
|
||||
size: 100Gi
|
||||
storageClass: fast-ssd
|
||||
```
|
||||
|
||||
### 5. Enable Monitoring
|
||||
|
||||
```yaml
|
||||
monitoring:
|
||||
enabled: true
|
||||
serviceMonitor:
|
||||
enabled: true
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
- **README.md** - Complete Helm chart documentation
|
||||
- **DEPLOYMENT_GUIDE.md** - Step-by-step deployment instructions
|
||||
- **values.yaml** - Commented configuration reference
|
||||
|
||||
## Support
|
||||
|
||||
For issues, questions, or contributions:
|
||||
- GitHub: https://github.com/shankar0123/certctl
|
||||
- Documentation: https://github.com/shankar0123/certctl/tree/main/docs
|
||||
|
||||
## License
|
||||
|
||||
BSL-1.1 (Business Source License)
|
||||
Converts to Apache 2.0 on March 28, 2033
|
||||
@@ -0,0 +1,515 @@
|
||||
# Certctl Helm Deployment Guide
|
||||
|
||||
Complete guide for deploying certctl on Kubernetes with Helm.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Prerequisites](#prerequisites)
|
||||
2. [Installation Methods](#installation-methods)
|
||||
3. [Production Deployment](#production-deployment)
|
||||
4. [Configuration Examples](#configuration-examples)
|
||||
5. [Post-Deployment Setup](#post-deployment-setup)
|
||||
6. [Monitoring and Logging](#monitoring-and-logging)
|
||||
7. [Maintenance](#maintenance)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Required Tools
|
||||
|
||||
```bash
|
||||
# Verify Kubernetes cluster access
|
||||
kubectl cluster-info
|
||||
kubectl get nodes
|
||||
|
||||
# Install Helm (if not already installed)
|
||||
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
|
||||
helm version
|
||||
|
||||
# Verify Helm installation
|
||||
helm repo list
|
||||
```
|
||||
|
||||
### Kubernetes Requirements
|
||||
|
||||
- Kubernetes 1.19 or later
|
||||
- At least 2GB available memory
|
||||
- At least 10GB available storage (for PostgreSQL)
|
||||
- Network policies support (optional, for security)
|
||||
- Ingress controller (nginx, istio, etc.) - optional
|
||||
|
||||
### Create Namespace
|
||||
|
||||
```bash
|
||||
# Create isolated namespace
|
||||
kubectl create namespace certctl
|
||||
|
||||
# Set as default namespace
|
||||
kubectl config set-context --current --namespace=certctl
|
||||
|
||||
# Label for network policies (optional)
|
||||
kubectl label namespace certctl certctl-ns=true
|
||||
```
|
||||
|
||||
## Installation Methods
|
||||
|
||||
### Method 1: Minimal Development Setup
|
||||
|
||||
Perfect for testing and development:
|
||||
|
||||
```bash
|
||||
# Install with minimal configuration
|
||||
helm install certctl certctl/certctl \
|
||||
--namespace certctl \
|
||||
--set server.auth.apiKey="dev-key-change-in-production" \
|
||||
--set postgresql.auth.password="dev-password-change-in-production"
|
||||
|
||||
# Wait for deployment
|
||||
kubectl rollout status deployment/certctl-server
|
||||
kubectl rollout status statefulset/certctl-postgres
|
||||
```
|
||||
|
||||
### Method 2: Production HA Setup
|
||||
|
||||
For production workloads:
|
||||
|
||||
```bash
|
||||
# Generate secure credentials
|
||||
API_KEY=$(openssl rand -base64 32)
|
||||
DB_PASSWORD=$(openssl rand -base64 32)
|
||||
|
||||
# Install with HA configuration
|
||||
helm install certctl certctl/certctl \
|
||||
--namespace certctl \
|
||||
--values deploy/helm/examples/values-prod-ha.yaml \
|
||||
--set server.auth.apiKey="$API_KEY" \
|
||||
--set postgresql.auth.password="$DB_PASSWORD"
|
||||
```
|
||||
|
||||
### Method 3: External PostgreSQL
|
||||
|
||||
Using managed database service:
|
||||
|
||||
```bash
|
||||
# Install with external database
|
||||
helm install certctl certctl/certctl \
|
||||
--namespace certctl \
|
||||
--values deploy/helm/examples/values-external-db.yaml \
|
||||
--set server.auth.apiKey="$API_KEY" \
|
||||
--set 'server.env.CERTCTL_DATABASE_URL=postgres://user:pass@db.example.com:5432/certctl?sslmode=require'
|
||||
```
|
||||
|
||||
### Method 4: Using Custom values.yaml
|
||||
|
||||
Recommended for GitOps workflows:
|
||||
|
||||
```bash
|
||||
# Create values file with secrets management
|
||||
cat > /tmp/certctl-values.yaml <<EOF
|
||||
server:
|
||||
auth:
|
||||
apiKey: "$API_KEY"
|
||||
logging:
|
||||
level: info
|
||||
|
||||
postgresql:
|
||||
auth:
|
||||
password: "$DB_PASSWORD"
|
||||
storage:
|
||||
size: 50Gi
|
||||
|
||||
agent:
|
||||
enabled: true
|
||||
kind: DaemonSet
|
||||
|
||||
ingress:
|
||||
enabled: true
|
||||
className: nginx
|
||||
hosts:
|
||||
- host: certctl.example.com
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
EOF
|
||||
|
||||
# Install using values file
|
||||
helm install certctl certctl/certctl \
|
||||
--namespace certctl \
|
||||
--values /tmp/certctl-values.yaml
|
||||
```
|
||||
|
||||
## Production Deployment
|
||||
|
||||
### Step 1: Prepare Environment
|
||||
|
||||
```bash
|
||||
# Create namespace
|
||||
kubectl create namespace certctl
|
||||
cd deploy/helm
|
||||
|
||||
# Generate credentials
|
||||
API_KEY=$(openssl rand -base64 32)
|
||||
DB_PASSWORD=$(openssl rand -base64 32)
|
||||
|
||||
echo "API Key: $API_KEY"
|
||||
echo "DB Password: $DB_PASSWORD"
|
||||
|
||||
# Save credentials in secure location (e.g., 1Password, Vault, AWS Secrets Manager)
|
||||
```
|
||||
|
||||
### Step 2: Prepare Storage
|
||||
|
||||
```bash
|
||||
# List available storage classes
|
||||
kubectl get storageclass
|
||||
|
||||
# If needed, create a high-performance storage class for production
|
||||
cat <<EOF | kubectl apply -f -
|
||||
apiVersion: storage.k8s.io/v1
|
||||
kind: StorageClass
|
||||
metadata:
|
||||
name: fast-ssd
|
||||
provisioner: ebs.csi.aws.com # For AWS, adjust for your cloud provider
|
||||
parameters:
|
||||
type: gp3
|
||||
iops: "3000"
|
||||
throughput: "125"
|
||||
EOF
|
||||
```
|
||||
|
||||
### Step 3: Set Up TLS with cert-manager
|
||||
|
||||
```bash
|
||||
# Install cert-manager (if not already installed)
|
||||
helm repo add jetstack https://charts.jetstack.io
|
||||
helm repo update
|
||||
helm install cert-manager jetstack/cert-manager \
|
||||
--namespace cert-manager \
|
||||
--create-namespace \
|
||||
--set installCRDs=true
|
||||
|
||||
# Create ClusterIssuer for Let's Encrypt
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: cert-manager.io/v1
|
||||
kind: ClusterIssuer
|
||||
metadata:
|
||||
name: letsencrypt-prod
|
||||
spec:
|
||||
acme:
|
||||
server: https://acme-v02.api.letsencrypt.org/directory
|
||||
email: admin@example.com
|
||||
privateKeySecretRef:
|
||||
name: letsencrypt-prod
|
||||
solvers:
|
||||
- http01:
|
||||
ingress:
|
||||
class: nginx
|
||||
EOF
|
||||
```
|
||||
|
||||
### Step 4: Install Certctl
|
||||
|
||||
```bash
|
||||
# Install using HA values
|
||||
helm install certctl certctl/ \
|
||||
--namespace certctl \
|
||||
--values examples/values-prod-ha.yaml \
|
||||
--set server.auth.apiKey="$API_KEY" \
|
||||
--set postgresql.auth.password="$DB_PASSWORD" \
|
||||
--set ingress.annotations."cert-manager\.io/cluster-issuer"=letsencrypt-prod \
|
||||
--set ingress.hosts[0].host=certctl.example.com
|
||||
|
||||
# Verify installation
|
||||
kubectl get all -l app.kubernetes.io/instance=certctl
|
||||
```
|
||||
|
||||
### Step 5: Verify Deployment
|
||||
|
||||
```bash
|
||||
# Check pod status
|
||||
kubectl get pods -l app.kubernetes.io/instance=certctl
|
||||
kubectl describe pods -l app.kubernetes.io/instance=certctl
|
||||
|
||||
# Check service status
|
||||
kubectl get svc -l app.kubernetes.io/instance=certctl
|
||||
|
||||
# Check ingress status
|
||||
kubectl get ingress
|
||||
kubectl describe ingress certctl
|
||||
|
||||
# Test API connectivity
|
||||
POD=$(kubectl get pods -l app.kubernetes.io/component=server -o jsonpath='{.items[0].metadata.name}')
|
||||
kubectl port-forward $POD 8443:8443 &
|
||||
curl -H "Authorization: Bearer $API_KEY" http://localhost:8443/health
|
||||
```
|
||||
|
||||
### Step 6: Access the Dashboard
|
||||
|
||||
```bash
|
||||
# Port forward to local machine
|
||||
kubectl port-forward svc/certctl-server 8443:8443 &
|
||||
|
||||
# Or if using Ingress:
|
||||
# Open browser: https://certctl.example.com
|
||||
# Login with API key: $API_KEY
|
||||
```
|
||||
|
||||
## Configuration Examples
|
||||
|
||||
### Example 1: ACME (Let's Encrypt)
|
||||
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--set server.issuer.acme.enabled=true \
|
||||
--set server.issuer.acme.directoryURL=https://acme-v02.api.letsencrypt.org/directory \
|
||||
--set server.issuer.acme.email=admin@example.com \
|
||||
--set server.issuer.acme.challengeType=http-01
|
||||
```
|
||||
|
||||
### Example 2: DNS-01 (Wildcard Certs)
|
||||
|
||||
Requires DNS scripts ConfigMap:
|
||||
|
||||
```bash
|
||||
# Create DNS scripts ConfigMap
|
||||
kubectl create configmap dns-scripts \
|
||||
--from-file=dns-present.sh=./scripts/dns-present.sh \
|
||||
--from-file=dns-cleanup.sh=./scripts/dns-cleanup.sh
|
||||
|
||||
# Install with DNS-01
|
||||
helm install certctl certctl/ \
|
||||
--set server.issuer.acme.enabled=true \
|
||||
--set server.issuer.acme.challengeType=dns-01 \
|
||||
--values examples/values-acme-dns01.yaml
|
||||
```
|
||||
|
||||
### Example 3: AWS RDS Database
|
||||
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--set postgresql.enabled=false \
|
||||
--set 'server.env.CERTCTL_DATABASE_URL=postgres://user:password@mydb.c9akciq32.us-east-1.rds.amazonaws.com:5432/certctl?sslmode=require'
|
||||
```
|
||||
|
||||
### Example 4: Multiple Issuers
|
||||
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--set server.issuer.local.enabled=true \
|
||||
--set server.issuer.acme.enabled=true \
|
||||
--set server.issuer.acme.directoryURL=https://acme-v02.api.letsencrypt.org/directory
|
||||
```
|
||||
|
||||
### Example 5: Email Notifications
|
||||
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--set server.smtp.enabled=true \
|
||||
--set server.smtp.host=smtp.example.com \
|
||||
--set server.smtp.port=587 \
|
||||
--set server.smtp.username=alerts@example.com \
|
||||
--set server.smtp.password="$SMTP_PASSWORD" \
|
||||
--set server.smtp.fromAddress=certctl@example.com
|
||||
```
|
||||
|
||||
## Post-Deployment Setup
|
||||
|
||||
### 1. Initial Database Setup
|
||||
|
||||
```bash
|
||||
# Check database connection
|
||||
POD=$(kubectl get pods -l app.kubernetes.io/component=postgres -o jsonpath='{.items[0].metadata.name}')
|
||||
|
||||
# Execute psql commands
|
||||
kubectl exec -it $POD -- \
|
||||
psql -U certctl -d certctl -c '\dt'
|
||||
|
||||
# View database status
|
||||
kubectl logs $POD | tail -20
|
||||
```
|
||||
|
||||
### 2. Create Default Certificates
|
||||
|
||||
```bash
|
||||
# Port forward to API
|
||||
kubectl port-forward svc/certctl-server 8443:8443 &
|
||||
|
||||
# Create a test certificate
|
||||
API_KEY="your-api-key"
|
||||
curl -X POST http://localhost:8443/api/v1/certificates \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"common_name": "test.example.com",
|
||||
"sans": ["test.example.com", "*.example.com"],
|
||||
"owner": "admin@example.com"
|
||||
}'
|
||||
```
|
||||
|
||||
### 3. Configure Agents
|
||||
|
||||
```bash
|
||||
# Get agent names
|
||||
kubectl get pods -l app.kubernetes.io/component=agent -o wide
|
||||
|
||||
# Check agent connectivity
|
||||
POD=$(kubectl get pods -l app.kubernetes.io/component=agent -o jsonpath='{.items[0].metadata.name}')
|
||||
kubectl logs $POD | grep -i heartbeat
|
||||
```
|
||||
|
||||
### 4. Set Up HTTPS for Web Dashboard
|
||||
|
||||
The Ingress will handle TLS if configured properly:
|
||||
|
||||
```bash
|
||||
# Verify ingress is ready
|
||||
kubectl get ingress
|
||||
kubectl describe ingress certctl
|
||||
|
||||
# Test HTTPS
|
||||
curl https://certctl.example.com/health
|
||||
```
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
### 1. View Logs
|
||||
|
||||
```bash
|
||||
# Server logs
|
||||
kubectl logs -l app.kubernetes.io/component=server -f --all-containers=true
|
||||
|
||||
# PostgreSQL logs
|
||||
kubectl logs -l app.kubernetes.io/component=postgres -f
|
||||
|
||||
# Agent logs
|
||||
kubectl logs -l app.kubernetes.io/component=agent -f --all-containers=true
|
||||
|
||||
# Logs from all components
|
||||
kubectl logs -l app.kubernetes.io/instance=certctl -f --all-containers=true
|
||||
```
|
||||
|
||||
### 2. Install Prometheus Monitoring
|
||||
|
||||
```bash
|
||||
# Install Prometheus operator (if not already installed)
|
||||
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
|
||||
helm repo update
|
||||
|
||||
helm install prometheus prometheus-community/kube-prometheus-stack \
|
||||
--namespace monitoring \
|
||||
--create-namespace
|
||||
|
||||
# Certctl will automatically expose metrics if monitoring.enabled=true
|
||||
helm install certctl certctl/ \
|
||||
--set monitoring.enabled=true \
|
||||
--set monitoring.serviceMonitor.enabled=true
|
||||
```
|
||||
|
||||
### 3. Set Up Alerts
|
||||
|
||||
```bash
|
||||
# Create Prometheus alerts
|
||||
cat <<EOF | kubectl apply -f -
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: PrometheusRule
|
||||
metadata:
|
||||
name: certctl-alerts
|
||||
spec:
|
||||
groups:
|
||||
- name: certctl
|
||||
interval: 30s
|
||||
rules:
|
||||
- alert: CertctlServerDown
|
||||
expr: up{job="certctl-server"} == 0
|
||||
for: 5m
|
||||
annotations:
|
||||
summary: "Certctl server is down"
|
||||
|
||||
- alert: CertificateExpiringSoon
|
||||
expr: certctl_certificate_expiring_soon > 0
|
||||
for: 1h
|
||||
annotations:
|
||||
summary: "{{ \$value }} certificates expiring soon"
|
||||
EOF
|
||||
```
|
||||
|
||||
## Maintenance
|
||||
|
||||
### Scaling
|
||||
|
||||
```bash
|
||||
# Scale server replicas
|
||||
helm upgrade certctl certctl/ \
|
||||
--set server.replicas=5
|
||||
|
||||
# Scale agents (Deployment kind only)
|
||||
helm upgrade certctl certctl/ \
|
||||
--set agent.kind=Deployment \
|
||||
--set agent.replicas=10
|
||||
```
|
||||
|
||||
### Updating
|
||||
|
||||
```bash
|
||||
# Update chart version
|
||||
helm repo update
|
||||
helm upgrade certctl certctl/certctl \
|
||||
--namespace certctl \
|
||||
-f values.yaml
|
||||
|
||||
# Verify update
|
||||
kubectl rollout status deployment/certctl-server
|
||||
kubectl rollout status statefulset/certctl-postgres
|
||||
```
|
||||
|
||||
### Backup and Restore
|
||||
|
||||
```bash
|
||||
# Backup PostgreSQL data
|
||||
kubectl exec -i $(kubectl get pods -l app.kubernetes.io/component=postgres -o jsonpath='{.items[0].metadata.name}') \
|
||||
pg_dump -U certctl certctl | gzip > certctl-backup.sql.gz
|
||||
|
||||
# Restore from backup
|
||||
zcat certctl-backup.sql.gz | kubectl exec -i $(kubectl get pods -l app.kubernetes.io/component=postgres -o jsonpath='{.items[0].metadata.name}') \
|
||||
psql -U certctl certctl
|
||||
|
||||
# Backup PVC data
|
||||
kubectl get pvc
|
||||
kubectl exec -i $(kubectl get pods -l app.kubernetes.io/component=postgres -o jsonpath='{.items[0].metadata.name}') \
|
||||
tar czf - /var/lib/postgresql/data | gzip > certctl-data-backup.tar.gz
|
||||
```
|
||||
|
||||
### Uninstall
|
||||
|
||||
```bash
|
||||
# Remove Helm release (keeps PVCs by default)
|
||||
helm uninstall certctl --namespace certctl
|
||||
|
||||
# Delete PVCs if needed
|
||||
kubectl delete pvc --all -n certctl
|
||||
|
||||
# Delete namespace
|
||||
kubectl delete namespace certctl
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
See [README.md](README.md#troubleshooting) for detailed troubleshooting steps.
|
||||
|
||||
Common commands:
|
||||
|
||||
```bash
|
||||
# Get all resources
|
||||
kubectl get all -n certctl
|
||||
|
||||
# Describe pod for events
|
||||
kubectl describe pod <pod-name> -n certctl
|
||||
|
||||
# Stream logs
|
||||
kubectl logs -f <pod-name> -n certctl
|
||||
|
||||
# Execute commands in pod
|
||||
kubectl exec -it <pod-name> -n certctl -- /bin/sh
|
||||
|
||||
# Check events
|
||||
kubectl get events -n certctl --sort-by='.lastTimestamp'
|
||||
```
|
||||
@@ -0,0 +1,234 @@
|
||||
# Certctl Helm Chart - Complete File Index
|
||||
|
||||
## Navigation Guide
|
||||
|
||||
### Getting Started
|
||||
|
||||
1. **Start here**: `INSTALLATION.md` - Quick installation guide with one-liners
|
||||
2. **Full reference**: `README.md` - Complete Helm chart documentation
|
||||
3. **Detailed guide**: `DEPLOYMENT_GUIDE.md` - Step-by-step deployment walkthrough
|
||||
4. **Architecture**: `CHART_SUMMARY.md` - Technical overview and design
|
||||
|
||||
### Chart Directory Structure
|
||||
|
||||
```
|
||||
deploy/helm/
|
||||
│
|
||||
├── README.md Main documentation (15 KB)
|
||||
├── DEPLOYMENT_GUIDE.md Step-by-step guide (12 KB)
|
||||
├── CHART_SUMMARY.md Architecture & design (13 KB)
|
||||
├── INSTALLATION.md Quick start (2.2 KB)
|
||||
├── INDEX.md This file
|
||||
│
|
||||
├── certctl/ Helm chart package
|
||||
│ ├── Chart.yaml Chart metadata
|
||||
│ ├── values.yaml Default configuration (11 KB)
|
||||
│ ├── .helmignore Build ignore patterns
|
||||
│ │
|
||||
│ └── templates/ 15 Kubernetes resource templates
|
||||
│ ├── _helpers.tpl Helper functions
|
||||
│ ├── NOTES.txt Post-install notes
|
||||
│ ├── server-deployment.yaml API server
|
||||
│ ├── server-service.yaml Server networking
|
||||
│ ├── server-configmap.yaml Server configuration
|
||||
│ ├── server-secret.yaml Server secrets
|
||||
│ ├── postgres-statefulset.yaml Database
|
||||
│ ├── postgres-service.yaml Database networking
|
||||
│ ├── postgres-secret.yaml Database secrets
|
||||
│ ├── agent-daemonset.yaml Agents (DaemonSet/Deployment)
|
||||
│ ├── agent-configmap.yaml Agent configuration
|
||||
│ ├── ingress.yaml Optional HTTPS ingress
|
||||
│ └── serviceaccount.yaml RBAC resources
|
||||
│
|
||||
└── examples/ Example configurations
|
||||
├── values-dev.yaml Development setup
|
||||
├── values-prod-ha.yaml Production HA setup
|
||||
├── values-external-db.yaml External PostgreSQL
|
||||
└── values-acme-dns01.yaml ACME DNS-01 configuration
|
||||
```
|
||||
|
||||
## File Descriptions
|
||||
|
||||
### Documentation Files
|
||||
|
||||
| File | Purpose | Size |
|
||||
|------|---------|------|
|
||||
| `README.md` | Complete Helm chart documentation, configuration reference, security considerations | 15 KB |
|
||||
| `DEPLOYMENT_GUIDE.md` | Step-by-step installation instructions, production setup, troubleshooting | 12 KB |
|
||||
| `CHART_SUMMARY.md` | Technical overview, architecture, features, best practices | 13 KB |
|
||||
| `INSTALLATION.md` | Quick start guide, one-liner commands, verification steps | 2.2 KB |
|
||||
| `INDEX.md` | This file - complete file index and navigation | - |
|
||||
|
||||
### Chart Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `Chart.yaml` | Helm chart metadata (name, version, appVersion, license) |
|
||||
| `values.yaml` | Default configuration values with comprehensive comments |
|
||||
| `.helmignore` | Files to ignore when building the chart |
|
||||
|
||||
### Template Files
|
||||
|
||||
| File | Components Created |
|
||||
|------|-------------------|
|
||||
| `_helpers.tpl` | 14 Helm template helper functions |
|
||||
| `NOTES.txt` | Post-installation notes and instructions |
|
||||
| `server-deployment.yaml` | Certctl API server deployment (1-N replicas) |
|
||||
| `server-service.yaml` | Service exposing the server |
|
||||
| `server-configmap.yaml` | Non-secret server configuration |
|
||||
| `server-secret.yaml` | Secrets (API key, DB password, SMTP) |
|
||||
| `postgres-statefulset.yaml` | PostgreSQL database with persistent storage |
|
||||
| `postgres-service.yaml` | Headless service for PostgreSQL |
|
||||
| `postgres-secret.yaml` | Database credentials |
|
||||
| `agent-daemonset.yaml` | Certctl agents (DaemonSet or Deployment) |
|
||||
| `agent-configmap.yaml` | Agent configuration |
|
||||
| `ingress.yaml` | Optional HTTPS ingress resource |
|
||||
| `serviceaccount.yaml` | ServiceAccount and RBAC resources |
|
||||
|
||||
### Example Configuration Files
|
||||
|
||||
| File | Use Case | Features |
|
||||
|------|----------|----------|
|
||||
| `values-dev.yaml` | Development/testing | Single replica, debug logging, LoadBalancer, no auth |
|
||||
| `values-prod-ha.yaml` | Production HA | 3 replicas, pod anti-affinity, monitoring, large storage |
|
||||
| `values-external-db.yaml` | External PostgreSQL | AWS RDS, Cloud SQL, Azure Database, self-managed |
|
||||
| `values-acme-dns01.yaml` | Let's Encrypt | DNS-01 challenges, wildcard certs, custom DNS scripts |
|
||||
|
||||
## Quick Links
|
||||
|
||||
### Installation Commands
|
||||
|
||||
#### Development
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--set server.auth.type=none \
|
||||
--set postgresql.auth.password=dev
|
||||
```
|
||||
|
||||
#### Production HA
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--values examples/values-prod-ha.yaml \
|
||||
--set server.auth.apiKey="$(openssl rand -base64 32)" \
|
||||
--set postgresql.auth.password="$(openssl rand -base64 32)"
|
||||
```
|
||||
|
||||
#### External Database
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--values examples/values-external-db.yaml \
|
||||
--set postgresql.enabled=false \
|
||||
--set 'server.env.CERTCTL_DATABASE_URL=postgres://...'
|
||||
```
|
||||
|
||||
### Verification Commands
|
||||
|
||||
```bash
|
||||
# Check chart syntax
|
||||
helm lint certctl/
|
||||
helm template certctl certctl/
|
||||
|
||||
# Install in cluster
|
||||
helm install certctl certctl/
|
||||
helm status certctl
|
||||
|
||||
# Check pod status
|
||||
kubectl get pods -l app.kubernetes.io/instance=certctl
|
||||
|
||||
# View logs
|
||||
kubectl logs -l app.kubernetes.io/component=server -f
|
||||
```
|
||||
|
||||
## Documentation Organization
|
||||
|
||||
### By User Role
|
||||
|
||||
**DevOps/Platform Engineers**
|
||||
- Start: `INSTALLATION.md`
|
||||
- Deep dive: `DEPLOYMENT_GUIDE.md`
|
||||
- Configuration reference: `README.md`
|
||||
|
||||
**Kubernetes Developers**
|
||||
- Architecture: `CHART_SUMMARY.md`
|
||||
- Configuration: `values.yaml`
|
||||
- Templates: `templates/`
|
||||
|
||||
**Security/SREs**
|
||||
- Security section: `README.md#security-considerations`
|
||||
- RBAC: `templates/serviceaccount.yaml`
|
||||
- Network policies: `DEPLOYMENT_GUIDE.md#network-policies`
|
||||
|
||||
**Database Administrators**
|
||||
- PostgreSQL config: `values.yaml` (postgresql section)
|
||||
- External DB setup: `examples/values-external-db.yaml`
|
||||
- Backup/restore: `DEPLOYMENT_GUIDE.md#backup-and-restore`
|
||||
|
||||
### By Task
|
||||
|
||||
**Getting Started**
|
||||
1. Read: `INSTALLATION.md`
|
||||
2. Install: `helm install certctl certctl/`
|
||||
3. Verify: Run commands in `INSTALLATION.md`
|
||||
|
||||
**Production Deployment**
|
||||
1. Read: `DEPLOYMENT_GUIDE.md`
|
||||
2. Choose: `examples/values-prod-ha.yaml`
|
||||
3. Deploy: Follow step-by-step guide
|
||||
4. Reference: `README.md` for detailed options
|
||||
|
||||
**Troubleshooting**
|
||||
- Common issues: `README.md#troubleshooting`
|
||||
- Detailed guide: `DEPLOYMENT_GUIDE.md#troubleshooting`
|
||||
- Error messages: kubectl logs and events
|
||||
|
||||
**Configuration**
|
||||
- All options: `values.yaml`
|
||||
- Examples: `examples/values-*.yaml`
|
||||
- Detailed docs: `README.md#configuration`
|
||||
|
||||
## Key Features
|
||||
|
||||
### High Availability
|
||||
- Multi-replica server deployment
|
||||
- Pod anti-affinity
|
||||
- StatefulSet for database
|
||||
- Pod disruption budgets
|
||||
|
||||
### Security
|
||||
- Non-root containers
|
||||
- Read-only filesystems
|
||||
- RBAC support
|
||||
- Kubernetes Secrets
|
||||
- Network policies
|
||||
|
||||
### Flexibility
|
||||
- Multiple issuers (Local CA, ACME, step-ca, OpenSSL)
|
||||
- Internal or external PostgreSQL
|
||||
- DaemonSet or Deployment agents
|
||||
- Optional Ingress with TLS
|
||||
- Email notifications
|
||||
|
||||
### Observability
|
||||
- Health checks
|
||||
- Structured logging
|
||||
- Prometheus metrics
|
||||
- ServiceMonitor support
|
||||
|
||||
## Support
|
||||
|
||||
- **GitHub**: https://github.com/shankar0123/certctl
|
||||
- **Issues**: Report on GitHub issues
|
||||
- **Documentation**: All docs are in `deploy/helm/`
|
||||
|
||||
## File Statistics
|
||||
|
||||
- **Total files**: 24
|
||||
- **Documentation**: 4 files (42 KB)
|
||||
- **Chart files**: 3 files
|
||||
- **Templates**: 13 files
|
||||
- **Examples**: 4 files
|
||||
- **Total size**: 144 KB
|
||||
|
||||
## License
|
||||
|
||||
All files are covered under the BSL-1.1 license (converts to Apache 2.0 in 2033).
|
||||
@@ -0,0 +1,95 @@
|
||||
# Quick Installation Guide
|
||||
|
||||
## One-Liner Installation
|
||||
|
||||
### Development (no auth)
|
||||
```bash
|
||||
helm install certctl certctl/ \
|
||||
--set server.auth.type=none \
|
||||
--set postgresql.auth.password=dev
|
||||
```
|
||||
|
||||
### Production (with API key)
|
||||
```bash
|
||||
API_KEY=$(openssl rand -base64 32)
|
||||
DB_PASSWORD=$(openssl rand -base64 32)
|
||||
|
||||
helm install certctl certctl/ \
|
||||
--values examples/values-prod-ha.yaml \
|
||||
--set server.auth.apiKey="$API_KEY" \
|
||||
--set postgresql.auth.password="$DB_PASSWORD"
|
||||
```
|
||||
|
||||
## Verify Installation
|
||||
|
||||
```bash
|
||||
# Wait for pods to be ready
|
||||
kubectl rollout status deployment/certctl-server
|
||||
kubectl rollout status statefulset/certctl-postgres
|
||||
|
||||
# Check all components
|
||||
kubectl get pods -l app.kubernetes.io/instance=certctl
|
||||
|
||||
# View server logs
|
||||
kubectl logs -l app.kubernetes.io/component=server -f
|
||||
|
||||
# Access the API
|
||||
kubectl port-forward svc/certctl-server 8443:8443 &
|
||||
curl http://localhost:8443/health
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Read Documentation**
|
||||
- `README.md` - Complete reference
|
||||
- `DEPLOYMENT_GUIDE.md` - Step-by-step guide
|
||||
- `CHART_SUMMARY.md` - Architecture overview
|
||||
|
||||
2. **Configure for Your Environment**
|
||||
- Review `examples/` for your deployment scenario
|
||||
- Customize `values.yaml` as needed
|
||||
- Use `helm upgrade` to apply changes
|
||||
|
||||
3. **Set Up Monitoring**
|
||||
- Install Prometheus (optional)
|
||||
- Enable Ingress with HTTPS
|
||||
- Configure email notifications
|
||||
|
||||
4. **Deploy Agents**
|
||||
- Agents deploy automatically as DaemonSet
|
||||
- Verify with: `kubectl get pods -l app.kubernetes.io/component=agent`
|
||||
|
||||
5. **Create Certificates**
|
||||
- Configure issuer connectors (Local CA, ACME, etc.)
|
||||
- Access web dashboard at ingress or port-forward
|
||||
|
||||
## Common Commands
|
||||
|
||||
```bash
|
||||
# List installations
|
||||
helm list
|
||||
|
||||
# View chart values
|
||||
helm values certctl
|
||||
|
||||
# Upgrade chart
|
||||
helm upgrade certctl certctl/ -f new-values.yaml
|
||||
|
||||
# Rollback to previous version
|
||||
helm rollback certctl 1
|
||||
|
||||
# Uninstall chart
|
||||
helm uninstall certctl
|
||||
|
||||
# View deployment history
|
||||
helm history certctl
|
||||
|
||||
# Dry-run installation to see generated YAML
|
||||
helm install certctl certctl/ --dry-run --debug
|
||||
```
|
||||
|
||||
## Support
|
||||
|
||||
- Full documentation in `README.md`
|
||||
- Troubleshooting in `DEPLOYMENT_GUIDE.md`
|
||||
- Issues: https://github.com/shankar0123/certctl
|
||||
@@ -0,0 +1,516 @@
|
||||
# Certctl Helm Chart
|
||||
|
||||
Production-ready Helm chart for deploying certctl (self-hosted certificate lifecycle management platform) on Kubernetes.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Quick Start](#quick-start)
|
||||
2. [Chart Features](#chart-features)
|
||||
3. [Prerequisites](#prerequisites)
|
||||
4. [Installation](#installation)
|
||||
5. [Configuration](#configuration)
|
||||
6. [Usage Examples](#usage-examples)
|
||||
7. [Upgrading](#upgrading)
|
||||
8. [Uninstalling](#uninstalling)
|
||||
9. [Architecture](#architecture)
|
||||
10. [Security Considerations](#security-considerations)
|
||||
11. [Troubleshooting](#troubleshooting)
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Add the chart repository (when available)
|
||||
helm repo add certctl https://charts.example.com
|
||||
helm repo update
|
||||
|
||||
# Install with default values
|
||||
helm install certctl certctl/certctl \
|
||||
--set server.auth.apiKey="your-secure-api-key" \
|
||||
--set postgresql.auth.password="your-secure-password"
|
||||
|
||||
# Check installation status
|
||||
kubectl get pods -l app.kubernetes.io/instance=certctl
|
||||
```
|
||||
|
||||
## Chart Features
|
||||
|
||||
- **Server Deployment** — certctl control plane with configurable replicas
|
||||
- **PostgreSQL StatefulSet** — Persistent database with automatic schema migration
|
||||
- **Agent DaemonSet or Deployment** — Flexible agent deployment (per-node or custom replicas)
|
||||
- **Ingress Support** — Optional HTTPS ingress with cert-manager integration
|
||||
- **Security Contexts** — Non-root containers, read-only filesystems, minimal capabilities
|
||||
- **Resource Limits** — Configurable CPU and memory requests/limits
|
||||
- **Health Checks** — Liveness and readiness probes on all containers
|
||||
- **ConfigMaps and Secrets** — Centralized configuration management
|
||||
- **Service Account and RBAC** — Optional cluster role bindings
|
||||
- **Pod Disruption Budgets** — HA-ready with configurable disruption budgets
|
||||
- **Monitoring** — Optional Prometheus ServiceMonitor support
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Kubernetes 1.19 or later
|
||||
- Helm 3.0 or later
|
||||
- Optional: cert-manager (for automatic TLS certificate provisioning)
|
||||
- Optional: Prometheus (for metrics scraping)
|
||||
|
||||
## Installation
|
||||
|
||||
### 1. Using Chart from Repository
|
||||
|
||||
```bash
|
||||
helm repo add certctl https://charts.example.com
|
||||
helm repo update
|
||||
helm install certctl certctl/certctl -f my-values.yaml
|
||||
```
|
||||
|
||||
### 2. Using Local Chart
|
||||
|
||||
```bash
|
||||
cd deploy/helm
|
||||
helm install certctl certctl/ \
|
||||
--set server.auth.apiKey="$(openssl rand -base64 32)" \
|
||||
--set postgresql.auth.password="$(openssl rand -base64 32)"
|
||||
```
|
||||
|
||||
### 3. Minimal Production Installation
|
||||
|
||||
```bash
|
||||
helm install certctl certctl/certctl \
|
||||
--namespace certctl \
|
||||
--create-namespace \
|
||||
--set server.auth.apiKey="change-me" \
|
||||
--set postgresql.auth.password="change-me" \
|
||||
--set server.replicas=2 \
|
||||
--set server.resources.requests.cpu=200m \
|
||||
--set server.resources.requests.memory=256Mi \
|
||||
--set ingress.enabled=true \
|
||||
--set ingress.className=nginx \
|
||||
--set ingress.hosts[0].host=certctl.example.com
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Server Configuration
|
||||
|
||||
```yaml
|
||||
server:
|
||||
replicas: 1 # Number of server replicas
|
||||
port: 8443 # Service port
|
||||
auth:
|
||||
type: api-key # Authentication type
|
||||
apiKey: "your-api-key" # REQUIRED for production
|
||||
logging:
|
||||
level: info # Log level (debug, info, warn, error)
|
||||
format: json # Output format
|
||||
issuer:
|
||||
local:
|
||||
enabled: true # Enable local CA issuer
|
||||
acme:
|
||||
enabled: false # Enable ACME issuer
|
||||
directoryURL: "" # ACME directory URL
|
||||
email: "" # ACME registration email
|
||||
challengeType: "http-01" # Challenge type (http-01, dns-01, dns-persist-01)
|
||||
```
|
||||
|
||||
### PostgreSQL Configuration
|
||||
|
||||
```yaml
|
||||
postgresql:
|
||||
enabled: true # Use managed PostgreSQL
|
||||
auth:
|
||||
database: certctl
|
||||
username: certctl
|
||||
password: "your-password" # REQUIRED
|
||||
storage:
|
||||
size: 10Gi # PVC size
|
||||
storageClass: "" # Use default StorageClass
|
||||
```
|
||||
|
||||
### Agent Configuration
|
||||
|
||||
```yaml
|
||||
agent:
|
||||
enabled: true # Deploy agents
|
||||
kind: DaemonSet # DaemonSet (one per node) or Deployment
|
||||
replicas: 1 # For Deployment kind only
|
||||
discoveryDirs: "" # Comma-separated cert discovery paths
|
||||
nodeSelector: {} # Node affinity for DaemonSet
|
||||
```
|
||||
|
||||
### Ingress Configuration
|
||||
|
||||
```yaml
|
||||
ingress:
|
||||
enabled: false
|
||||
className: nginx
|
||||
annotations:
|
||||
cert-manager.io/cluster-issuer: letsencrypt-prod
|
||||
hosts:
|
||||
- host: certctl.example.com
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
tls:
|
||||
- secretName: certctl-tls
|
||||
hosts:
|
||||
- certctl.example.com
|
||||
```
|
||||
|
||||
See `values.yaml` for all available configuration options.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Example 1: High Availability Setup
|
||||
|
||||
```yaml
|
||||
# ha-values.yaml
|
||||
server:
|
||||
replicas: 3
|
||||
resources:
|
||||
requests:
|
||||
cpu: 250m
|
||||
memory: 256Mi
|
||||
limits:
|
||||
cpu: 1000m
|
||||
memory: 512Mi
|
||||
|
||||
postgresql:
|
||||
storage:
|
||||
size: 50Gi
|
||||
|
||||
podAntiAffinity:
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
- labelSelector:
|
||||
matchExpressions:
|
||||
- key: app.kubernetes.io/component
|
||||
operator: In
|
||||
values: [server]
|
||||
topologyKey: kubernetes.io/hostname
|
||||
```
|
||||
|
||||
Deploy with:
|
||||
```bash
|
||||
helm install certctl certctl/certctl -f ha-values.yaml
|
||||
```
|
||||
|
||||
### Example 2: External PostgreSQL Database
|
||||
|
||||
```yaml
|
||||
# external-db-values.yaml
|
||||
postgresql:
|
||||
enabled: false
|
||||
|
||||
server:
|
||||
env:
|
||||
CERTCTL_DATABASE_URL: "postgres://user:password@rds.example.com:5432/certctl?sslmode=require"
|
||||
```
|
||||
|
||||
Deploy with:
|
||||
```bash
|
||||
helm install certctl certctl/certctl -f external-db-values.yaml
|
||||
```
|
||||
|
||||
### Example 3: ACME + Let's Encrypt
|
||||
|
||||
```yaml
|
||||
# acme-values.yaml
|
||||
server:
|
||||
issuer:
|
||||
acme:
|
||||
enabled: true
|
||||
directoryURL: https://acme-v02.api.letsencrypt.org/directory
|
||||
email: admin@example.com
|
||||
challengeType: dns-01
|
||||
dnsPresentScript: /scripts/dns-present.sh
|
||||
dnsCleanupScript: /scripts/dns-cleanup.sh
|
||||
dnsPropagationWait: 30s
|
||||
```
|
||||
|
||||
### Example 4: Email Notifications via Slack + SMTP
|
||||
|
||||
```yaml
|
||||
# notifications-values.yaml
|
||||
server:
|
||||
smtp:
|
||||
enabled: true
|
||||
host: smtp.example.com
|
||||
port: 587
|
||||
username: certctl@example.com
|
||||
password: "smtp-password"
|
||||
fromAddress: certctl@example.com
|
||||
useTLS: true
|
||||
|
||||
notifiers:
|
||||
slack:
|
||||
enabled: true
|
||||
webhookUrl: https://hooks.slack.com/services/YOUR/WEBHOOK/URL
|
||||
channel: "#certificates"
|
||||
```
|
||||
|
||||
## Upgrading
|
||||
|
||||
```bash
|
||||
# Update chart repository
|
||||
helm repo update
|
||||
|
||||
# Upgrade release
|
||||
helm upgrade certctl certctl/certctl -f values.yaml
|
||||
|
||||
# View upgrade history
|
||||
helm history certctl
|
||||
|
||||
# Rollback to previous version
|
||||
helm rollback certctl 1
|
||||
```
|
||||
|
||||
## Uninstalling
|
||||
|
||||
```bash
|
||||
# Delete the release (keeps data by default)
|
||||
helm uninstall certctl
|
||||
|
||||
# Also delete persistent data
|
||||
kubectl delete pvc --all -l app.kubernetes.io/instance=certctl
|
||||
|
||||
# Delete namespace
|
||||
kubectl delete namespace certctl
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Components
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ Kubernetes Cluster │
|
||||
├──────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌─────────────────┐ ┌──────────────────┐ │
|
||||
│ │ Ingress/LB │ │ Agent Pod 1 │ │
|
||||
│ │ (optional) │ │ (DaemonSet) │ │
|
||||
│ └────────┬────────┘ └──────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ ┌──────────────────┐ │
|
||||
│ ┌─────────────────────────┐ │ Agent Pod 2 │ │
|
||||
│ │ Server Deployment │ │ (DaemonSet) │ │
|
||||
│ │ (1 to N replicas) │ └──────────────────┘ │
|
||||
│ │ - REST API │ │
|
||||
│ │ - Scheduler │ ┌──────────────────┐ │
|
||||
│ │ - UI Dashboard │ │ Agent Pod N │ │
|
||||
│ └────────┬────────────────┘ │ (DaemonSet) │ │
|
||||
│ │ └──────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────┐ │
|
||||
│ │ PostgreSQL StatefulSet │ │
|
||||
│ │ - Database │ │
|
||||
│ │ - PVC (persistent) │ │
|
||||
│ └──────────────────────────┘ │
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Network Communication
|
||||
|
||||
- **Server → PostgreSQL**: Internal cluster DNS (`certctl-postgres:5432`)
|
||||
- **Agent → Server**: Internal cluster DNS (`certctl-server:8443`)
|
||||
- **External → Server**: Via Ingress or Service (ClusterIP/LoadBalancer/NodePort)
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### 1. Secrets Management
|
||||
|
||||
All sensitive data is stored in Kubernetes Secrets:
|
||||
- PostgreSQL credentials
|
||||
- API keys
|
||||
- SMTP passwords
|
||||
- ACME account secrets
|
||||
|
||||
**Best Practices:**
|
||||
- Use sealed-secrets or external-secrets operator
|
||||
- Enable encryption at rest in etcd
|
||||
- Rotate secrets regularly
|
||||
|
||||
```bash
|
||||
# Example: Using sealed-secrets
|
||||
kubectl create secret generic certctl-api-key --from-literal=api-key="$(openssl rand -base64 32)" --dry-run=client -o yaml | kubeseal -f - | kubectl apply -f -
|
||||
```
|
||||
|
||||
### 2. RBAC
|
||||
|
||||
The chart creates minimal RBAC by default:
|
||||
- ServiceAccount per release
|
||||
- ClusterRole (empty, extensible)
|
||||
- ClusterRoleBinding
|
||||
|
||||
**To restrict further:**
|
||||
```yaml
|
||||
rbac:
|
||||
create: true
|
||||
# Add specific rules here
|
||||
```
|
||||
|
||||
### 3. Pod Security
|
||||
|
||||
All containers run with:
|
||||
- Non-root user (UID 1000)
|
||||
- Read-only root filesystem
|
||||
- No privilege escalation
|
||||
- Dropped capabilities (ALL)
|
||||
|
||||
### 4. Network Policies
|
||||
|
||||
Restrict pod-to-pod communication:
|
||||
|
||||
```yaml
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: certctl-default-deny
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/instance: certctl
|
||||
policyTypes:
|
||||
- Ingress
|
||||
- Egress
|
||||
ingress:
|
||||
- from:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
name: certctl
|
||||
egress:
|
||||
- to:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
name: certctl
|
||||
- to:
|
||||
- podSelector: {}
|
||||
ports:
|
||||
- protocol: TCP
|
||||
port: 53 # DNS
|
||||
- protocol: UDP
|
||||
port: 53
|
||||
```
|
||||
|
||||
### 5. TLS/HTTPS
|
||||
|
||||
Enable HTTPS with cert-manager:
|
||||
|
||||
```bash
|
||||
helm install cert-manager jetstack/cert-manager \
|
||||
--namespace cert-manager \
|
||||
--create-namespace \
|
||||
--set installCRDs=true
|
||||
```
|
||||
|
||||
Then configure Ingress with TLS.
|
||||
|
||||
### 6. API Key Security
|
||||
|
||||
For production:
|
||||
1. Generate a strong API key: `openssl rand -base64 32`
|
||||
2. Store securely (Vault, sealed-secrets, etc.)
|
||||
3. Never commit to Git
|
||||
4. Rotate periodically
|
||||
|
||||
```bash
|
||||
# Generate and deploy API key
|
||||
NEW_KEY=$(openssl rand -base64 32)
|
||||
kubectl patch secret certctl-server -p "{\"data\":{\"api-key\":\"$(echo -n $NEW_KEY | base64)\"}}"
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### 1. Pods Not Starting
|
||||
|
||||
```bash
|
||||
# Check pod status
|
||||
kubectl get pods -l app.kubernetes.io/instance=certctl
|
||||
kubectl describe pod <pod-name>
|
||||
kubectl logs <pod-name>
|
||||
```
|
||||
|
||||
### 2. Database Connection Issues
|
||||
|
||||
```bash
|
||||
# Verify PostgreSQL is running
|
||||
kubectl get pods -l app.kubernetes.io/component=postgres
|
||||
kubectl logs -l app.kubernetes.io/component=postgres
|
||||
|
||||
# Test connection from server pod
|
||||
kubectl exec -it <server-pod> -- \
|
||||
psql postgres://certctl:password@certctl-postgres:5432/certctl
|
||||
```
|
||||
|
||||
### 3. Agent Not Connecting
|
||||
|
||||
```bash
|
||||
# Check agent logs
|
||||
kubectl logs -l app.kubernetes.io/component=agent
|
||||
|
||||
# Verify server is reachable
|
||||
kubectl exec -it <agent-pod> -- \
|
||||
wget -q -O - http://certctl-server:8443/health
|
||||
```
|
||||
|
||||
### 4. Persistent Data Loss
|
||||
|
||||
```bash
|
||||
# Check PVC status
|
||||
kubectl get pvc
|
||||
|
||||
# Verify data is being stored
|
||||
kubectl exec -it <postgres-pod> -- \
|
||||
ls -lah /var/lib/postgresql/data/postgres
|
||||
```
|
||||
|
||||
### 5. Permission Denied Errors
|
||||
|
||||
The chart runs containers as non-root (UID 1000). If you see permission errors:
|
||||
|
||||
```yaml
|
||||
# Temporarily allow root for debugging
|
||||
server:
|
||||
securityContext:
|
||||
runAsUser: 0 # NOT FOR PRODUCTION
|
||||
```
|
||||
|
||||
### 6. Out of Memory
|
||||
|
||||
Increase resource limits:
|
||||
|
||||
```bash
|
||||
helm upgrade certctl certctl/certctl \
|
||||
--set server.resources.limits.memory=1Gi \
|
||||
--set postgresql.resources.limits.memory=2Gi
|
||||
```
|
||||
|
||||
### 7. Certificate Validation Issues
|
||||
|
||||
For self-signed certificates:
|
||||
|
||||
```bash
|
||||
kubectl exec -it <pod> -- \
|
||||
CERTCTL_TLS_INSECURE_SKIP_VERIFY=true <command>
|
||||
```
|
||||
|
||||
### Common Issues and Solutions
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| `ImagePullBackOff` | Update `server.image.repository` to your registry |
|
||||
| `CrashLoopBackOff` | Check logs with `kubectl logs <pod>` |
|
||||
| `Pending` PVC | Check storage class availability |
|
||||
| Connection timeout | Verify network policies and service DNS |
|
||||
| High memory usage | Adjust `postgresql.resources.limits` and `server.resources.limits` |
|
||||
|
||||
## Support and Contributing
|
||||
|
||||
For issues, questions, or contributions, visit:
|
||||
- GitHub: https://github.com/shankar0123/certctl
|
||||
- Documentation: https://github.com/shankar0123/certctl/tree/main/docs
|
||||
|
||||
## License
|
||||
|
||||
BSL-1.1 (converts to Apache 2.0 in 2033)
|
||||
@@ -0,0 +1,31 @@
|
||||
# Patterns to ignore when building packages.
|
||||
# This supports shell glob patterns, relative path patterns, and negated
|
||||
# patterns. Only one pattern per line.
|
||||
.DS_Store
|
||||
# Common VCS dirs
|
||||
.git/
|
||||
.gitignore
|
||||
.bzr/
|
||||
.bzrignore
|
||||
.hg/
|
||||
.hgignore
|
||||
.svn/
|
||||
# Common backup files
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
*.pyo
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
# OS
|
||||
Thumbs.db
|
||||
# Helm
|
||||
Chart.lock
|
||||
@@ -0,0 +1,20 @@
|
||||
apiVersion: v2
|
||||
name: certctl
|
||||
description: Self-hosted certificate lifecycle management platform
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "2.1.0"
|
||||
keywords:
|
||||
- certificate
|
||||
- tls
|
||||
- ssl
|
||||
- pki
|
||||
- acme
|
||||
- lifecycle
|
||||
- kubernetes
|
||||
maintainers:
|
||||
- name: certctl
|
||||
home: https://github.com/shankar0123/certctl
|
||||
sources:
|
||||
- https://github.com/shankar0123/certctl
|
||||
license: BSL-1.1
|
||||
@@ -0,0 +1,68 @@
|
||||
1. Get the certctl Server URL by running:
|
||||
{{- if .Values.ingress.enabled }}
|
||||
https://{{ index .Values.ingress.hosts 0 "host" }}
|
||||
{{- else if contains "NodePort" .Values.server.service.type }}
|
||||
export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
|
||||
export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "certctl.fullname" . }}-server)
|
||||
echo http://$NODE_IP:$NODE_PORT
|
||||
{{- else if contains "LoadBalancer" .Values.server.service.type }}
|
||||
export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "certctl.fullname" . }}-server --template "{.status.loadBalancer.ingress[0].ip}")
|
||||
echo http://$SERVICE_IP:{{ .Values.server.service.port }}
|
||||
{{- else }}
|
||||
export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "certctl.name" . }},app.kubernetes.io/instance={{ .Release.Name }},app.kubernetes.io/component=server" -o jsonpath="{.items[0].metadata.name}")
|
||||
export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}")
|
||||
echo "Visit http://127.0.0.1:8080 to use your application"
|
||||
kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT
|
||||
{{- end }}
|
||||
|
||||
2. Get the default API key:
|
||||
kubectl get secret --namespace {{ .Release.Namespace }} {{ include "certctl.fullname" . }}-server -o jsonpath="{.data.api-key}" | base64 --decode; echo
|
||||
|
||||
3. Get PostgreSQL connection details:
|
||||
Host: {{ include "certctl.fullname" . }}-postgres.{{ .Release.Namespace }}.svc.cluster.local
|
||||
Port: 5432
|
||||
Database: {{ .Values.postgresql.auth.database }}
|
||||
Username: {{ .Values.postgresql.auth.username }}
|
||||
Password: $(kubectl get secret --namespace {{ .Release.Namespace }} {{ include "certctl.fullname" . }}-postgres -o jsonpath="{.data.password}" | base64 --decode)
|
||||
|
||||
4. Check deployment status:
|
||||
kubectl get pods -n {{ .Release.Namespace }} -l app.kubernetes.io/instance={{ .Release.Name }}
|
||||
|
||||
5. View server logs:
|
||||
kubectl logs -n {{ .Release.Namespace }} -l app.kubernetes.io/name={{ include "certctl.name" . }},app.kubernetes.io/component=server -f
|
||||
|
||||
{{- if .Values.agent.enabled }}
|
||||
|
||||
6. View agent logs:
|
||||
kubectl logs -n {{ .Release.Namespace }} -l app.kubernetes.io/name={{ include "certctl.name" . }},app.kubernetes.io/component=agent -f
|
||||
|
||||
{{- end }}
|
||||
|
||||
IMPORTANT NOTES FOR PRODUCTION:
|
||||
|
||||
1. Update the API key for security:
|
||||
kubectl patch secret {{ include "certctl.fullname" . }}-server -n {{ .Release.Namespace }} \
|
||||
-p '{"data":{"api-key":"'$(echo -n "YOUR_NEW_API_KEY" | base64)'"}}'
|
||||
|
||||
2. Update PostgreSQL password:
|
||||
kubectl patch secret {{ include "certctl.fullname" . }}-postgres -n {{ .Release.Namespace }} \
|
||||
-p '{"data":{"password":"'$(echo -n "YOUR_NEW_PASSWORD" | base64)'"}}'
|
||||
|
||||
3. Configure certificate issuers (ACME, step-ca, etc.) via values.yaml:
|
||||
helm upgrade {{ .Release.Name }} certctl/certctl \
|
||||
--set server.issuer.acme.enabled=true \
|
||||
--set server.issuer.acme.directoryURL=https://acme-v02.api.letsencrypt.org/directory \
|
||||
--set server.issuer.acme.email=admin@example.com
|
||||
|
||||
4. For production with persistent databases and backups:
|
||||
- Use an external PostgreSQL managed service (AWS RDS, Cloud SQL, etc.)
|
||||
- Set postgresql.enabled=false and configure CERTCTL_DATABASE_URL in values
|
||||
|
||||
5. Enable HTTPS/TLS using an Ingress with certificate management:
|
||||
- Configure cert-manager for automatic TLS certificate renewal
|
||||
- Update ingress values with your domain and certificate issuer
|
||||
|
||||
6. Review security contexts and network policies:
|
||||
- All containers run as non-root
|
||||
- Implement network policies to restrict traffic between components
|
||||
- Consider pod security policies or security standards for your cluster
|
||||
@@ -0,0 +1,125 @@
|
||||
{{/*
|
||||
Expand the name of the chart.
|
||||
*/}}
|
||||
{{- define "certctl.name" -}}
|
||||
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create a default fully qualified app name.
|
||||
*/}}
|
||||
{{- define "certctl.fullname" -}}
|
||||
{{- if .Values.fullnameOverride }}
|
||||
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
|
||||
{{- else }}
|
||||
{{- $name := default .Chart.Name .Values.nameOverride }}
|
||||
{{- if contains $name .Release.Name }}
|
||||
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
|
||||
{{- else }}
|
||||
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create chart name and version as used by the chart label.
|
||||
*/}}
|
||||
{{- define "certctl.chart" -}}
|
||||
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Common labels
|
||||
*/}}
|
||||
{{- define "certctl.labels" -}}
|
||||
helm.sh/chart: {{ include "certctl.chart" . }}
|
||||
{{ include "certctl.selectorLabels" . }}
|
||||
{{- if .Chart.AppVersion }}
|
||||
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
|
||||
{{- end }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
{{- with .Values.commonLabels }}
|
||||
{{ toYaml . }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Selector labels for the main service (server, agent, postgres)
|
||||
*/}}
|
||||
{{- define "certctl.selectorLabels" -}}
|
||||
app.kubernetes.io/name: {{ include "certctl.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Server selector labels
|
||||
*/}}
|
||||
{{- define "certctl.serverSelectorLabels" -}}
|
||||
{{ include "certctl.selectorLabels" . }}
|
||||
app.kubernetes.io/component: server
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Agent selector labels
|
||||
*/}}
|
||||
{{- define "certctl.agentSelectorLabels" -}}
|
||||
{{ include "certctl.selectorLabels" . }}
|
||||
app.kubernetes.io/component: agent
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
PostgreSQL selector labels
|
||||
*/}}
|
||||
{{- define "certctl.postgresSelectorLabels" -}}
|
||||
{{ include "certctl.selectorLabels" . }}
|
||||
app.kubernetes.io/component: postgres
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Service account name
|
||||
*/}}
|
||||
{{- define "certctl.serviceAccountName" -}}
|
||||
{{- if .Values.serviceAccount.create }}
|
||||
{{- default (include "certctl.fullname" .) .Values.serviceAccount.name }}
|
||||
{{- else }}
|
||||
{{- default "default" .Values.serviceAccount.name }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Server image
|
||||
*/}}
|
||||
{{- define "certctl.serverImage" -}}
|
||||
{{- $image := .Values.server.image }}
|
||||
{{- printf "%s:%s" $image.repository (coalesce $image.tag .Chart.AppVersion) }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Agent image
|
||||
*/}}
|
||||
{{- define "certctl.agentImage" -}}
|
||||
{{- $image := .Values.agent.image }}
|
||||
{{- printf "%s:%s" $image.repository (coalesce $image.tag .Chart.AppVersion) }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
PostgreSQL image
|
||||
*/}}
|
||||
{{- define "certctl.postgresImage" -}}
|
||||
{{- $image := .Values.postgresql.image }}
|
||||
{{- printf "%s:%s" $image.repository $image.tag }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Database connection string
|
||||
*/}}
|
||||
{{- define "certctl.databaseURL" -}}
|
||||
postgres://{{ .Values.postgresql.auth.username }}:$(POSTGRES_PASSWORD)@{{ include "certctl.fullname" . }}-postgres:5432/{{ .Values.postgresql.auth.database }}?sslmode=disable
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Server URL (for agents)
|
||||
*/}}
|
||||
{{- define "certctl.serverURL" -}}
|
||||
http://{{ include "certctl.fullname" . }}-server:{{ .Values.server.service.port }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,13 @@
|
||||
{{- if .Values.agent.enabled }}
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-agent
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: agent
|
||||
data:
|
||||
{{- if .Values.agent.discoveryDirs }}
|
||||
discovery-dirs: {{ .Values.agent.discoveryDirs | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,162 @@
|
||||
{{- if .Values.agent.enabled }}
|
||||
{{- if eq .Values.agent.kind "DaemonSet" }}
|
||||
apiVersion: apps/v1
|
||||
kind: DaemonSet
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-agent
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: agent
|
||||
spec:
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "certctl.agentSelectorLabels" . | nindent 6 }}
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "certctl.agentSelectorLabels" . | nindent 8 }}
|
||||
spec:
|
||||
serviceAccountName: {{ include "certctl.serviceAccountName" . }}
|
||||
securityContext:
|
||||
{{- toYaml .Values.agent.securityContext | nindent 8 }}
|
||||
{{- with .Values.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.agent.nodeSelector }}
|
||||
nodeSelector:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.agent.tolerations }}
|
||||
tolerations:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.agent.affinity }}
|
||||
affinity:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: agent
|
||||
image: {{ include "certctl.agentImage" . }}
|
||||
imagePullPolicy: {{ .Values.agent.image.pullPolicy }}
|
||||
env:
|
||||
- name: CERTCTL_SERVER_URL
|
||||
value: {{ include "certctl.serverURL" . }}
|
||||
- name: CERTCTL_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: api-key
|
||||
- name: CERTCTL_AGENT_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
- name: CERTCTL_KEY_DIR
|
||||
value: {{ .Values.agent.keyDir }}
|
||||
{{- if .Values.agent.discoveryDirs }}
|
||||
- name: CERTCTL_DISCOVERY_DIRS
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-agent
|
||||
key: discovery-dirs
|
||||
{{- end }}
|
||||
{{- with .Values.agent.env }}
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
resources:
|
||||
{{- toYaml .Values.agent.resources | nindent 12 }}
|
||||
volumeMounts:
|
||||
- name: agent-keys
|
||||
mountPath: {{ .Values.agent.keyDir }}
|
||||
- name: tmp
|
||||
mountPath: /tmp
|
||||
volumes:
|
||||
- name: agent-keys
|
||||
emptyDir:
|
||||
sizeLimit: 1Gi
|
||||
- name: tmp
|
||||
emptyDir: {}
|
||||
{{- else if eq .Values.agent.kind "Deployment" }}
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-agent
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: agent
|
||||
spec:
|
||||
replicas: {{ .Values.agent.replicas }}
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "certctl.agentSelectorLabels" . | nindent 6 }}
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "certctl.agentSelectorLabels" . | nindent 8 }}
|
||||
spec:
|
||||
serviceAccountName: {{ include "certctl.serviceAccountName" . }}
|
||||
securityContext:
|
||||
{{- toYaml .Values.agent.securityContext | nindent 8 }}
|
||||
{{- with .Values.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.agent.nodeSelector }}
|
||||
nodeSelector:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.agent.tolerations }}
|
||||
tolerations:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.agent.affinity }}
|
||||
affinity:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: agent
|
||||
image: {{ include "certctl.agentImage" . }}
|
||||
imagePullPolicy: {{ .Values.agent.image.pullPolicy }}
|
||||
env:
|
||||
- name: CERTCTL_SERVER_URL
|
||||
value: {{ include "certctl.serverURL" . }}
|
||||
- name: CERTCTL_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: api-key
|
||||
- name: CERTCTL_AGENT_NAME
|
||||
{{- if .Values.agent.name }}
|
||||
value: {{ .Values.agent.name | quote }}
|
||||
{{- else }}
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
{{- end }}
|
||||
- name: CERTCTL_KEY_DIR
|
||||
value: {{ .Values.agent.keyDir }}
|
||||
{{- if .Values.agent.discoveryDirs }}
|
||||
- name: CERTCTL_DISCOVERY_DIRS
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-agent
|
||||
key: discovery-dirs
|
||||
{{- end }}
|
||||
{{- with .Values.agent.env }}
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
resources:
|
||||
{{- toYaml .Values.agent.resources | nindent 12 }}
|
||||
volumeMounts:
|
||||
- name: agent-keys
|
||||
mountPath: {{ .Values.agent.keyDir }}
|
||||
- name: tmp
|
||||
mountPath: /tmp
|
||||
volumes:
|
||||
- name: agent-keys
|
||||
emptyDir:
|
||||
sizeLimit: 1Gi
|
||||
- name: tmp
|
||||
emptyDir: {}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,41 @@
|
||||
{{- if .Values.ingress.enabled }}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
{{- with .Values.ingress.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
{{- if .Values.ingress.className }}
|
||||
ingressClassName: {{ .Values.ingress.className }}
|
||||
{{- end }}
|
||||
{{- if .Values.ingress.tls }}
|
||||
tls:
|
||||
{{- range .Values.ingress.tls }}
|
||||
- hosts:
|
||||
{{- range .hosts }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
secretName: {{ .secretName }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
rules:
|
||||
{{- range .Values.ingress.hosts }}
|
||||
- host: {{ .host | quote }}
|
||||
http:
|
||||
paths:
|
||||
{{- range .paths }}
|
||||
- path: {{ .path }}
|
||||
pathType: {{ .pathType }}
|
||||
backend:
|
||||
service:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
port:
|
||||
number: {{ $.Values.server.service.port }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,12 @@
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-postgres
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: postgres
|
||||
type: Opaque
|
||||
stringData:
|
||||
password: {{ .Values.postgresql.auth.password | default "changeme" | quote }}
|
||||
username: {{ .Values.postgresql.auth.username | quote }}
|
||||
database: {{ .Values.postgresql.auth.database | quote }}
|
||||
@@ -0,0 +1,18 @@
|
||||
{{- if .Values.postgresql.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-postgres
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: postgres
|
||||
spec:
|
||||
clusterIP: None
|
||||
ports:
|
||||
- port: {{ .Values.postgresql.service.port }}
|
||||
targetPort: postgres
|
||||
protocol: TCP
|
||||
name: postgres
|
||||
selector:
|
||||
{{- include "certctl.postgresSelectorLabels" . | nindent 4 }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,79 @@
|
||||
{{- if .Values.postgresql.enabled }}
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-postgres
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: postgres
|
||||
spec:
|
||||
serviceName: {{ include "certctl.fullname" . }}-postgres
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "certctl.postgresSelectorLabels" . | nindent 6 }}
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "certctl.postgresSelectorLabels" . | nindent 8 }}
|
||||
spec:
|
||||
securityContext:
|
||||
{{- toYaml .Values.postgresql.securityContext | nindent 8 }}
|
||||
{{- with .Values.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: postgres
|
||||
image: {{ include "certctl.postgresImage" . }}
|
||||
imagePullPolicy: {{ .Values.postgresql.image.pullPolicy }}
|
||||
ports:
|
||||
- name: postgres
|
||||
containerPort: 5432
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: POSTGRES_DB
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-postgres
|
||||
key: database
|
||||
- name: POSTGRES_USER
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-postgres
|
||||
key: username
|
||||
- name: POSTGRES_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-postgres
|
||||
key: password
|
||||
- name: POSTGRES_INITDB_ARGS
|
||||
value: "--encoding=UTF8"
|
||||
livenessProbe:
|
||||
{{- toYaml .Values.postgresql.livenessProbe | nindent 12 }}
|
||||
readinessProbe:
|
||||
{{- toYaml .Values.postgresql.readinessProbe | nindent 12 }}
|
||||
resources:
|
||||
{{- toYaml .Values.postgresql.resources | nindent 12 }}
|
||||
volumeMounts:
|
||||
- name: postgres-data
|
||||
mountPath: /var/lib/postgresql/data
|
||||
subPath: postgres
|
||||
- name: postgres-init
|
||||
mountPath: /docker-entrypoint-initdb.d
|
||||
volumes:
|
||||
- name: postgres-init
|
||||
emptyDir: {}
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
name: postgres-data
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
{{- if .Values.postgresql.storage.storageClass }}
|
||||
storageClassName: {{ .Values.postgresql.storage.storageClass }}
|
||||
{{- end }}
|
||||
resources:
|
||||
requests:
|
||||
storage: {{ .Values.postgresql.storage.size }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,36 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: server
|
||||
data:
|
||||
log-level: {{ .Values.server.logging.level | quote }}
|
||||
auth-type: {{ .Values.server.auth.type | quote }}
|
||||
keygen-mode: {{ .Values.server.keygen.mode | quote }}
|
||||
rate-limit-rps: {{ .Values.server.rateLimiting.rps | quote }}
|
||||
rate-limit-burst: {{ .Values.server.rateLimiting.burst | quote }}
|
||||
{{- if .Values.server.cors.origins }}
|
||||
cors-origins: {{ .Values.server.cors.origins | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.server.networkScan.enabled }}
|
||||
network-scan-interval: {{ .Values.server.networkScan.interval | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.server.est.enabled }}
|
||||
est-issuer-id: {{ .Values.server.est.issuerID | quote }}
|
||||
{{- if .Values.server.est.profileID }}
|
||||
est-profile-id: {{ .Values.server.est.profileID | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.server.smtp.enabled }}
|
||||
smtp-host: {{ .Values.server.smtp.host | quote }}
|
||||
smtp-port: {{ .Values.server.smtp.port | quote }}
|
||||
smtp-username: {{ .Values.server.smtp.username | quote }}
|
||||
smtp-from-address: {{ .Values.server.smtp.fromAddress | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.server.issuer.acme.enabled }}
|
||||
acme-directory-url: {{ .Values.server.issuer.acme.directoryURL | quote }}
|
||||
acme-email: {{ .Values.server.issuer.acme.email | quote }}
|
||||
acme-challenge-type: {{ .Values.server.issuer.acme.challengeType | quote }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,196 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: server
|
||||
spec:
|
||||
{{- if gt (int .Values.server.replicas) 1 }}
|
||||
replicas: {{ .Values.server.replicas }}
|
||||
{{- end }}
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "certctl.serverSelectorLabels" . | nindent 6 }}
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "certctl.serverSelectorLabels" . | nindent 8 }}
|
||||
annotations:
|
||||
checksum/config: {{ include (print $.Template.BasePath "/server-configmap.yaml") . | sha256sum }}
|
||||
checksum/secret: {{ include (print $.Template.BasePath "/server-secret.yaml") . | sha256sum }}
|
||||
spec:
|
||||
serviceAccountName: {{ include "certctl.serviceAccountName" . }}
|
||||
securityContext:
|
||||
{{- toYaml .Values.server.securityContext | nindent 8 }}
|
||||
{{- with .Values.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: server
|
||||
image: {{ include "certctl.serverImage" . }}
|
||||
imagePullPolicy: {{ .Values.server.image.pullPolicy }}
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: {{ .Values.server.port }}
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: CERTCTL_SERVER_HOST
|
||||
value: "0.0.0.0"
|
||||
- name: CERTCTL_SERVER_PORT
|
||||
value: "{{ .Values.server.port }}"
|
||||
- name: CERTCTL_DATABASE_URL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: database-url
|
||||
- name: POSTGRES_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-postgres
|
||||
key: password
|
||||
- name: CERTCTL_LOG_LEVEL
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: log-level
|
||||
- name: CERTCTL_LOG_FORMAT
|
||||
value: "json"
|
||||
- name: CERTCTL_AUTH_TYPE
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: auth-type
|
||||
{{- if eq .Values.server.auth.type "api-key" }}
|
||||
- name: CERTCTL_AUTH_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: api-key
|
||||
{{- end }}
|
||||
- name: CERTCTL_KEYGEN_MODE
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: keygen-mode
|
||||
- name: CERTCTL_RATE_LIMIT_RPS
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: rate-limit-rps
|
||||
- name: CERTCTL_RATE_LIMIT_BURST
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: rate-limit-burst
|
||||
{{- if .Values.server.cors.origins }}
|
||||
- name: CERTCTL_CORS_ORIGINS
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: cors-origins
|
||||
{{- end }}
|
||||
{{- if .Values.server.networkScan.enabled }}
|
||||
- name: CERTCTL_NETWORK_SCAN_ENABLED
|
||||
value: "true"
|
||||
- name: CERTCTL_NETWORK_SCAN_INTERVAL
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: network-scan-interval
|
||||
{{- end }}
|
||||
{{- if .Values.server.est.enabled }}
|
||||
- name: CERTCTL_EST_ENABLED
|
||||
value: "true"
|
||||
- name: CERTCTL_EST_ISSUER_ID
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: est-issuer-id
|
||||
{{- if .Values.server.est.profileID }}
|
||||
- name: CERTCTL_EST_PROFILE_ID
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: est-profile-id
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.server.smtp.enabled }}
|
||||
- name: CERTCTL_SMTP_HOST
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: smtp-host
|
||||
- name: CERTCTL_SMTP_PORT
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: smtp-port
|
||||
- name: CERTCTL_SMTP_USERNAME
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: smtp-username
|
||||
- name: CERTCTL_SMTP_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: smtp-password
|
||||
- name: CERTCTL_SMTP_FROM_ADDRESS
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: smtp-from-address
|
||||
{{- end }}
|
||||
{{- if .Values.server.issuer.acme.enabled }}
|
||||
- name: CERTCTL_ACME_DIRECTORY_URL
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: acme-directory-url
|
||||
- name: CERTCTL_ACME_EMAIL
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: acme-email
|
||||
- name: CERTCTL_ACME_CHALLENGE_TYPE
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
key: acme-challenge-type
|
||||
{{- end }}
|
||||
{{- with .Values.server.env }}
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
livenessProbe:
|
||||
{{- toYaml .Values.server.livenessProbe | nindent 12 }}
|
||||
readinessProbe:
|
||||
{{- toYaml .Values.server.readinessProbe | nindent 12 }}
|
||||
resources:
|
||||
{{- toYaml .Values.server.resources | nindent 12 }}
|
||||
volumeMounts:
|
||||
- name: tmp
|
||||
mountPath: /tmp
|
||||
{{- if .Values.server.volumeMounts }}
|
||||
{{- toYaml .Values.server.volumeMounts | nindent 12 }}
|
||||
{{- end }}
|
||||
volumes:
|
||||
- name: tmp
|
||||
emptyDir: {}
|
||||
{{- if .Values.server.volumes }}
|
||||
{{- toYaml .Values.server.volumes | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- if .Values.nodeAffinity }}
|
||||
affinity:
|
||||
nodeAffinity:
|
||||
{{- toYaml .Values.nodeAffinity | nindent 10 }}
|
||||
{{- else if .Values.podAntiAffinity }}
|
||||
affinity:
|
||||
podAntiAffinity:
|
||||
{{- toYaml .Values.podAntiAffinity | nindent 10 }}
|
||||
{{- else if .Values.podAffinity }}
|
||||
affinity:
|
||||
podAffinity:
|
||||
{{- toYaml .Values.podAffinity | nindent 10 }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,16 @@
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: server
|
||||
type: Opaque
|
||||
stringData:
|
||||
database-url: postgres://{{ .Values.postgresql.auth.username }}:$(POSTGRES_PASSWORD)@{{ include "certctl.fullname" . }}-postgres:5432/{{ .Values.postgresql.auth.database }}?sslmode=disable
|
||||
{{- if and (eq .Values.server.auth.type "api-key") .Values.server.auth.apiKey }}
|
||||
api-key: {{ .Values.server.auth.apiKey | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.server.smtp.enabled }}
|
||||
smtp-password: {{ .Values.server.smtp.password | quote }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,20 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}-server
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: server
|
||||
{{- with .Values.server.service.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
type: {{ .Values.server.service.type }}
|
||||
ports:
|
||||
- port: {{ .Values.server.service.port }}
|
||||
targetPort: http
|
||||
protocol: TCP
|
||||
name: http
|
||||
selector:
|
||||
{{- include "certctl.serverSelectorLabels" . | nindent 4 }}
|
||||
@@ -0,0 +1,37 @@
|
||||
{{- if .Values.serviceAccount.create }}
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: {{ include "certctl.serviceAccountName" . }}
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
{{- with .Values.serviceAccount.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.rbac.create }}
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: ClusterRole
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
rules: []
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: ClusterRoleBinding
|
||||
metadata:
|
||||
name: {{ include "certctl.fullname" . }}
|
||||
labels:
|
||||
{{- include "certctl.labels" . | nindent 4 }}
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: ClusterRole
|
||||
name: {{ include "certctl.fullname" . }}
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: {{ include "certctl.serviceAccountName" . }}
|
||||
namespace: {{ .Release.Namespace }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,434 @@
|
||||
# Default values for certctl Helm chart
|
||||
# This is a YAML-formatted file.
|
||||
# Declare variables to be passed into your templates.
|
||||
|
||||
# Namespace override (optional)
|
||||
namespace: ""
|
||||
|
||||
# Global configuration
|
||||
commonLabels: {}
|
||||
imagePullSecrets: []
|
||||
nameOverride: ""
|
||||
fullnameOverride: ""
|
||||
|
||||
# ==============================================================================
|
||||
# Certctl Server Configuration
|
||||
# ==============================================================================
|
||||
server:
|
||||
# Number of replicas (for HA deployments)
|
||||
replicas: 1
|
||||
|
||||
# Image configuration
|
||||
image:
|
||||
repository: ghcr.io/shankar0123/certctl
|
||||
tag: "" # defaults to Chart.appVersion
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
# Server port
|
||||
port: 8443
|
||||
|
||||
# Resource requests and limits
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 128Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 512Mi
|
||||
|
||||
# Pod security context
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 1000
|
||||
runAsGroup: 1000
|
||||
fsGroup: 1000
|
||||
readOnlyRootFilesystem: true
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities:
|
||||
drop:
|
||||
- ALL
|
||||
|
||||
# Liveness and readiness probes
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
initialDelaySeconds: 10
|
||||
periodSeconds: 10
|
||||
timeoutSeconds: 5
|
||||
failureThreshold: 3
|
||||
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /readyz
|
||||
port: http
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 5
|
||||
timeoutSeconds: 3
|
||||
failureThreshold: 2
|
||||
|
||||
# Service type (ClusterIP, LoadBalancer, NodePort)
|
||||
service:
|
||||
type: ClusterIP
|
||||
port: 8443
|
||||
annotations: {}
|
||||
|
||||
# Authentication configuration
|
||||
auth:
|
||||
type: api-key # Options: api-key, none (for demo only)
|
||||
apiKey: "" # REQUIRED in production - set via --set or values override
|
||||
|
||||
# Logging configuration
|
||||
logging:
|
||||
level: info # debug, info, warn, error
|
||||
format: json # json or text
|
||||
|
||||
# SMTP configuration for email notifications (optional)
|
||||
smtp:
|
||||
enabled: false
|
||||
host: ""
|
||||
port: 587
|
||||
username: ""
|
||||
password: ""
|
||||
fromAddress: ""
|
||||
useTLS: true
|
||||
|
||||
# Certificate digest digest (periodic email summary)
|
||||
digest:
|
||||
enabled: false
|
||||
interval: "24h"
|
||||
recipients: []
|
||||
# Example:
|
||||
# - admin@example.com
|
||||
# - ops@example.com
|
||||
|
||||
# Enrollment over Secure Transport (EST) configuration
|
||||
est:
|
||||
enabled: false
|
||||
issuerID: "iss-local"
|
||||
profileID: ""
|
||||
|
||||
# Rate limiting configuration
|
||||
rateLimiting:
|
||||
rps: 100 # Requests per second
|
||||
burst: 200 # Burst capacity
|
||||
|
||||
# Network scanning configuration
|
||||
networkScan:
|
||||
enabled: false
|
||||
interval: "6h"
|
||||
|
||||
# Certificate key generation mode
|
||||
keygen:
|
||||
mode: agent # Options: agent (production), server (demo with warning)
|
||||
|
||||
# CORS configuration
|
||||
cors:
|
||||
origins: "" # Comma-separated list, empty means deny all cross-origin requests
|
||||
|
||||
# Issuer connectors configuration
|
||||
issuer:
|
||||
local:
|
||||
enabled: true
|
||||
# For sub-CA mode, provide these paths:
|
||||
# caCertPath: /path/to/ca.crt
|
||||
# caKeyPath: /path/to/ca.key
|
||||
|
||||
acme:
|
||||
enabled: false
|
||||
directoryURL: ""
|
||||
email: ""
|
||||
challengeType: "http-01" # Options: http-01, dns-01, dns-persist-01
|
||||
# DNS configuration (for dns-01 or dns-persist-01)
|
||||
# dnsPresentScript: /path/to/dns-present.sh
|
||||
# dnsCleanupScript: /path/to/dns-cleanup.sh
|
||||
# dnsPropagationWait: "30s"
|
||||
# dnsPersistIssuerDomain: "validation.example.com"
|
||||
# EAB configuration (for ZeroSSL, Google Trust Services, etc.)
|
||||
# eabKid: ""
|
||||
# eabHmac: ""
|
||||
|
||||
stepca:
|
||||
enabled: false
|
||||
# rootCAPath: /path/to/root_ca.crt
|
||||
# intermediateCAPath: /path/to/intermediate_ca.crt
|
||||
# provisionerName: ""
|
||||
# provisionerPassword: ""
|
||||
|
||||
openssl:
|
||||
enabled: false
|
||||
# signScript: /path/to/sign.sh
|
||||
# revokeScript: /path/to/revoke.sh
|
||||
# crlScript: /path/to/crl.sh
|
||||
# timeoutSeconds: 30
|
||||
|
||||
# Notifier connectors configuration
|
||||
notifiers:
|
||||
slack:
|
||||
enabled: false
|
||||
# webhookUrl: ""
|
||||
# channel: ""
|
||||
# username: ""
|
||||
# iconEmoji: ""
|
||||
|
||||
teams:
|
||||
enabled: false
|
||||
# webhookUrl: ""
|
||||
|
||||
pagerduty:
|
||||
enabled: false
|
||||
# routingKey: ""
|
||||
# severity: warning
|
||||
|
||||
opsgenie:
|
||||
enabled: false
|
||||
# apiKey: ""
|
||||
# priority: P3
|
||||
|
||||
# Additional environment variables
|
||||
# Will be passed as-is to the server container
|
||||
env: {}
|
||||
# Example:
|
||||
# CERTCTL_SCHEDULER_RENEWAL_CHECK_INTERVAL: "1h"
|
||||
# CERTCTL_DATABASE_MAX_CONNS: "25"
|
||||
|
||||
# Additional volume mounts for custom configurations
|
||||
# volumeMounts: []
|
||||
# - name: ca-cert
|
||||
# mountPath: /etc/ssl/certs/ca.crt
|
||||
# subPath: ca.crt
|
||||
|
||||
# Additional volumes
|
||||
# volumes: []
|
||||
# - name: ca-cert
|
||||
# secret:
|
||||
# secretName: ca-cert
|
||||
|
||||
# ==============================================================================
|
||||
# PostgreSQL Configuration
|
||||
# ==============================================================================
|
||||
postgresql:
|
||||
# Enable/disable PostgreSQL (set to false if using external database)
|
||||
enabled: true
|
||||
|
||||
# Image configuration
|
||||
image:
|
||||
repository: postgres
|
||||
tag: "16-alpine"
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
# Authentication
|
||||
auth:
|
||||
database: certctl
|
||||
username: certctl
|
||||
password: "" # REQUIRED - set via --set or values override
|
||||
|
||||
# Storage configuration
|
||||
storage:
|
||||
size: 10Gi
|
||||
storageClass: "" # Uses default StorageClass if empty
|
||||
# deleteOnTermination: false # Keep data on Helm uninstall
|
||||
|
||||
# Resource requests and limits
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 256Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 512Mi
|
||||
|
||||
# Pod security context
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 999
|
||||
runAsGroup: 999
|
||||
fsGroup: 999
|
||||
|
||||
# Liveness and readiness probes
|
||||
livenessProbe:
|
||||
exec:
|
||||
command:
|
||||
- /bin/sh
|
||||
- -c
|
||||
- pg_isready -U certctl -d certctl
|
||||
initialDelaySeconds: 10
|
||||
periodSeconds: 10
|
||||
timeoutSeconds: 5
|
||||
failureThreshold: 3
|
||||
|
||||
readinessProbe:
|
||||
exec:
|
||||
command:
|
||||
- /bin/sh
|
||||
- -c
|
||||
- pg_isready -U certctl -d certctl
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 5
|
||||
timeoutSeconds: 3
|
||||
failureThreshold: 2
|
||||
|
||||
# Service configuration
|
||||
service:
|
||||
type: ClusterIP
|
||||
port: 5432
|
||||
|
||||
# PostgreSQL-specific settings
|
||||
postgresqlConfig: {}
|
||||
# Example:
|
||||
# max_connections: "200"
|
||||
# shared_buffers: "256MB"
|
||||
|
||||
# ==============================================================================
|
||||
# Certctl Agent Configuration
|
||||
# ==============================================================================
|
||||
agent:
|
||||
# Enable/disable agent deployment
|
||||
enabled: true
|
||||
|
||||
# Deployment strategy: DaemonSet (recommended) or Deployment
|
||||
kind: DaemonSet # Options: DaemonSet, Deployment
|
||||
|
||||
# Image configuration
|
||||
image:
|
||||
repository: ghcr.io/shankar0123/certctl-agent
|
||||
tag: "" # defaults to Chart.appVersion
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
# Number of replicas (for Deployment kind; ignored for DaemonSet)
|
||||
replicas: 1
|
||||
|
||||
# Resource requests and limits
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 200m
|
||||
memory: 256Mi
|
||||
|
||||
# Pod security context
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 1000
|
||||
runAsGroup: 1000
|
||||
fsGroup: 1000
|
||||
readOnlyRootFilesystem: true
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities:
|
||||
drop:
|
||||
- ALL
|
||||
|
||||
# Agent name (can be overridden per pod via StatefulSet ordinals)
|
||||
name: "" # If empty, uses release name
|
||||
|
||||
# Key storage directory
|
||||
keyDir: /var/lib/certctl/keys
|
||||
|
||||
# Certificate discovery directories (comma-separated)
|
||||
discoveryDirs: ""
|
||||
# Example: "/etc/ssl/certs,/etc/pki/tls"
|
||||
|
||||
# Node selector for agent pods (for DaemonSet)
|
||||
nodeSelector: {}
|
||||
# Example:
|
||||
# node-role.kubernetes.io/worker: "true"
|
||||
|
||||
# Tolerations for agent pods
|
||||
tolerations: []
|
||||
# Example:
|
||||
# - key: node-role
|
||||
# operator: Equal
|
||||
# value: worker
|
||||
# effect: NoSchedule
|
||||
|
||||
# Affinity rules
|
||||
affinity: {}
|
||||
|
||||
# Additional environment variables
|
||||
env: {}
|
||||
|
||||
# ==============================================================================
|
||||
# Ingress Configuration
|
||||
# ==============================================================================
|
||||
ingress:
|
||||
enabled: false
|
||||
className: ""
|
||||
annotations: {}
|
||||
# kubernetes.io/ingress.class: nginx
|
||||
# cert-manager.io/cluster-issuer: letsencrypt-prod
|
||||
hosts:
|
||||
- host: certctl.local
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
tls: []
|
||||
# - secretName: certctl-tls
|
||||
# hosts:
|
||||
# - certctl.local
|
||||
|
||||
# ==============================================================================
|
||||
# Service Account Configuration
|
||||
# ==============================================================================
|
||||
serviceAccount:
|
||||
create: true
|
||||
annotations: {}
|
||||
name: "" # defaults to release name if empty
|
||||
|
||||
# ==============================================================================
|
||||
# RBAC Configuration
|
||||
# ==============================================================================
|
||||
rbac:
|
||||
create: true
|
||||
|
||||
# ==============================================================================
|
||||
# Pod Disruption Budget (for HA deployments)
|
||||
# ==============================================================================
|
||||
podDisruptionBudget:
|
||||
enabled: false
|
||||
minAvailable: 1
|
||||
# maxUnavailable: 1
|
||||
|
||||
# ==============================================================================
|
||||
# Monitoring Configuration
|
||||
# ==============================================================================
|
||||
monitoring:
|
||||
enabled: false
|
||||
# Prometheus ServiceMonitor
|
||||
serviceMonitor:
|
||||
enabled: false
|
||||
interval: 30s
|
||||
scrapeTimeout: 10s
|
||||
# labels: {}
|
||||
# selector: {}
|
||||
|
||||
# ==============================================================================
|
||||
# Advanced Configuration
|
||||
# ==============================================================================
|
||||
|
||||
# Node affinity for server pods
|
||||
nodeAffinity: {}
|
||||
|
||||
# Pod affinity for server pods
|
||||
podAffinity: {}
|
||||
|
||||
# Pod anti-affinity for server pods (for HA)
|
||||
podAntiAffinity: {}
|
||||
# Example:
|
||||
# podAntiAffinity:
|
||||
# preferredDuringSchedulingIgnoredDuringExecution:
|
||||
# - weight: 100
|
||||
# podAffinityTerm:
|
||||
# labelSelector:
|
||||
# matchExpressions:
|
||||
# - key: app.kubernetes.io/name
|
||||
# operator: In
|
||||
# values:
|
||||
# - certctl
|
||||
# topologyKey: kubernetes.io/hostname
|
||||
|
||||
# Custom labels for all resources
|
||||
customLabels: {}
|
||||
|
||||
# Custom annotations for all resources
|
||||
customAnnotations: {}
|
||||
@@ -0,0 +1,77 @@
|
||||
# Certctl with ACME DNS-01 Challenge (Let's Encrypt)
|
||||
# Enables automatic certificate issuance from Let's Encrypt
|
||||
# using DNS-01 verification (wildcard-capable)
|
||||
|
||||
server:
|
||||
auth:
|
||||
type: api-key
|
||||
apiKey: "CHANGE_ME"
|
||||
|
||||
issuer:
|
||||
local:
|
||||
enabled: true
|
||||
|
||||
acme:
|
||||
enabled: true
|
||||
directoryURL: https://acme-v02.api.letsencrypt.org/directory
|
||||
email: admin@example.com
|
||||
challengeType: dns-01
|
||||
dnsPresentScript: /scripts/dns-present.sh
|
||||
dnsCleanupScript: /scripts/dns-cleanup.sh
|
||||
dnsPropagationWait: 30s
|
||||
# For DNS-PERSIST-01 (standing validation record, no per-renewal updates):
|
||||
# challengeType: dns-persist-01
|
||||
# dnsPersistIssuerDomain: validation.example.com
|
||||
|
||||
# Mount DNS scripts as ConfigMap
|
||||
volumes:
|
||||
- name: dns-scripts
|
||||
configMap:
|
||||
name: dns-scripts
|
||||
defaultMode: 0755
|
||||
|
||||
volumeMounts:
|
||||
- name: dns-scripts
|
||||
mountPath: /scripts
|
||||
readOnly: true
|
||||
|
||||
postgresql:
|
||||
enabled: true
|
||||
storage:
|
||||
size: 20Gi
|
||||
|
||||
agent:
|
||||
enabled: true
|
||||
kind: DaemonSet
|
||||
|
||||
ingress:
|
||||
enabled: true
|
||||
className: nginx
|
||||
hosts:
|
||||
- host: certctl.example.com
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
|
||||
---
|
||||
# You'll need to create the DNS scripts ConfigMap separately:
|
||||
#
|
||||
# kubectl create configmap dns-scripts \
|
||||
# --from-file=dns-present.sh=./scripts/dns-present.sh \
|
||||
# --from-file=dns-cleanup.sh=./scripts/dns-cleanup.sh
|
||||
#
|
||||
# Example dns-present.sh (Cloudflare):
|
||||
# #!/bin/bash
|
||||
# DOMAIN=$1
|
||||
# TOKEN=$2
|
||||
#
|
||||
# curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records" \
|
||||
# -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
|
||||
# -d "{\"type\":\"TXT\",\"name\":\"_acme-challenge.${DOMAIN}\",\"content\":\"${TOKEN}\"}"
|
||||
#
|
||||
# Example dns-cleanup.sh (Cloudflare):
|
||||
# #!/bin/bash
|
||||
# DOMAIN=$1
|
||||
#
|
||||
# curl -X DELETE "https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}" \
|
||||
# -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}"
|
||||
@@ -0,0 +1,99 @@
|
||||
# Certctl Development Configuration
|
||||
# Lightweight setup for development and testing
|
||||
# - Single server replica
|
||||
# - Small PostgreSQL storage
|
||||
# - Minimal resource limits
|
||||
# - No ingress or monitoring
|
||||
# - Demo auth mode (no API key required)
|
||||
|
||||
server:
|
||||
replicas: 1
|
||||
|
||||
image:
|
||||
repository: ghcr.io/shankar0123/certctl
|
||||
pullPolicy: IfNotPresent # Use latest tag
|
||||
|
||||
port: 8443
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 200m
|
||||
memory: 256Mi
|
||||
|
||||
auth:
|
||||
type: none # Demo mode - no authentication
|
||||
|
||||
logging:
|
||||
level: debug
|
||||
format: json
|
||||
|
||||
service:
|
||||
type: LoadBalancer # Easy external access for dev
|
||||
|
||||
issuer:
|
||||
local:
|
||||
enabled: true
|
||||
|
||||
rateLimiting:
|
||||
rps: 100
|
||||
burst: 200
|
||||
|
||||
postgresql:
|
||||
enabled: true
|
||||
|
||||
image:
|
||||
repository: postgres
|
||||
tag: "16-alpine"
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
auth:
|
||||
database: certctl
|
||||
username: certctl
|
||||
password: "dev-password-change-me"
|
||||
|
||||
storage:
|
||||
size: 5Gi
|
||||
storageClass: "" # Use default storage class
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 128Mi
|
||||
limits:
|
||||
cpu: 200m
|
||||
memory: 256Mi
|
||||
|
||||
agent:
|
||||
enabled: true
|
||||
kind: Deployment
|
||||
replicas: 1
|
||||
|
||||
image:
|
||||
repository: ghcr.io/shankar0123/certctl-agent
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 25m
|
||||
memory: 32Mi
|
||||
limits:
|
||||
cpu: 100m
|
||||
memory: 128Mi
|
||||
|
||||
ingress:
|
||||
enabled: false
|
||||
|
||||
serviceAccount:
|
||||
create: true
|
||||
|
||||
rbac:
|
||||
create: true
|
||||
|
||||
monitoring:
|
||||
enabled: false
|
||||
|
||||
customLabels:
|
||||
environment: development
|
||||
@@ -0,0 +1,50 @@
|
||||
# Certctl with External PostgreSQL Database
|
||||
# Use this when PostgreSQL is managed externally:
|
||||
# - AWS RDS
|
||||
# - Cloud SQL (Google Cloud)
|
||||
# - Azure Database for PostgreSQL
|
||||
# - Self-managed PostgreSQL server
|
||||
|
||||
server:
|
||||
replicas: 2
|
||||
|
||||
auth:
|
||||
type: api-key
|
||||
apiKey: "CHANGE_ME"
|
||||
|
||||
issuer:
|
||||
local:
|
||||
enabled: true
|
||||
|
||||
# Pass external database URL via environment variable
|
||||
env:
|
||||
CERTCTL_DATABASE_URL: "postgres://certctl:CHANGE_ME@postgres.example.com:5432/certctl?sslmode=require"
|
||||
|
||||
# Disable internal PostgreSQL
|
||||
postgresql:
|
||||
enabled: false
|
||||
|
||||
agent:
|
||||
enabled: true
|
||||
kind: DaemonSet
|
||||
|
||||
ingress:
|
||||
enabled: true
|
||||
className: nginx
|
||||
hosts:
|
||||
- host: certctl.example.com
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
|
||||
# For AWS RDS with IAM authentication:
|
||||
# env:
|
||||
# CERTCTL_DATABASE_URL: "postgres://certctl:CHANGE_ME@mydb.123456789.us-east-1.rds.amazonaws.com:5432/certctl?sslmode=require"
|
||||
|
||||
# For Google Cloud SQL:
|
||||
# env:
|
||||
# CERTCTL_DATABASE_URL: "postgres://certctl:CHANGE_ME@/certctl?host=/cloudsql/PROJECT:REGION:INSTANCE&sslmode=require"
|
||||
|
||||
# For Azure Database:
|
||||
# env:
|
||||
# CERTCTL_DATABASE_URL: "postgres://certctl@servername:CHANGE_ME@servername.postgres.database.azure.com:5432/certctl?sslmode=require"
|
||||
@@ -0,0 +1,159 @@
|
||||
# Certctl Production HA Configuration
|
||||
# High availability deployment with:
|
||||
# - 3 server replicas with pod anti-affinity
|
||||
# - Large PostgreSQL storage
|
||||
# - Resource limits for production
|
||||
# - Prometheus monitoring
|
||||
# - Network policies enforcement
|
||||
|
||||
namespace: certctl
|
||||
|
||||
server:
|
||||
replicas: 3
|
||||
|
||||
image:
|
||||
repository: ghcr.io/shankar0123/certctl
|
||||
tag: "2.1.0"
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
port: 8443
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 250m
|
||||
memory: 256Mi
|
||||
limits:
|
||||
cpu: 1000m
|
||||
memory: 512Mi
|
||||
|
||||
auth:
|
||||
type: api-key
|
||||
apiKey: "CHANGE_ME_IN_PRODUCTION" # Use --set or sealed-secrets
|
||||
|
||||
logging:
|
||||
level: info
|
||||
format: json
|
||||
|
||||
service:
|
||||
type: ClusterIP
|
||||
annotations:
|
||||
prometheus.io/scrape: "true"
|
||||
prometheus.io/port: "8443"
|
||||
prometheus.io/path: "/api/v1/metrics/prometheus"
|
||||
|
||||
issuer:
|
||||
local:
|
||||
enabled: true
|
||||
acme:
|
||||
enabled: true
|
||||
directoryURL: https://acme-v02.api.letsencrypt.org/directory
|
||||
email: admin@example.com
|
||||
challengeType: dns-01
|
||||
|
||||
rateLimiting:
|
||||
rps: 500
|
||||
burst: 1000
|
||||
|
||||
postgresql:
|
||||
enabled: true
|
||||
|
||||
image:
|
||||
repository: postgres
|
||||
tag: "16-alpine"
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
auth:
|
||||
database: certctl
|
||||
username: certctl
|
||||
password: "CHANGE_ME_IN_PRODUCTION" # Use --set or sealed-secrets
|
||||
|
||||
storage:
|
||||
size: 100Gi
|
||||
storageClass: "fast-ssd" # Use your high-performance storage class
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 500m
|
||||
memory: 512Mi
|
||||
limits:
|
||||
cpu: 2000m
|
||||
memory: 2Gi
|
||||
|
||||
agent:
|
||||
enabled: true
|
||||
kind: DaemonSet
|
||||
|
||||
image:
|
||||
repository: ghcr.io/shankar0123/certctl-agent
|
||||
tag: "2.1.0"
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 128Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 256Mi
|
||||
|
||||
discoveryDirs: "/etc/ssl/certs,/etc/pki/tls,/etc/ssl"
|
||||
|
||||
ingress:
|
||||
enabled: true
|
||||
className: nginx
|
||||
annotations:
|
||||
cert-manager.io/cluster-issuer: letsencrypt-prod
|
||||
nginx.ingress.kubernetes.io/ssl-redirect: "true"
|
||||
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
|
||||
hosts:
|
||||
- host: certctl.example.com
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
tls:
|
||||
- secretName: certctl-tls
|
||||
hosts:
|
||||
- certctl.example.com
|
||||
|
||||
serviceAccount:
|
||||
create: true
|
||||
annotations:
|
||||
eks.amazonaws.com/role-arn: arn:aws:iam::ACCOUNT:role/certctl-role # For IRSA on AWS
|
||||
|
||||
rbac:
|
||||
create: true
|
||||
|
||||
podDisruptionBudget:
|
||||
enabled: true
|
||||
minAvailable: 2
|
||||
|
||||
monitoring:
|
||||
enabled: true
|
||||
serviceMonitor:
|
||||
enabled: true
|
||||
interval: 30s
|
||||
scrapeTimeout: 10s
|
||||
|
||||
# Pod anti-affinity for HA
|
||||
podAntiAffinity:
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
- labelSelector:
|
||||
matchExpressions:
|
||||
- key: app.kubernetes.io/name
|
||||
operator: In
|
||||
values:
|
||||
- certctl
|
||||
- key: app.kubernetes.io/component
|
||||
operator: In
|
||||
values:
|
||||
- server
|
||||
topologyKey: kubernetes.io/hostname
|
||||
|
||||
customLabels:
|
||||
environment: production
|
||||
team: platform
|
||||
cost-center: ops
|
||||
|
||||
customAnnotations:
|
||||
slack-alerts: "#ops"
|
||||
backup-policy: daily
|
||||
File diff suppressed because it is too large
Load Diff
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# Generate a self-signed placeholder certificate so NGINX can boot
|
||||
# before the certctl agent deploys a real certificate.
|
||||
# Once the agent deploys, it overwrites these files and reloads NGINX.
|
||||
|
||||
CERT_DIR="/etc/nginx/certs"
|
||||
mkdir -p "$CERT_DIR"
|
||||
|
||||
# Make cert directory world-writable so the certctl-agent container
|
||||
# (which shares this volume) can overwrite the placeholder certs.
|
||||
chmod 777 "$CERT_DIR"
|
||||
|
||||
if [ ! -f "$CERT_DIR/cert.pem" ]; then
|
||||
echo "Generating self-signed placeholder certificate..."
|
||||
apk add --no-cache openssl > /dev/null 2>&1
|
||||
openssl req -x509 -nodes -days 1 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
|
||||
-keyout "$CERT_DIR/key.pem" \
|
||||
-out "$CERT_DIR/cert.pem" \
|
||||
-subj "/CN=placeholder.certctl.test" \
|
||||
2>/dev/null
|
||||
# Make placeholder certs writable by the agent container
|
||||
chmod 666 "$CERT_DIR/cert.pem" "$CERT_DIR/key.pem"
|
||||
echo "Placeholder certificate generated."
|
||||
fi
|
||||
|
||||
# Start NGINX in foreground
|
||||
exec nginx -g "daemon off;"
|
||||
@@ -0,0 +1,42 @@
|
||||
# NGINX configuration for certctl test environment.
|
||||
# The agent deploys certificates to /etc/nginx/certs/ and reloads NGINX.
|
||||
# On startup, NGINX uses a self-signed placeholder so it can boot before any cert is deployed.
|
||||
|
||||
# Generate a self-signed placeholder on container start (see entrypoint in compose).
|
||||
# Once the agent deploys a real cert, it overwrites these files and reloads.
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
# HTTP → redirect to HTTPS (optional, for realism)
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
# HTTPS server — serves whatever cert the agent has deployed
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name _;
|
||||
|
||||
ssl_certificate /etc/nginx/certs/cert.pem;
|
||||
ssl_certificate_key /etc/nginx/certs/key.pem;
|
||||
|
||||
# Modern TLS settings
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_prefer_server_ciphers off;
|
||||
|
||||
location / {
|
||||
default_type text/plain;
|
||||
return 200 'certctl test environment — NGINX is serving TLS\n';
|
||||
}
|
||||
|
||||
location /health {
|
||||
default_type text/plain;
|
||||
return 200 'ok\n';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"pebble": {
|
||||
"listenAddress": "0.0.0.0:14000",
|
||||
"managementListenAddress": "0.0.0.0:15000",
|
||||
"certificate": "test/certs/localhost/cert.pem",
|
||||
"privateKey": "test/certs/localhost/key.pem",
|
||||
"httpPort": 80,
|
||||
"tlsPort": 443,
|
||||
"ocspResponderURL": "",
|
||||
"externalAccountBindingRequired": false,
|
||||
"retryAfter": {
|
||||
"authz": 3,
|
||||
"order": 5
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+937
@@ -0,0 +1,937 @@
|
||||
#!/usr/bin/env bash
|
||||
# =============================================================================
|
||||
# certctl End-to-End Test Script
|
||||
# =============================================================================
|
||||
#
|
||||
# Automates the full lifecycle test from docs/test-env.md:
|
||||
# 1. Bring up all 7 containers (build from source)
|
||||
# 2. Wait for every service to be healthy
|
||||
# 3. Verify pre-seeded data (agents, issuers, targets, profiles)
|
||||
# 4. Issue a certificate via Local CA → deploy to NGINX → verify TLS
|
||||
# 5. Issue a certificate via ACME/Pebble → verify
|
||||
# 6. Issue a certificate via step-ca → verify
|
||||
# 7. Test revocation + CRL
|
||||
# 8. Test discovery
|
||||
# 9. Test renewal (re-issue step-ca cert, check version history)
|
||||
# 10. EST enrollment (RFC 7030) — cacerts + simpleenroll
|
||||
# 11. S/MIME issuance — emailProtection EKU + adaptive KeyUsage
|
||||
# 12. API spot checks + print summary
|
||||
#
|
||||
# Usage:
|
||||
# cd certctl/deploy
|
||||
# ./test/run-test.sh # full run (build + test)
|
||||
# ./test/run-test.sh --no-build # skip docker build, reuse existing containers
|
||||
# ./test/run-test.sh --no-teardown # leave containers running after test
|
||||
#
|
||||
# Requirements: docker, curl, openssl, jq (or python3 for json parsing)
|
||||
# =============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------------
|
||||
COMPOSE_FILE="docker-compose.test.yml"
|
||||
API_URL="http://localhost:8443"
|
||||
API_KEY="test-key-2026"
|
||||
NGINX_TLS="localhost:8444"
|
||||
AUTH_HEADER="Authorization: Bearer ${API_KEY}"
|
||||
|
||||
# Flags
|
||||
BUILD=true
|
||||
TEARDOWN=true
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--no-build) BUILD=false ;;
|
||||
--no-teardown) TEARDOWN=false ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
CYAN='\033[0;36m'
|
||||
BOLD='\033[1m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
SKIP=0
|
||||
|
||||
pass() {
|
||||
PASS=$((PASS + 1))
|
||||
echo -e " ${GREEN}PASS${NC} $1"
|
||||
}
|
||||
|
||||
fail() {
|
||||
FAIL=$((FAIL + 1))
|
||||
echo -e " ${RED}FAIL${NC} $1"
|
||||
if [ -n "${2:-}" ]; then
|
||||
echo -e " ${RED}$2${NC}"
|
||||
fi
|
||||
}
|
||||
|
||||
skip() {
|
||||
SKIP=$((SKIP + 1))
|
||||
echo -e " ${YELLOW}SKIP${NC} $1"
|
||||
}
|
||||
|
||||
info() {
|
||||
echo -e "${CYAN}==>${NC} $1"
|
||||
}
|
||||
|
||||
header() {
|
||||
echo ""
|
||||
echo -e "${BOLD}─── $1 ───${NC}"
|
||||
}
|
||||
|
||||
# API helper: GET endpoint, return JSON body. Exits 1 on HTTP error.
|
||||
api_get() {
|
||||
local path="$1"
|
||||
curl -sf -H "${AUTH_HEADER}" "${API_URL}${path}" 2>/dev/null
|
||||
}
|
||||
|
||||
# API helper: POST with optional JSON body
|
||||
api_post() {
|
||||
local path="$1"
|
||||
local body="${2:-}"
|
||||
if [ -n "$body" ]; then
|
||||
curl -sf -X POST -H "${AUTH_HEADER}" -H "Content-Type: application/json" \
|
||||
-d "$body" "${API_URL}${path}" 2>/dev/null
|
||||
else
|
||||
curl -sf -X POST -H "${AUTH_HEADER}" "${API_URL}${path}" 2>/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
# Wait for an HTTP endpoint to return 200. Retries with backoff.
|
||||
wait_for_http() {
|
||||
local url="$1"
|
||||
local label="$2"
|
||||
local max_wait="${3:-120}"
|
||||
local elapsed=0
|
||||
local interval=3
|
||||
|
||||
while [ $elapsed -lt $max_wait ]; do
|
||||
if curl -sf -H "${AUTH_HEADER}" "$url" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
sleep $interval
|
||||
elapsed=$((elapsed + interval))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# Extract a field from JSON using python3 (no jq dependency)
|
||||
json_field() {
|
||||
python3 -c "import sys,json; d=json.load(sys.stdin); print($1)" 2>/dev/null
|
||||
}
|
||||
|
||||
# Wait for a job to reach a terminal state (Completed or Failed)
|
||||
# Usage: wait_for_job <cert_id> <max_seconds>
|
||||
# Returns 0 if Completed, 1 if Failed/timeout
|
||||
wait_for_jobs_done() {
|
||||
local cert_id="$1"
|
||||
local max_wait="${2:-180}"
|
||||
local elapsed=0
|
||||
local interval=5
|
||||
|
||||
while [ $elapsed -lt $max_wait ]; do
|
||||
local jobs_json
|
||||
jobs_json=$(api_get "/api/v1/jobs" 2>/dev/null || echo '{"data":[]}')
|
||||
|
||||
# Check if all jobs for this cert are in terminal state
|
||||
# API returns jobs under "data" key (not "jobs")
|
||||
local pending
|
||||
pending=$(echo "$jobs_json" | python3 -c "
|
||||
import sys, json
|
||||
data = json.load(sys.stdin)
|
||||
jobs = data.get('data') or data.get('jobs') or []
|
||||
active = [j for j in jobs if j.get('certificate_id') == '$cert_id'
|
||||
and j.get('status') not in ('Completed', 'Failed', 'Cancelled')]
|
||||
print(len(active))
|
||||
" 2>/dev/null || echo "99")
|
||||
|
||||
if [ "$pending" = "0" ]; then
|
||||
# Check how many jobs exist and their terminal states
|
||||
local job_counts
|
||||
job_counts=$(echo "$jobs_json" | python3 -c "
|
||||
import sys, json
|
||||
data = json.load(sys.stdin)
|
||||
jobs = data.get('data') or data.get('jobs') or []
|
||||
mine = [j for j in jobs if j.get('certificate_id') == '$cert_id']
|
||||
completed = len([j for j in mine if j.get('status') == 'Completed'])
|
||||
failed = len([j for j in mine if j.get('status') in ('Failed', 'Cancelled')])
|
||||
print(f'{len(mine)} {completed} {failed}')
|
||||
" 2>/dev/null || echo "0 0 0")
|
||||
local total_jobs completed_jobs failed_jobs
|
||||
total_jobs=$(echo "$job_counts" | cut -d' ' -f1)
|
||||
completed_jobs=$(echo "$job_counts" | cut -d' ' -f2)
|
||||
failed_jobs=$(echo "$job_counts" | cut -d' ' -f3)
|
||||
|
||||
if [ "$completed_jobs" -gt 0 ]; then
|
||||
return 0 # At least one job completed successfully
|
||||
fi
|
||||
if [ "$total_jobs" -gt 0 ] && [ "$failed_jobs" -gt 0 ]; then
|
||||
return 1 # All jobs are in terminal state but none completed — all failed
|
||||
fi
|
||||
fi
|
||||
|
||||
sleep $interval
|
||||
elapsed=$((elapsed + interval))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# Get the TLS cert subject from NGINX for a given SNI
|
||||
get_tls_subject() {
|
||||
local sni="$1"
|
||||
echo | openssl s_client -connect "$NGINX_TLS" -servername "$sni" 2>/dev/null \
|
||||
| openssl x509 -noout -subject 2>/dev/null \
|
||||
| sed 's/subject=//' | sed 's/^ *//'
|
||||
}
|
||||
|
||||
get_tls_issuer() {
|
||||
local sni="$1"
|
||||
echo | openssl s_client -connect "$NGINX_TLS" -servername "$sni" 2>/dev/null \
|
||||
| openssl x509 -noout -issuer 2>/dev/null \
|
||||
| sed 's/issuer=//' | sed 's/^ *//'
|
||||
}
|
||||
|
||||
# Get the TLS cert SANs from NGINX for a given SNI
|
||||
# Modern CAs (including Let's Encrypt / Pebble) put domains only in SAN, not Subject CN.
|
||||
get_tls_san() {
|
||||
local sni="$1"
|
||||
echo | openssl s_client -connect "$NGINX_TLS" -servername "$sni" 2>/dev/null \
|
||||
| openssl x509 -noout -ext subjectAltName 2>/dev/null \
|
||||
| grep -i "DNS:" | sed 's/^ *//'
|
||||
}
|
||||
|
||||
# Check if NGINX is serving a cert that matches the given domain (checks Subject then SAN)
|
||||
check_tls_identity() {
|
||||
local domain="$1"
|
||||
local subject issuer san
|
||||
subject=$(get_tls_subject "$domain")
|
||||
issuer=$(get_tls_issuer "$domain")
|
||||
san=$(get_tls_san "$domain")
|
||||
if echo "$subject" | grep -qi "$domain" || echo "$san" | grep -qi "$domain"; then
|
||||
echo "MATCH"
|
||||
echo "Subject: $subject"
|
||||
echo "SAN: $san"
|
||||
echo "Issuer: $issuer"
|
||||
else
|
||||
echo "NO_MATCH"
|
||||
echo "Subject: $subject"
|
||||
echo "SAN: $san"
|
||||
echo "Issuer: $issuer"
|
||||
fi
|
||||
}
|
||||
|
||||
# SQL exec in the postgres container
|
||||
psql_exec() {
|
||||
docker exec certctl-test-postgres psql -U certctl -d certctl -tAc "$1" 2>/dev/null
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cleanup trap
|
||||
# ---------------------------------------------------------------------------
|
||||
cleanup() {
|
||||
if [ "$TEARDOWN" = true ]; then
|
||||
info "Tearing down test environment..."
|
||||
docker compose -f "$COMPOSE_FILE" down -v >/dev/null 2>&1 || true
|
||||
else
|
||||
info "Leaving containers running (--no-teardown)"
|
||||
fi
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 0: Environment Check
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 0: Environment Check"
|
||||
|
||||
# Make sure we're in the deploy directory
|
||||
if [ ! -f "$COMPOSE_FILE" ]; then
|
||||
echo -e "${RED}ERROR: $COMPOSE_FILE not found.${NC}"
|
||||
echo "Run this script from the certctl/deploy directory:"
|
||||
echo " cd certctl/deploy && ./test/run-test.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for cmd in docker curl openssl python3; do
|
||||
if command -v "$cmd" >/dev/null 2>&1; then
|
||||
pass "$cmd available"
|
||||
else
|
||||
fail "$cmd not found" "Install $cmd and try again"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
if docker compose version >/dev/null 2>&1; then
|
||||
pass "docker compose available"
|
||||
else
|
||||
fail "docker compose not available" "Install Docker Compose v2+"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 1: Start the Stack
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 1: Start Test Environment"
|
||||
|
||||
# Teardown any previous run
|
||||
info "Cleaning up previous test environment..."
|
||||
docker compose -f "$COMPOSE_FILE" down -v >/dev/null 2>&1 || true
|
||||
|
||||
# Set the cleanup trap AFTER the initial teardown
|
||||
trap cleanup EXIT
|
||||
|
||||
if [ "$BUILD" = true ]; then
|
||||
info "Building and starting containers (this takes 2-5 minutes on first run)..."
|
||||
docker compose -f "$COMPOSE_FILE" up --build -d 2>&1 | tail -5
|
||||
else
|
||||
info "Starting containers (--no-build)..."
|
||||
docker compose -f "$COMPOSE_FILE" up -d 2>&1 | tail -5
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 2: Wait for Services
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 2: Waiting for Services"
|
||||
|
||||
info "Waiting for PostgreSQL..."
|
||||
if docker compose -f "$COMPOSE_FILE" exec -T postgres pg_isready -U certctl -d certctl >/dev/null 2>&1 ||
|
||||
wait_for_http "${API_URL}/health" "postgres" 60; then
|
||||
pass "PostgreSQL ready"
|
||||
else
|
||||
fail "PostgreSQL not ready after 60s"
|
||||
fi
|
||||
|
||||
info "Waiting for certctl server..."
|
||||
if wait_for_http "${API_URL}/health" "server" 120; then
|
||||
pass "certctl server healthy"
|
||||
# Show trust setup + connector init for debugging
|
||||
echo " --- Server startup (trust setup) ---"
|
||||
docker logs certctl-test-server 2>&1 | grep -E "trust|Added|Extract|provisioner|Pre-launch|key file|WARNING|CERTCTL_" | head -15
|
||||
echo " ---"
|
||||
else
|
||||
fail "certctl server not healthy after 120s"
|
||||
echo ""
|
||||
echo "Server logs:"
|
||||
docker logs certctl-test-server --tail 30
|
||||
exit 1
|
||||
fi
|
||||
|
||||
info "Waiting for NGINX..."
|
||||
if wait_for_http "http://localhost:8080" "nginx" 30; then
|
||||
pass "NGINX healthy"
|
||||
else
|
||||
# NGINX might not respond to plain curl on /health without the right path
|
||||
# Check docker health instead
|
||||
if docker inspect certctl-test-nginx --format='{{.State.Health.Status}}' 2>/dev/null | grep -q healthy; then
|
||||
pass "NGINX healthy (docker healthcheck)"
|
||||
else
|
||||
skip "NGINX health check inconclusive (will verify via TLS later)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Give the agent a few seconds to register and send first heartbeat
|
||||
info "Waiting for agent heartbeat (up to 45s)..."
|
||||
AGENT_READY=false
|
||||
for i in $(seq 1 15); do
|
||||
AGENT_STATUS=$(api_get "/api/v1/agents/agent-test-01" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null || echo "")
|
||||
if [ "$AGENT_STATUS" = "online" ]; then
|
||||
AGENT_READY=true
|
||||
break
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
if [ "$AGENT_READY" = true ]; then
|
||||
pass "Agent online"
|
||||
else
|
||||
skip "Agent not yet online (may be slow to heartbeat — continuing)"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 3: Verify Pre-Seeded Data
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 3: Verify Pre-Seeded Data"
|
||||
|
||||
# Agents
|
||||
AGENT_COUNT=$(api_get "/api/v1/agents" | python3 -c "import sys,json; print(json.load(sys.stdin).get('total',0))" 2>/dev/null || echo 0)
|
||||
if [ "$AGENT_COUNT" -ge 2 ]; then
|
||||
pass "Agents: $AGENT_COUNT found (agent-test-01 + server-scanner)"
|
||||
else
|
||||
fail "Agents: expected >= 2, got $AGENT_COUNT"
|
||||
fi
|
||||
|
||||
# Issuers
|
||||
ISSUER_COUNT=$(api_get "/api/v1/issuers" | python3 -c "import sys,json; print(json.load(sys.stdin).get('total',0))" 2>/dev/null || echo 0)
|
||||
if [ "$ISSUER_COUNT" -ge 3 ]; then
|
||||
pass "Issuers: $ISSUER_COUNT found (iss-local, iss-acme-staging, iss-stepca)"
|
||||
else
|
||||
fail "Issuers: expected >= 3, got $ISSUER_COUNT" "Check seed_test.sql loaded correctly"
|
||||
fi
|
||||
|
||||
# Targets
|
||||
TARGET_COUNT=$(api_get "/api/v1/targets" | python3 -c "import sys,json; print(json.load(sys.stdin).get('total',0))" 2>/dev/null || echo 0)
|
||||
if [ "$TARGET_COUNT" -ge 1 ]; then
|
||||
pass "Targets: $TARGET_COUNT found (target-test-nginx)"
|
||||
else
|
||||
fail "Targets: expected >= 1, got $TARGET_COUNT" "seed_test.sql may have failed after iss-local"
|
||||
fi
|
||||
|
||||
# Profile
|
||||
PROFILE_RESP=$(api_get "/api/v1/profiles" 2>/dev/null || echo '{"total":0}')
|
||||
PROFILE_COUNT=$(echo "$PROFILE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('total',0))" 2>/dev/null || echo 0)
|
||||
if [ "$PROFILE_COUNT" -ge 2 ]; then
|
||||
pass "Profiles: $PROFILE_COUNT found (prof-test-tls, prof-test-smime)"
|
||||
else
|
||||
fail "Profiles: expected >= 1, got $PROFILE_COUNT"
|
||||
fi
|
||||
|
||||
# Bail if seed data is broken
|
||||
if [ "$ISSUER_COUNT" -lt 3 ] || [ "$TARGET_COUNT" -lt 1 ]; then
|
||||
echo ""
|
||||
echo -e "${RED}Seed data is incomplete. Cannot continue.${NC}"
|
||||
echo "Check PostgreSQL logs: docker logs certctl-test-postgres"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 4: Local CA Issuance
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 4: Local CA Certificate Issuance"
|
||||
|
||||
info "Creating certificate record mc-local-test..."
|
||||
CREATE_RESP=$(api_post "/api/v1/certificates" '{
|
||||
"id": "mc-local-test",
|
||||
"name": "local-test-cert",
|
||||
"common_name": "local.certctl.test",
|
||||
"sans": ["local.certctl.test"],
|
||||
"issuer_id": "iss-local",
|
||||
"owner_id": "owner-test-admin",
|
||||
"team_id": "team-test-ops",
|
||||
"renewal_policy_id": "rp-default",
|
||||
"certificate_profile_id": "prof-test-tls",
|
||||
"environment": "development"
|
||||
}' 2>/dev/null || echo "ERROR")
|
||||
|
||||
if echo "$CREATE_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('id')=='mc-local-test'" 2>/dev/null; then
|
||||
pass "Certificate record created"
|
||||
else
|
||||
fail "Certificate creation failed" "$CREATE_RESP"
|
||||
fi
|
||||
|
||||
info "Linking certificate to NGINX target..."
|
||||
psql_exec "INSERT INTO certificate_target_mappings (certificate_id, target_id) VALUES ('mc-local-test', 'target-test-nginx') ON CONFLICT DO NOTHING;"
|
||||
pass "Target mapping inserted"
|
||||
|
||||
info "Triggering issuance..."
|
||||
RENEW_RESP=$(api_post "/api/v1/certificates/mc-local-test/renew" 2>/dev/null || echo "ERROR")
|
||||
if echo "$RENEW_RESP" | grep -q "renewal_triggered\|status"; then
|
||||
pass "Issuance triggered"
|
||||
else
|
||||
fail "Trigger failed" "$RENEW_RESP"
|
||||
fi
|
||||
|
||||
# Verify a job was created (this is the bug fix check)
|
||||
sleep 2
|
||||
JOB_COUNT=$(api_get "/api/v1/jobs" | python3 -c "
|
||||
import sys, json
|
||||
data = json.load(sys.stdin)
|
||||
jobs = [j for j in (data.get('data') or data.get('jobs') or []) if j.get('certificate_id') == 'mc-local-test']
|
||||
print(len(jobs))
|
||||
" 2>/dev/null || echo "0")
|
||||
|
||||
if [ "$JOB_COUNT" -gt 0 ]; then
|
||||
pass "Job created ($JOB_COUNT jobs for mc-local-test)"
|
||||
else
|
||||
fail "No jobs created — TriggerRenewalWithActor bug still present"
|
||||
fi
|
||||
|
||||
info "Waiting for issuance + deployment (up to 180s)..."
|
||||
if wait_for_jobs_done "mc-local-test" 180; then
|
||||
pass "All jobs completed"
|
||||
else
|
||||
fail "Jobs did not complete within 180s"
|
||||
echo " Current jobs:"
|
||||
api_get "/api/v1/jobs" 2>/dev/null | python3 -m json.tool 2>/dev/null | head -30
|
||||
fi
|
||||
|
||||
info "Reloading NGINX to pick up deployed certificate..."
|
||||
docker exec certctl-test-nginx nginx -s reload 2>/dev/null || true
|
||||
sleep 3
|
||||
|
||||
info "Verifying TLS certificate on NGINX..."
|
||||
TLS_CHECK=$(check_tls_identity "local.certctl.test")
|
||||
TLS_RESULT=$(echo "$TLS_CHECK" | head -1)
|
||||
if [ "$TLS_RESULT" = "MATCH" ]; then
|
||||
pass "NGINX serving cert for local.certctl.test"
|
||||
echo "$TLS_CHECK" | tail -n +2 | while read -r line; do echo -e " $line"; done
|
||||
else
|
||||
fail "NGINX not serving expected cert" "$(echo "$TLS_CHECK" | tail -n +2 | tr '\n' ', ')"
|
||||
fi
|
||||
|
||||
# Check cert status in API
|
||||
CERT_STATUS=$(api_get "/api/v1/certificates/mc-local-test" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null || echo "unknown")
|
||||
if [ "$CERT_STATUS" = "Active" ]; then
|
||||
pass "Certificate status: Active"
|
||||
else
|
||||
skip "Certificate status: $CERT_STATUS (expected Active — may need more time)"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 5: ACME (Pebble) Issuance
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 5: ACME (Pebble) Certificate Issuance"
|
||||
|
||||
info "Creating certificate record mc-acme-test..."
|
||||
CREATE_RESP=$(api_post "/api/v1/certificates" '{
|
||||
"id": "mc-acme-test",
|
||||
"name": "acme-test-cert",
|
||||
"common_name": "acme.certctl.test",
|
||||
"sans": ["acme.certctl.test"],
|
||||
"issuer_id": "iss-acme-staging",
|
||||
"owner_id": "owner-test-admin",
|
||||
"team_id": "team-test-ops",
|
||||
"renewal_policy_id": "rp-default",
|
||||
"certificate_profile_id": "prof-test-tls",
|
||||
"environment": "staging"
|
||||
}' 2>/dev/null || echo "ERROR")
|
||||
|
||||
if echo "$CREATE_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('id')=='mc-acme-test'" 2>/dev/null; then
|
||||
pass "Certificate record created"
|
||||
else
|
||||
fail "Certificate creation failed" "$CREATE_RESP"
|
||||
fi
|
||||
|
||||
info "Linking to target and triggering issuance..."
|
||||
psql_exec "INSERT INTO certificate_target_mappings (certificate_id, target_id) VALUES ('mc-acme-test', 'target-test-nginx') ON CONFLICT DO NOTHING;"
|
||||
RENEW_RESP=$(api_post "/api/v1/certificates/mc-acme-test/renew" 2>/dev/null || echo "ERROR")
|
||||
if echo "$RENEW_RESP" | grep -q "renewal_triggered\|status"; then
|
||||
pass "Issuance triggered"
|
||||
else
|
||||
fail "Trigger failed" "$RENEW_RESP"
|
||||
fi
|
||||
|
||||
info "Waiting for ACME issuance + deployment (up to 180s)..."
|
||||
if wait_for_jobs_done "mc-acme-test" 180; then
|
||||
pass "All jobs completed"
|
||||
|
||||
info "Reloading NGINX to pick up deployed certificate..."
|
||||
docker exec certctl-test-nginx nginx -s reload 2>/dev/null || true
|
||||
sleep 3
|
||||
|
||||
TLS_CHECK=$(check_tls_identity "acme.certctl.test")
|
||||
TLS_RESULT=$(echo "$TLS_CHECK" | head -1)
|
||||
if [ "$TLS_RESULT" = "MATCH" ]; then
|
||||
pass "NGINX serving cert for acme.certctl.test"
|
||||
echo "$TLS_CHECK" | tail -n +2 | while read -r line; do echo -e " $line"; done
|
||||
else
|
||||
fail "NGINX not serving expected ACME cert" "$(echo "$TLS_CHECK" | tail -n +2 | tr '\n' ', ')"
|
||||
fi
|
||||
else
|
||||
fail "ACME jobs did not complete within 180s"
|
||||
info "Checking ACME job status..."
|
||||
api_get "/api/v1/jobs" 2>/dev/null | python3 -c "
|
||||
import sys, json
|
||||
data = json.load(sys.stdin)
|
||||
for j in data.get('data', []):
|
||||
if j.get('certificate_id') == 'mc-acme-test':
|
||||
print(f\" Job {j['id']}: type={j['type']} status={j['status']} error={j.get('last_error','')}\")" 2>/dev/null || true
|
||||
echo " Server logs (last 20 lines):"
|
||||
docker logs certctl-test-server --tail 20 2>&1 | grep -i "acme\|error\|fail\|CSR" | head -10 || true
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 6: step-ca Issuance
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 6: step-ca (Private CA) Certificate Issuance"
|
||||
|
||||
info "Creating certificate record mc-stepca-test..."
|
||||
CREATE_RESP=$(api_post "/api/v1/certificates" '{
|
||||
"id": "mc-stepca-test",
|
||||
"name": "stepca-test-cert",
|
||||
"common_name": "stepca.certctl.test",
|
||||
"sans": ["stepca.certctl.test"],
|
||||
"issuer_id": "iss-stepca",
|
||||
"owner_id": "owner-test-admin",
|
||||
"team_id": "team-test-ops",
|
||||
"renewal_policy_id": "rp-default",
|
||||
"certificate_profile_id": "prof-test-tls",
|
||||
"environment": "staging"
|
||||
}' 2>/dev/null || echo "ERROR")
|
||||
|
||||
if echo "$CREATE_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('id')=='mc-stepca-test'" 2>/dev/null; then
|
||||
pass "Certificate record created"
|
||||
else
|
||||
fail "Certificate creation failed" "$CREATE_RESP"
|
||||
fi
|
||||
|
||||
info "Linking to target and triggering issuance..."
|
||||
psql_exec "INSERT INTO certificate_target_mappings (certificate_id, target_id) VALUES ('mc-stepca-test', 'target-test-nginx') ON CONFLICT DO NOTHING;"
|
||||
RENEW_RESP=$(api_post "/api/v1/certificates/mc-stepca-test/renew" 2>/dev/null || echo "ERROR")
|
||||
if echo "$RENEW_RESP" | grep -q "renewal_triggered\|status"; then
|
||||
pass "Issuance triggered"
|
||||
else
|
||||
fail "Trigger failed" "$RENEW_RESP"
|
||||
fi
|
||||
|
||||
info "Waiting for step-ca issuance + deployment (up to 120s)..."
|
||||
if wait_for_jobs_done "mc-stepca-test" 120; then
|
||||
pass "All jobs completed"
|
||||
else
|
||||
fail "Jobs did not complete in time"
|
||||
info "Checking step-ca job status..."
|
||||
api_get "/api/v1/jobs" 2>/dev/null | python3 -c "
|
||||
import sys, json
|
||||
data = json.load(sys.stdin)
|
||||
for j in data.get('data', []):
|
||||
if j.get('certificate_id') == 'mc-stepca-test':
|
||||
print(f\" Job {j['id']}: type={j['type']} status={j['status']} error={j.get('last_error','')}\")" 2>/dev/null || true
|
||||
echo " Server logs (step-ca related):"
|
||||
docker logs certctl-test-server --tail 30 2>&1 | grep -i "stepca\|step-ca\|provisioner\|jwe\|decrypt\|CSR.*fail\|error" | head -10 || true
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 7: Revocation
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 7: Revocation"
|
||||
|
||||
info "Revoking mc-local-test (reason: superseded)..."
|
||||
REVOKE_RESP=$(api_post "/api/v1/certificates/mc-local-test/revoke" '{"reason": "superseded"}' 2>/dev/null || echo "ERROR")
|
||||
if echo "$REVOKE_RESP" | grep -qi "revoked\|status"; then
|
||||
pass "Certificate revoked"
|
||||
else
|
||||
fail "Revocation failed" "$REVOKE_RESP"
|
||||
fi
|
||||
|
||||
info "Checking CRL..."
|
||||
CRL_RESP=$(api_get "/api/v1/crl" 2>/dev/null || echo '{"total":0}')
|
||||
CRL_TOTAL=$(echo "$CRL_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('total',0))" 2>/dev/null || echo 0)
|
||||
if [ "$CRL_TOTAL" -ge 1 ]; then
|
||||
pass "CRL contains $CRL_TOTAL revoked certificate(s)"
|
||||
else
|
||||
fail "CRL empty after revocation"
|
||||
fi
|
||||
|
||||
CERT_STATUS=$(api_get "/api/v1/certificates/mc-local-test" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null || echo "unknown")
|
||||
if [ "$CERT_STATUS" = "Revoked" ]; then
|
||||
pass "Certificate status updated to Revoked"
|
||||
else
|
||||
fail "Certificate status: $CERT_STATUS (expected Revoked)"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 8: Discovery
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 8: Certificate Discovery"
|
||||
|
||||
info "Checking discovered certificates..."
|
||||
DISC_RESP=$(api_get "/api/v1/discovered-certificates" 2>/dev/null || echo '{"total":0}')
|
||||
DISC_TOTAL=$(echo "$DISC_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('total',0))" 2>/dev/null || echo 0)
|
||||
if [ "$DISC_TOTAL" -ge 1 ]; then
|
||||
pass "Discovered $DISC_TOTAL certificate(s) on filesystem"
|
||||
else
|
||||
skip "No discovered certificates yet (agent scan may not have run)"
|
||||
fi
|
||||
|
||||
SUMMARY_RESP=$(api_get "/api/v1/discovery-summary" 2>/dev/null || echo '{}')
|
||||
echo -e " Discovery summary: $SUMMARY_RESP"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 9: Renewal (re-issue ACME cert)
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 9: Renewal"
|
||||
|
||||
# Try mc-stepca-test first (mc-local-test was revoked in Phase 7).
|
||||
# Fall back to mc-acme-test if step-ca cert isn't Active.
|
||||
RENEWAL_CERT=""
|
||||
for candidate in mc-stepca-test mc-acme-test; do
|
||||
STATUS=$(api_get "/api/v1/certificates/$candidate" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null || echo "unknown")
|
||||
if [ "$STATUS" = "Active" ]; then
|
||||
RENEWAL_CERT="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$RENEWAL_CERT" ]; then
|
||||
skip "Cannot test renewal — no certificate in Active state"
|
||||
else
|
||||
info "Using $RENEWAL_CERT for renewal test..."
|
||||
info "Triggering renewal on $RENEWAL_CERT..."
|
||||
RENEW_RESP=$(api_post "/api/v1/certificates/$RENEWAL_CERT/renew" 2>/dev/null || echo "ERROR")
|
||||
if echo "$RENEW_RESP" | grep -q "renewal_triggered\|status"; then
|
||||
pass "Renewal triggered"
|
||||
else
|
||||
skip "Renewal trigger returned: $RENEW_RESP"
|
||||
fi
|
||||
|
||||
info "Waiting for renewal to complete (up to 180s)..."
|
||||
if wait_for_jobs_done "$RENEWAL_CERT" 180; then
|
||||
pass "Renewal jobs completed"
|
||||
|
||||
info "Reloading NGINX to pick up renewed certificate..."
|
||||
docker exec certctl-test-nginx nginx -s reload 2>/dev/null || true
|
||||
sleep 3
|
||||
|
||||
# Verify version history shows multiple versions
|
||||
VERSIONS=$(api_get "/api/v1/certificates/$RENEWAL_CERT/versions" 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); print(len(d) if isinstance(d, list) else d.get('total', 0))" 2>/dev/null || echo 0)
|
||||
if [ "$VERSIONS" -ge 2 ]; then
|
||||
pass "Certificate has $VERSIONS versions (original + renewal)"
|
||||
else
|
||||
skip "Expected 2+ versions, got $VERSIONS"
|
||||
fi
|
||||
else
|
||||
skip "Renewal jobs did not complete within 180s"
|
||||
fi
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 10: EST Enrollment (RFC 7030)
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 10: EST Enrollment (RFC 7030)"
|
||||
|
||||
# Test cacerts endpoint — should return PKCS#7 with CA cert chain
|
||||
info "Testing EST cacerts endpoint..."
|
||||
EST_CACERTS_RESP=$(curl -sf -H "${AUTH_HEADER}" "${API_URL}/.well-known/est/cacerts" 2>/dev/null || echo "ERROR")
|
||||
if [ "$EST_CACERTS_RESP" != "ERROR" ] && [ -n "$EST_CACERTS_RESP" ]; then
|
||||
# Response should be base64-encoded PKCS#7
|
||||
if echo "$EST_CACERTS_RESP" | base64 -d >/dev/null 2>&1; then
|
||||
pass "EST cacerts returns valid base64 PKCS#7 response"
|
||||
else
|
||||
fail "EST cacerts returned non-base64 data"
|
||||
fi
|
||||
else
|
||||
fail "EST cacerts endpoint failed" "$EST_CACERTS_RESP"
|
||||
fi
|
||||
|
||||
# Test csrattrs endpoint
|
||||
info "Testing EST csrattrs endpoint..."
|
||||
EST_CSRATTRS_STATUS=$(curl -sf -o /dev/null -w "%{http_code}" -H "${AUTH_HEADER}" "${API_URL}/.well-known/est/csrattrs" 2>/dev/null || echo "000")
|
||||
if [ "$EST_CSRATTRS_STATUS" = "200" ] || [ "$EST_CSRATTRS_STATUS" = "204" ]; then
|
||||
pass "EST csrattrs returns $EST_CSRATTRS_STATUS"
|
||||
else
|
||||
fail "EST csrattrs returned $EST_CSRATTRS_STATUS (expected 200 or 204)"
|
||||
fi
|
||||
|
||||
# Test simpleenroll — generate CSR, POST as base64-encoded DER
|
||||
info "Testing EST simpleenroll with generated CSR..."
|
||||
EST_KEY_FILE=$(mktemp /tmp/est-key-XXXXXX.pem)
|
||||
EST_CSR_PEM_FILE=$(mktemp /tmp/est-csr-XXXXXX.pem)
|
||||
EST_CSR_DER_FILE=$(mktemp /tmp/est-csr-XXXXXX.der)
|
||||
trap "rm -f $EST_KEY_FILE $EST_CSR_PEM_FILE $EST_CSR_DER_FILE" EXIT
|
||||
|
||||
# Generate ECDSA key + CSR
|
||||
openssl ecparam -genkey -name prime256v1 -noout -out "$EST_KEY_FILE" 2>/dev/null
|
||||
openssl req -new -key "$EST_KEY_FILE" -out "$EST_CSR_PEM_FILE" -subj "/CN=est-device.certctl.test" 2>/dev/null
|
||||
openssl req -in "$EST_CSR_PEM_FILE" -out "$EST_CSR_DER_FILE" -outform DER 2>/dev/null
|
||||
|
||||
# base64-encode the DER CSR (EST wire format)
|
||||
EST_CSR_B64=$(base64 < "$EST_CSR_DER_FILE" | tr -d '\n')
|
||||
|
||||
EST_ENROLL_RESP=$(curl -sf \
|
||||
-X POST \
|
||||
-H "${AUTH_HEADER}" \
|
||||
-H "Content-Type: application/pkcs10" \
|
||||
-d "$EST_CSR_B64" \
|
||||
"${API_URL}/.well-known/est/simpleenroll" 2>/dev/null || echo "ERROR")
|
||||
|
||||
if [ "$EST_ENROLL_RESP" != "ERROR" ] && [ -n "$EST_ENROLL_RESP" ]; then
|
||||
# Response should be base64-encoded PKCS#7 containing the issued cert
|
||||
if echo "$EST_ENROLL_RESP" | base64 -d >/dev/null 2>&1; then
|
||||
pass "EST simpleenroll issued certificate via PKCS#7 response"
|
||||
else
|
||||
fail "EST simpleenroll returned non-base64 data"
|
||||
fi
|
||||
else
|
||||
fail "EST simpleenroll failed" "$(curl -s -X POST -H "${AUTH_HEADER}" -H "Content-Type: application/pkcs10" -d "$EST_CSR_B64" "${API_URL}/.well-known/est/simpleenroll" 2>&1 | head -5)"
|
||||
fi
|
||||
|
||||
# Test simplereenroll (should work identically)
|
||||
info "Testing EST simplereenroll..."
|
||||
EST_REENROLL_STATUS=$(curl -sf -o /dev/null -w "%{http_code}" \
|
||||
-X POST \
|
||||
-H "${AUTH_HEADER}" \
|
||||
-H "Content-Type: application/pkcs10" \
|
||||
-d "$EST_CSR_B64" \
|
||||
"${API_URL}/.well-known/est/simplereenroll" 2>/dev/null || echo "000")
|
||||
|
||||
if [ "$EST_REENROLL_STATUS" = "200" ]; then
|
||||
pass "EST simplereenroll works (status 200)"
|
||||
else
|
||||
fail "EST simplereenroll returned $EST_REENROLL_STATUS (expected 200)"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 11: S/MIME Certificate Issuance
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 11: S/MIME Certificate Issuance"
|
||||
|
||||
info "Creating S/MIME certificate record..."
|
||||
SMIME_RESP=$(api_post "/api/v1/certificates" '{
|
||||
"id": "mc-smime-test",
|
||||
"name": "smime-test-cert",
|
||||
"common_name": "testuser@certctl.test",
|
||||
"sans": ["testuser@certctl.test"],
|
||||
"issuer_id": "iss-local",
|
||||
"owner_id": "owner-test-admin",
|
||||
"team_id": "team-test-ops",
|
||||
"renewal_policy_id": "rp-default",
|
||||
"certificate_profile_id": "prof-test-smime",
|
||||
"environment": "staging"
|
||||
}' 2>/dev/null || echo "ERROR")
|
||||
|
||||
if echo "$SMIME_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('id')=='mc-smime-test'" 2>/dev/null; then
|
||||
pass "S/MIME certificate record created"
|
||||
else
|
||||
fail "S/MIME certificate creation failed" "$SMIME_RESP"
|
||||
fi
|
||||
|
||||
info "Linking S/MIME cert to target (needed for agent work routing)..."
|
||||
psql_exec "INSERT INTO certificate_target_mappings (certificate_id, target_id) VALUES ('mc-smime-test', 'target-test-nginx') ON CONFLICT DO NOTHING;"
|
||||
|
||||
info "Triggering S/MIME issuance..."
|
||||
SMIME_RENEW=$(api_post "/api/v1/certificates/mc-smime-test/renew" 2>/dev/null || echo "ERROR")
|
||||
if echo "$SMIME_RENEW" | grep -q "renewal_triggered\|status"; then
|
||||
pass "S/MIME issuance triggered"
|
||||
else
|
||||
fail "S/MIME trigger failed" "$SMIME_RENEW"
|
||||
fi
|
||||
|
||||
info "Waiting for S/MIME issuance (up to 120s)..."
|
||||
if wait_for_jobs_done "mc-smime-test" 120; then
|
||||
pass "S/MIME jobs completed"
|
||||
|
||||
# Fetch the issued cert and verify EKU
|
||||
info "Verifying S/MIME certificate EKU..."
|
||||
SMIME_VERSIONS=$(api_get "/api/v1/certificates/mc-smime-test/versions" 2>/dev/null || echo "[]")
|
||||
SMIME_PEM=$(echo "$SMIME_VERSIONS" | python3 -c "
|
||||
import sys, json
|
||||
data = json.load(sys.stdin)
|
||||
versions = data if isinstance(data, list) else data.get('data', [])
|
||||
if versions:
|
||||
print(versions[-1].get('pem_chain', versions[-1].get('pem', '')))
|
||||
" 2>/dev/null || echo "")
|
||||
|
||||
if [ -n "$SMIME_PEM" ]; then
|
||||
# Parse the cert and check for emailProtection EKU
|
||||
SMIME_EKU=$(echo "$SMIME_PEM" | openssl x509 -noout -text 2>/dev/null | grep -A2 "Extended Key Usage" || echo "")
|
||||
if echo "$SMIME_EKU" | grep -qi "emailProtection\|E-mail Protection"; then
|
||||
pass "S/MIME cert has emailProtection EKU"
|
||||
else
|
||||
fail "S/MIME cert missing emailProtection EKU" "Got: $SMIME_EKU"
|
||||
fi
|
||||
|
||||
# Check KeyUsage flags (S/MIME should have Digital Signature + Content Commitment)
|
||||
SMIME_KU=$(echo "$SMIME_PEM" | openssl x509 -noout -text 2>/dev/null | awk '/X509v3 Key Usage:/{getline; print; exit}')
|
||||
if echo "$SMIME_KU" | grep -qi "Digital Signature"; then
|
||||
pass "S/MIME cert has Digital Signature KeyUsage"
|
||||
else
|
||||
fail "S/MIME cert missing Digital Signature KeyUsage" "Got: $SMIME_KU"
|
||||
fi
|
||||
|
||||
# Check that email SAN is present
|
||||
SMIME_SAN=$(echo "$SMIME_PEM" | openssl x509 -noout -ext subjectAltName 2>/dev/null || echo "")
|
||||
if echo "$SMIME_SAN" | grep -qi "email:testuser@certctl.test"; then
|
||||
pass "S/MIME cert has email SAN"
|
||||
else
|
||||
# Some implementations use rfc822Name instead of email:
|
||||
if echo "$SMIME_SAN" | grep -qi "testuser@certctl.test"; then
|
||||
pass "S/MIME cert has email SAN (rfc822Name)"
|
||||
else
|
||||
skip "S/MIME email SAN not found in cert (may be in CN only)"
|
||||
echo " SAN content: $SMIME_SAN"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
skip "Could not extract S/MIME cert PEM for EKU verification"
|
||||
fi
|
||||
else
|
||||
fail "S/MIME issuance did not complete within 120s"
|
||||
info "Checking S/MIME job status..."
|
||||
api_get "/api/v1/jobs" 2>/dev/null | python3 -c "
|
||||
import sys, json
|
||||
data = json.load(sys.stdin)
|
||||
for j in data.get('data', []):
|
||||
if j.get('certificate_id') == 'mc-smime-test':
|
||||
print(f\" Job {j['id']}: type={j['type']} status={j['status']} error={j.get('last_error','')}\")" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PHASE 12: API Spot Checks
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Phase 12: API Spot Checks"
|
||||
|
||||
# Health
|
||||
if api_get "/health" >/dev/null 2>&1; then
|
||||
pass "GET /health returns 200"
|
||||
else
|
||||
fail "GET /health failed"
|
||||
fi
|
||||
|
||||
# Metrics
|
||||
METRICS_RESP=$(api_get "/api/v1/metrics" 2>/dev/null || echo "ERROR")
|
||||
if echo "$METRICS_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); assert 'gauge' in d" 2>/dev/null; then
|
||||
pass "GET /api/v1/metrics returns valid JSON"
|
||||
else
|
||||
fail "Metrics endpoint broken"
|
||||
fi
|
||||
|
||||
# Stats summary
|
||||
STATS_RESP=$(api_get "/api/v1/stats/summary" 2>/dev/null || echo "ERROR")
|
||||
if echo "$STATS_RESP" | python3 -c "import sys,json; json.load(sys.stdin)" 2>/dev/null; then
|
||||
pass "GET /api/v1/stats/summary returns valid JSON"
|
||||
else
|
||||
fail "Stats summary endpoint broken"
|
||||
fi
|
||||
|
||||
# Audit trail
|
||||
AUDIT_RESP=$(api_get "/api/v1/audit" 2>/dev/null || echo '{"total":0}')
|
||||
AUDIT_TOTAL=$(echo "$AUDIT_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('total',0))" 2>/dev/null || echo 0)
|
||||
if [ "$AUDIT_TOTAL" -gt 0 ]; then
|
||||
pass "Audit trail: $AUDIT_TOTAL events recorded"
|
||||
else
|
||||
fail "Audit trail empty"
|
||||
fi
|
||||
|
||||
# Jobs summary
|
||||
JOBS_RESP=$(api_get "/api/v1/jobs" 2>/dev/null || echo '{"total":0}')
|
||||
JOBS_TOTAL=$(echo "$JOBS_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('total',0))" 2>/dev/null || echo 0)
|
||||
pass "Total jobs created: $JOBS_TOTAL"
|
||||
|
||||
# Prometheus
|
||||
PROM_RESP=$(curl -sf -H "${AUTH_HEADER}" "${API_URL}/api/v1/metrics/prometheus" 2>/dev/null || echo "")
|
||||
if echo "$PROM_RESP" | grep -q "certctl_certificate_total"; then
|
||||
pass "Prometheus metrics endpoint working"
|
||||
else
|
||||
fail "Prometheus metrics endpoint broken"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Summary
|
||||
# ---------------------------------------------------------------------------
|
||||
header "Test Summary"
|
||||
|
||||
TOTAL=$((PASS + FAIL + SKIP))
|
||||
echo ""
|
||||
echo -e " ${GREEN}Passed: $PASS${NC}"
|
||||
echo -e " ${RED}Failed: $FAIL${NC}"
|
||||
echo -e " ${YELLOW}Skipped: $SKIP${NC}"
|
||||
echo -e " Total: $TOTAL"
|
||||
echo ""
|
||||
|
||||
if [ "$FAIL" -eq 0 ]; then
|
||||
echo -e "${GREEN}${BOLD}All tests passed.${NC}"
|
||||
exit 0
|
||||
else
|
||||
echo -e "${RED}${BOLD}$FAIL test(s) failed.${NC}"
|
||||
echo ""
|
||||
echo "Useful debug commands:"
|
||||
echo " docker logs certctl-test-server --tail 50"
|
||||
echo " docker logs certctl-test-agent --tail 50"
|
||||
echo " docker compose -f $COMPOSE_FILE ps"
|
||||
exit 1
|
||||
fi
|
||||
Executable
+140
@@ -0,0 +1,140 @@
|
||||
#!/bin/sh
|
||||
# This script runs inside the certctl-server container at startup.
|
||||
# It fetches CA certificates from Pebble and step-ca, adds them to the
|
||||
# system trust store, then starts the certctl server.
|
||||
#
|
||||
# Why: The ACME connector and step-ca connector use Go's default http.Client
|
||||
# with no InsecureSkipVerify. They rely on the system trust store to verify
|
||||
# TLS connections. Pebble and step-ca both use self-signed root CAs that
|
||||
# aren't in Alpine's default CA bundle, so we must add them manually.
|
||||
#
|
||||
# This script runs as root (user: "0:0" in docker-compose) so that
|
||||
# update-ca-certificates can write to /etc/ssl/certs/.
|
||||
|
||||
set -e
|
||||
|
||||
echo "=== certctl trust store setup ==="
|
||||
|
||||
# --- Pebble CA cert (fetched from management API) ---
|
||||
# Pebble's management API serves the root CA at /roots/0.
|
||||
# We use -k because we can't verify Pebble's TLS cert yet (chicken-and-egg).
|
||||
echo "Fetching Pebble root CA from management API..."
|
||||
PEBBLE_CA=""
|
||||
for i in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if PEBBLE_CA=$(curl -sk https://pebble:15000/roots/0 2>/dev/null); then
|
||||
if [ -n "$PEBBLE_CA" ]; then
|
||||
echo "$PEBBLE_CA" > /usr/local/share/ca-certificates/pebble-ca.crt
|
||||
echo " Added: Pebble test CA"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
echo " Waiting for Pebble (attempt $i/10)..."
|
||||
sleep 2
|
||||
done
|
||||
|
||||
if [ -z "$PEBBLE_CA" ]; then
|
||||
echo " WARNING: Could not fetch Pebble CA. ACME issuance will fail."
|
||||
fi
|
||||
|
||||
# --- step-ca root cert (from shared volume) ---
|
||||
# The step-ca container writes its root CA to /home/step/certs/root_ca.crt.
|
||||
# We mount the step-ca data volume at /stepca-data inside this container.
|
||||
STEPCA_ROOT="/stepca-data/certs/root_ca.crt"
|
||||
echo "Waiting for step-ca root cert..."
|
||||
for i in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if [ -f "$STEPCA_ROOT" ]; then
|
||||
cp "$STEPCA_ROOT" /usr/local/share/ca-certificates/step-ca-root.crt
|
||||
echo " Added: step-ca root CA"
|
||||
break
|
||||
fi
|
||||
echo " Waiting for step-ca root cert (attempt $i/10)..."
|
||||
sleep 2
|
||||
done
|
||||
|
||||
if [ ! -f "$STEPCA_ROOT" ]; then
|
||||
echo " WARNING: step-ca root cert not found at $STEPCA_ROOT"
|
||||
echo " step-ca issuance may fail until the cert is available."
|
||||
fi
|
||||
|
||||
# --- step-ca provisioner key (extracted from ca.json) ---
|
||||
# When step-ca auto-bootstraps via DOCKER_STEPCA_INIT_* env vars, the
|
||||
# encrypted provisioner key (JWE) is NOT written as a separate file.
|
||||
# Instead, it's embedded in ca.json under:
|
||||
# authority.provisioners[0].encryptedKey
|
||||
# We extract it here and write to /tmp so the certctl server can read it.
|
||||
# The stepca_data volume is mounted :ro, so we can't write there.
|
||||
STEPCA_CA_JSON="/stepca-data/config/ca.json"
|
||||
STEPCA_KEY_EXTRACTED="/tmp/step-ca-provisioner-key"
|
||||
echo "Extracting step-ca provisioner key from ca.json..."
|
||||
for i in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if [ -f "$STEPCA_CA_JSON" ]; then
|
||||
# Extract the encryptedKey value using grep+sed (no jq in Alpine base)
|
||||
# The field looks like: "encryptedKey": "eyJhbGciOi..."
|
||||
ENCRYPTED_KEY=$(grep -o '"encryptedKey":"[^"]*"' "$STEPCA_CA_JSON" | head -1 | sed 's/"encryptedKey":"//;s/"$//')
|
||||
if [ -z "$ENCRYPTED_KEY" ]; then
|
||||
# Try with spaces around colon (JSON formatting varies)
|
||||
ENCRYPTED_KEY=$(grep -o '"encryptedKey" *: *"[^"]*"' "$STEPCA_CA_JSON" | head -1 | sed 's/"encryptedKey" *: *"//;s/"$//')
|
||||
fi
|
||||
if [ -n "$ENCRYPTED_KEY" ]; then
|
||||
# Check if it's JWE compact serialization (dot-separated) or JSON serialization
|
||||
case "$ENCRYPTED_KEY" in
|
||||
\{*)
|
||||
# Already JSON serialization — write as-is
|
||||
echo "$ENCRYPTED_KEY" > "$STEPCA_KEY_EXTRACTED"
|
||||
;;
|
||||
*)
|
||||
# JWE compact serialization: header.encrypted_key.iv.ciphertext.tag
|
||||
# Convert to JSON serialization expected by Go decryptProvisionerKey()
|
||||
JWE_PROTECTED=$(echo "$ENCRYPTED_KEY" | cut -d. -f1)
|
||||
JWE_ENCKEY=$(echo "$ENCRYPTED_KEY" | cut -d. -f2)
|
||||
JWE_IV=$(echo "$ENCRYPTED_KEY" | cut -d. -f3)
|
||||
JWE_CT=$(echo "$ENCRYPTED_KEY" | cut -d. -f4)
|
||||
JWE_TAG=$(echo "$ENCRYPTED_KEY" | cut -d. -f5)
|
||||
printf '{"protected":"%s","encrypted_key":"%s","iv":"%s","ciphertext":"%s","tag":"%s"}' \
|
||||
"$JWE_PROTECTED" "$JWE_ENCKEY" "$JWE_IV" "$JWE_CT" "$JWE_TAG" > "$STEPCA_KEY_EXTRACTED"
|
||||
;;
|
||||
esac
|
||||
echo " Extracted provisioner key to $STEPCA_KEY_EXTRACTED"
|
||||
echo " Key file size: $(wc -c < "$STEPCA_KEY_EXTRACTED") bytes"
|
||||
echo " Key starts with: $(head -c 40 "$STEPCA_KEY_EXTRACTED")..."
|
||||
# Override the env var so the server reads from the extracted file
|
||||
export CERTCTL_STEPCA_KEY_PATH="$STEPCA_KEY_EXTRACTED"
|
||||
break
|
||||
else
|
||||
echo " ca.json found but encryptedKey not found in it (attempt $i/10)"
|
||||
fi
|
||||
else
|
||||
echo " Waiting for step-ca ca.json (attempt $i/10)..."
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
|
||||
if [ ! -f "$STEPCA_KEY_EXTRACTED" ]; then
|
||||
echo " WARNING: Could not extract step-ca provisioner key"
|
||||
echo " Listing /stepca-data/config/ for debugging:"
|
||||
ls -la /stepca-data/config/ 2>/dev/null || echo " /stepca-data/config/ does not exist"
|
||||
echo " step-ca issuance will fail."
|
||||
fi
|
||||
|
||||
# --- Update system trust store ---
|
||||
echo "Updating system CA trust store..."
|
||||
update-ca-certificates 2>/dev/null || true
|
||||
|
||||
echo "Trust store updated."
|
||||
|
||||
# --- Debug: verify configuration before starting server ---
|
||||
echo "=== Pre-launch verification ==="
|
||||
echo " CERTCTL_STEPCA_KEY_PATH=$CERTCTL_STEPCA_KEY_PATH"
|
||||
if [ -f "$CERTCTL_STEPCA_KEY_PATH" ]; then
|
||||
echo " step-ca key file exists ($(wc -c < "$CERTCTL_STEPCA_KEY_PATH") bytes)"
|
||||
echo " step-ca key preview: $(head -c 60 "$CERTCTL_STEPCA_KEY_PATH")..."
|
||||
else
|
||||
echo " WARNING: step-ca key file NOT FOUND at $CERTCTL_STEPCA_KEY_PATH"
|
||||
fi
|
||||
echo " CERTCTL_ACME_DIRECTORY_URL=$CERTCTL_ACME_DIRECTORY_URL"
|
||||
echo " CERTCTL_ACME_INSECURE=$CERTCTL_ACME_INSECURE"
|
||||
echo " Pebble CA cert: $(ls -la /usr/local/share/ca-certificates/pebble-ca.crt 2>/dev/null || echo 'NOT FOUND')"
|
||||
echo " step-ca root cert: $(ls -la /usr/local/share/ca-certificates/step-ca-root.crt 2>/dev/null || echo 'NOT FOUND')"
|
||||
echo " System CA count: $(ls /etc/ssl/certs/*.pem 2>/dev/null | wc -l) PEM files"
|
||||
echo "=== Starting certctl server ==="
|
||||
exec /app/server
|
||||
+65
-31
@@ -45,7 +45,7 @@ New to certificates? Read the [Concepts Guide](concepts.md) first.
|
||||
### Design Principles
|
||||
|
||||
1. **Private Key Isolation** — Agents generate ECDSA P-256 keys locally and submit CSRs only. Private keys never touch the control plane. Server-side keygen available via `CERTCTL_KEYGEN_MODE=server` for demo only.
|
||||
2. **Pull-Only Deployment** — The server never initiates outbound connections to agents or targets. Agents poll for work. For network appliances and agentless targets, a proxy agent in the same network zone executes deployments via the target's API. This keeps the control plane firewalled off and limits credential scope to the proxy agent's zone.
|
||||
2. **Pull-Only Deployment** — The server never initiates outbound connections to agents or targets. Agents poll for work and receive only jobs assigned to their targets (routed via `agent_id` on jobs or through target→agent relationships). For network appliances and agentless targets, a proxy agent in the same network zone executes deployments via the target's API. This keeps the control plane firewalled off and limits credential scope to the proxy agent's zone.
|
||||
3. **Sub-CA Capable** — The Local CA can operate as a subordinate CA under an enterprise root (e.g., ADCS). Load a pre-signed CA cert+key from disk and all issued certs chain to the enterprise trust hierarchy. Self-signed mode remains the default for development/demos.
|
||||
4. **GUI as Primary Interface** — The web dashboard is the operational control plane, not a secondary viewer. Every backend feature ships with its corresponding GUI surface.
|
||||
5. **Decoupled Operations** — Agents operate autonomously; the control plane coordinates but doesn't block agent function
|
||||
@@ -61,7 +61,7 @@ flowchart TB
|
||||
API["REST API\n(Go net/http, :8443)"]
|
||||
SVC["Service Layer"]
|
||||
REPO["Repository Layer\n(database/sql + lib/pq)"]
|
||||
SCHED["Background Scheduler\n6 loops"]
|
||||
SCHED["Background Scheduler\n7 loops"]
|
||||
DASH["Web Dashboard\n(React SPA)"]
|
||||
end
|
||||
|
||||
@@ -80,15 +80,20 @@ flowchart TB
|
||||
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)"]
|
||||
CA6["Vault PKI\n(token auth, /sign API)"]
|
||||
CA7["DigiCert CertCentral\n(async order model)"]
|
||||
end
|
||||
|
||||
subgraph "Target Systems"
|
||||
T1["NGINX\n(file write + reload)"]
|
||||
T4["Apache httpd\n(file write + reload)"]
|
||||
T5["HAProxy\n(combined PEM + reload)"]
|
||||
T2["F5 BIG-IP\n(proxy agent + iControl REST, planned)"]
|
||||
T3["IIS\n(agent-local PowerShell, planned)"]
|
||||
T6["Traefik\n(file provider)"]
|
||||
T7["Caddy\n(admin API / file)"]
|
||||
T8["Envoy\n(file-based SDS)"]
|
||||
T9["Postfix/Dovecot\n(file + service reload)"]
|
||||
T2["F5 BIG-IP\n(proxy agent + iControl REST)"]
|
||||
T3["IIS\n(WinRM + local)"]
|
||||
end
|
||||
|
||||
DASH --> API
|
||||
@@ -96,7 +101,7 @@ flowchart TB
|
||||
SVC --> REPO
|
||||
REPO --> PG
|
||||
SCHED --> SVC
|
||||
SVC -->|"Issue/Renew"| CA1 & CA2 & CA3
|
||||
SVC -->|"Issue/Renew"| CA1 & CA2 & CA3 & CA4 & CA6 & CA7
|
||||
|
||||
A1 & A2 & A3 -->|"CSR + Heartbeat"| API
|
||||
API -->|"Cert + Chain\n(NO private key)"| A1 & A2 & A3
|
||||
@@ -116,7 +121,7 @@ The server exposes a REST API under `/api/v1/` and optionally serves the web das
|
||||
|
||||
### Agents
|
||||
|
||||
Lightweight Go processes that run on or near your infrastructure. Agents generate ECDSA P-256 private keys locally, create CSRs, and submit them to the control plane for signing — private keys never leave agent infrastructure. Agents also handle certificate deployment to target systems (NGINX, Apache httpd, HAProxy fully implemented; F5 BIG-IP, IIS interface only with V2 implementations planned) and report job status. They communicate with the control plane via HTTP and authenticate with API keys.
|
||||
Lightweight Go processes that run on or near your infrastructure. Agents generate ECDSA P-256 private keys locally, create CSRs, and submit them to the control plane for signing — private keys never leave agent infrastructure. Agents also handle certificate deployment to target systems (NGINX, Apache httpd, HAProxy, Traefik, Caddy, Envoy, Postfix, Dovecot, IIS fully implemented; F5 BIG-IP interface stub only) and report job status. They communicate with the control plane via HTTP and authenticate with API keys.
|
||||
|
||||
The agent runs two background loops: a heartbeat (every 60 seconds) to signal it's alive, and a work poll (every 30 seconds) to check for actionable jobs via `GET /api/v1/agents/{id}/work`. Jobs may be `AwaitingCSR` (agent needs to generate key + submit CSR) or `Deployment` (agent needs to deploy a certificate). Private keys are stored in `CERTCTL_KEY_DIR` (default `/var/lib/certctl/keys`) with 0600 permissions.
|
||||
|
||||
@@ -413,8 +418,8 @@ The agent deploys certificates using target connectors. Each connector knows how
|
||||
- **NGINX**: Writes cert/chain/key files to disk, validates config with `nginx -t`, reloads with `nginx -s reload` or `systemctl reload nginx`
|
||||
- **Apache httpd**: Writes separate cert/chain/key files, validates with `apachectl configtest`, graceful reload
|
||||
- **HAProxy**: Builds a combined PEM file (cert + chain + key), optionally validates config, reloads via systemctl or signal
|
||||
- **F5 BIG-IP** (planned): A proxy agent in the same network zone calls the iControl REST API to upload certificate and update SSL profile bindings. The server assigns the work; the proxy agent executes it.
|
||||
- **IIS** (planned, dual-mode): (1) Agent-local (recommended) — a Windows agent on the IIS box runs PowerShell `Import-PfxCertificate` + `Set-WebBinding` directly. (2) Proxy agent WinRM — for agentless IIS targets, a nearby Windows agent reaches the IIS box via WinRM.
|
||||
- **F5 BIG-IP**: A proxy agent in the same network zone calls the iControl REST API to upload certificate/key files, install crypto objects, and update the SSL client profile within an atomic transaction. The server assigns the work; the proxy agent executes it.
|
||||
- **IIS** (implemented, dual-mode): (1) Agent-local (recommended) — a Windows agent on the IIS box runs PowerShell `Import-PfxCertificate` + `Set-WebBinding` directly with PFX conversion and SHA-1 thumbprint computation. (2) Proxy agent WinRM — for agentless IIS targets, a nearby Windows agent reaches the IIS box via WinRM.
|
||||
|
||||
The agent handles both the certificate (public) and the private key (read from local key store at `CERTCTL_KEY_DIR`). The control plane never sees the private key and never initiates outbound connections to agents or targets (pull-only model).
|
||||
|
||||
@@ -450,7 +455,7 @@ Short-lived certificates (those with profile TTL < 1 hour) return "good" from OC
|
||||
|
||||
### 4. Automatic Renewal
|
||||
|
||||
The control plane runs a scheduler with six background loops:
|
||||
The control plane runs a scheduler with seven background loops:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
@@ -461,6 +466,7 @@ flowchart LR
|
||||
N["Notification Processor\n⏱ every 1m"]
|
||||
SL["Short-Lived Expiry\n⏱ every 30s"]
|
||||
NS["Network Scanner\n⏱ every 6h"]
|
||||
DG["Certificate Digest\n⏱ every 24h"]
|
||||
end
|
||||
|
||||
R -->|"Find expiring certs\nCreate renewal jobs"| DB[("PostgreSQL")]
|
||||
@@ -469,6 +475,7 @@ flowchart LR
|
||||
N -->|"Send pending notifications\nEmail / Webhook / Slack"| DB
|
||||
SL -->|"Expire short-lived certs\nMark as Expired"| DB
|
||||
NS -->|"Probe TLS endpoints\nStore discovered certs"| DB
|
||||
DG -->|"Generate & send HTML digest\nEmail to recipients"| DB
|
||||
```
|
||||
|
||||
| Loop | Interval | Timeout | Purpose |
|
||||
@@ -479,8 +486,9 @@ flowchart LR
|
||||
| Notification processor | 1 minute | 1 minute | Sends pending notifications via configured channels |
|
||||
| Short-lived expiry | 30 seconds | 30 seconds | Marks expired short-lived certificates (profile TTL < 1 hour) |
|
||||
| Network scanner | 6 hours | 30 minutes | Probes TLS endpoints on configured CIDR ranges, stores discovered certs (M21, opt-in via `CERTCTL_NETWORK_SCAN_ENABLED`). CIDR size validated at API level — max /20 (4096 IPs) per range. |
|
||||
| Certificate digest | 24 hours | 5 minutes | Generates HTML email with certificate stats, expiration timeline, job health, agent count. Does NOT run on startup — waits for first scheduled tick. Configurable interval and recipients via `CERTCTL_DIGEST_INTERVAL` and `CERTCTL_DIGEST_RECIPIENTS`. Falls back to certificate owner emails if no explicit recipients configured. |
|
||||
|
||||
Each loop uses `sync/atomic.Bool` idempotency guards to prevent concurrent tick execution — if a loop iteration is still running when the next tick fires, the tick is skipped with a warning log. All loops (including short-lived expiry check) run immediately on startup before entering their ticker interval, ensuring no gap between scheduler start and first execution. Graceful shutdown uses `sync.WaitGroup` with `WaitForCompletion()` to drain all in-flight work before process exit.
|
||||
Each loop uses `sync/atomic.Bool` idempotency guards to prevent concurrent tick execution — if a loop iteration is still running when the next tick fires, the tick is skipped with a warning log. All loops (including short-lived expiry check) run immediately on startup before entering their ticker interval, ensuring no gap between scheduler start and first execution. The certificate digest loop is the exception — it does NOT run on startup, only on scheduled ticks. Graceful shutdown uses `sync.WaitGroup` with `WaitForCompletion()` to drain all in-flight work before process exit.
|
||||
|
||||
Each operation has a context timeout to prevent indefinite hangs if external services become unresponsive.
|
||||
|
||||
@@ -503,7 +511,10 @@ flowchart TB
|
||||
II --> ACME["ACME v2"]
|
||||
II --> SC["step-ca"]
|
||||
II --> OC["OpenSSL / Custom CA"]
|
||||
II --> VP["Vault PKI (planned)"]
|
||||
II --> VP["Vault PKI"]
|
||||
II --> DC["DigiCert CertCentral"]
|
||||
II --> SG["Sectigo SCM"]
|
||||
II --> GC["Google CAS"]
|
||||
end
|
||||
|
||||
subgraph "Target Connectors"
|
||||
@@ -514,8 +525,10 @@ flowchart TB
|
||||
TI --> HP["HAProxy"]
|
||||
TI --> TF["Traefik"]
|
||||
TI --> CD["Caddy"]
|
||||
TI --> F5["F5 BIG-IP (interface only)"]
|
||||
TI --> IIS["IIS (interface only)"]
|
||||
TI --> EV["Envoy"]
|
||||
TI --> PO["Postfix/Dovecot"]
|
||||
TI --> IIS["IIS"]
|
||||
TI --> F5["F5 BIG-IP"]
|
||||
end
|
||||
|
||||
subgraph "Notifier Connectors"
|
||||
@@ -567,7 +580,11 @@ type Connector interface {
|
||||
}
|
||||
```
|
||||
|
||||
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).
|
||||
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), **OpenSSL/Custom CA** (script-based signing delegating to user-provided shell scripts), **Vault PKI** (HashiCorp Vault's PKI secrets engine via /sign API with token auth), and **DigiCert** (commercial CA via CertCentral REST API with async order processing). 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.
|
||||
|
||||
**ACME Renewal Information (ARI, RFC 9702):** The ACME connector supports CA-directed renewal timing via the `GetRenewalInfo()` method. Instead of using fixed thresholds (e.g., renew 30 days before expiry), the CA tells certctl when to renew by providing a `suggestedWindow` with start and end times. This is useful for distributing renewal load during maintenance windows and coordinating mass-revocation scenarios. Enable with `CERTCTL_ACME_ARI_ENABLED=true`. Cert ID is computed as `base64url(SHA-256(DER cert))` per RFC 9702. If the CA doesn't support ARI (404 from the ARI endpoint), certctl automatically falls back to threshold-based renewal — no operator intervention required. Errors from the CA are logged as warnings.
|
||||
|
||||
The interface also includes `GetCACertPEM(ctx)` for CA chain distribution (used by the EST server's `/cacerts` endpoint).
|
||||
|
||||
### Target Connector
|
||||
|
||||
@@ -640,7 +657,7 @@ type ESTService interface {
|
||||
}
|
||||
```
|
||||
|
||||
**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).
|
||||
**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, OpenSSL, Vault, and DigiCert 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.
|
||||
|
||||
@@ -744,7 +761,7 @@ The HTTP middleware stack processes requests in the following order (see `cmd/se
|
||||
|
||||
### Concurrency Safety
|
||||
|
||||
The background scheduler uses `sync/atomic.Bool` idempotency guards on all 6 loops — if a tick fires while the previous iteration is still running, it skips. A `sync.WaitGroup` tracks all in-flight goroutines. `WaitForCompletion(timeout)` blocks during shutdown until all work finishes or the timeout expires, preventing state corruption from mid-flight database operations during process exit.
|
||||
The background scheduler uses `sync/atomic.Bool` idempotency guards on all 7 loops — if a tick fires while the previous iteration is still running, it skips. A `sync.WaitGroup` tracks all in-flight goroutines. `WaitForCompletion(timeout)` blocks during shutdown until all work finishes or the timeout expires, preventing state corruption from mid-flight database operations during process exit.
|
||||
|
||||
### Logging
|
||||
|
||||
@@ -763,7 +780,7 @@ All endpoints are under `/api/v1/` and follow consistent patterns:
|
||||
|
||||
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 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.
|
||||
The full API is documented in an OpenAPI 3.1 specification at `api/openapi.yaml` with 99 endpoints across 23 resource domains (97 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, 4 EST enrollment endpoints from M23, 2 digest endpoints from M29), 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`.
|
||||
|
||||
@@ -778,6 +795,8 @@ Jobs support additional action endpoints: `POST /api/v1/jobs/{id}/cancel`, `POST
|
||||
|
||||
Certificate revocation: `POST /api/v1/certificates/{id}/revoke` with optional `{"reason": "keyCompromise"}`. Supports RFC 5280 reason codes (unspecified, keyCompromise, caCompromise, affiliationChanged, superseded, cessationOfOperation, certificateHold, privilegeWithdrawn). Returns the updated certificate status. Best-effort issuer notification — the revocation succeeds even if the issuer connector is unavailable. A JSON-formatted CRL is available at `GET /api/v1/crl`, and a DER-encoded X.509 CRL signed by the issuing CA at `GET /api/v1/crl/{issuer_id}`. An embedded OCSP responder serves signed responses at `GET /api/v1/ocsp/{issuer_id}/{serial}`. Short-lived certificates (profile TTL < 1 hour) are exempt from CRL/OCSP — expiry is sufficient revocation.
|
||||
|
||||
Certificate export (M27): `GET /api/v1/certificates/{id}/export/pem` returns PEM-encoded certificate and chain, and `POST /api/v1/certificates/{id}/export/pkcs12` returns a PKCS#12 bundle (binary). Private keys are never exported — they remain on agents. All exports are audited with actor, timestamp, and format.
|
||||
|
||||
Health checks live outside the API prefix: `GET /health` and `GET /ready`.
|
||||
|
||||
## MCP Server
|
||||
@@ -833,7 +852,9 @@ flowchart TB
|
||||
**Credentials & Configuration:**
|
||||
Database and API credentials are managed via environment variables defined in a `.env` file. Copy `deploy/.env.example` to `deploy/.env` for local development and customize credentials for production. The agent key directory (`CERTCTL_KEY_DIR`) is persisted as a named Docker volume (`agent_keys`) at `/var/lib/certctl/keys` for reliable key storage across container restarts.
|
||||
|
||||
### Production (Kubernetes)
|
||||
### Production (Kubernetes with Helm)
|
||||
|
||||
A production-ready Helm chart is available under `deploy/helm/certctl/` with full support for multi-replica deployments, persistent PostgreSQL, agent DaemonSet, optional Ingress, and security best practices.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
@@ -859,6 +880,21 @@ flowchart TB
|
||||
DS --> DEP
|
||||
```
|
||||
|
||||
**Helm Installation:**
|
||||
|
||||
```bash
|
||||
# Add the chart (if published) or install from local directory
|
||||
helm install certctl deploy/helm/certctl/ \
|
||||
--set server.auth.apiKey="your-secure-key" \
|
||||
--set postgresql.auth.password="your-db-password" \
|
||||
--set ingress.enabled=true \
|
||||
--set ingress.hosts[0].host="certctl.example.com"
|
||||
```
|
||||
|
||||
The Helm chart includes: server Deployment with configurable replicas, liveness/readiness probes, security context (non-root, read-only rootfs), PostgreSQL StatefulSet with persistent volumes, optional Ingress with TLS, ServiceAccount with configurable RBAC, and agent DaemonSet running one agent per node. All certctl configuration options are exposed in `values.yaml` — issuers, targets, notifiers, scheduler intervals, discovery settings, and SMTP for digest emails.
|
||||
|
||||
See `deploy/helm/certctl/values.yaml` for the full configuration reference and `deploy/helm/certctl/Chart.yaml` for version and appVersion details.
|
||||
|
||||
For production, you would also add an ingress controller, TLS termination for the certctl API itself, and external PostgreSQL (RDS, Cloud SQL, etc.).
|
||||
|
||||
## Discovery Data Flow (M18b + M21)
|
||||
@@ -928,27 +964,25 @@ This data flow is pull-based and non-blocking. Agents discover at their own pace
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
certctl uses a layered testing approach aligned with the handler → service → repository architecture, with 1050+ tests across six layers (service, handler, integration, connector, frontend, and scheduler). The goal is high-confidence regression prevention at the service and handler layers, where the most complex business logic lives, combined with integration tests that exercise the full request path from HTTP to database.
|
||||
certctl is extensively tested across eight layers with CI-enforced coverage gates that act as regression floors. The goal is high-confidence regression prevention at the service and handler layers (where the most complex business logic lives), combined with integration tests that exercise the full request path from HTTP to database.
|
||||
|
||||
**Service layer unit tests** (`internal/service/*_test.go`) — ~238 test functions across 15 files with mock repositories. These test all business logic in isolation: certificate CRUD with validation, certificate revocation (success, already-revoked, archived, invalid reason, all RFC 5280 reason codes, issuer notification, notification service integration, OCSP/CRL generation), agent lifecycle (registration, heartbeat, CSR submission with both keygen modes), job state machine (creation, processing, cancellation, retry logic), policy evaluation (all 5 rule types, violation creation), renewal and issuance flow (server-side and agent-side keygen paths), notification deduplication (threshold tag matching, channel routing), team/owner/agent group CRUD with pagination and audit recording, issuer service CRUD with connection testing, and the issuer connector adapter (type translation between connector and service layers including revocation). Mock repositories are simple structs with function fields, avoiding heavy mocking frameworks — this keeps tests readable and avoids coupling to mock library APIs.
|
||||
**Service layer unit tests** (`internal/service/*_test.go`) — Mock-based tests across all service files covering certificate CRUD, revocation (all RFC 5280 reason codes, OCSP/CRL generation), agent lifecycle, job state machine, policy evaluation, renewal/issuance flow (both keygen modes), notification deduplication, team/owner/agent group CRUD, issuer service CRUD with connection testing, and the issuer connector adapter. Mock repositories are simple structs with function fields — no heavy mocking frameworks.
|
||||
|
||||
**Handler layer tests** (`internal/api/handler/*_test.go`) — ~257 test functions across 11 files using Go's `httptest` package. Every handler file has a corresponding test file: certificates (50 tests including revocation, DER CRL, and OCSP), agents (28 tests), jobs (21 tests including approve/reject), notifications (11 tests), policies (19 tests), profiles (18 tests), issuers (17 tests), targets (17 tests), agent groups (12 tests), teams (26 tests), and owners (21 tests). Each test file follows the same pattern: a mock service struct with function fields, `httptest.NewRecorder` for capturing responses, and a shared `contextWithRequestID()` helper. Tests cover the happy path, input validation (missing fields, invalid JSON, empty IDs, name length limits), error propagation from the service layer, method-not-allowed responses, and pagination parameters.
|
||||
**Handler layer tests** (`internal/api/handler/*_test.go`) — Every handler file has a corresponding test file using Go's `httptest` package: certificates (including revocation, DER CRL, OCSP), agents, jobs (including approve/reject), notifications, policies, profiles, issuers, targets, agent groups, teams, owners, discovery, network scan, verification, export, EST, digest, stats, and metrics. Tests cover the happy path, input validation, error propagation, method-not-allowed, and pagination.
|
||||
|
||||
**Integration tests** (`internal/integration/`) — Two test files exercising the full stack from HTTP request through router, handler, service, and postgres repository layers. `lifecycle_test.go` has 11 subtests covering the complete certificate lifecycle: team/owner creation, certificate creation, issuer verification, renewal trigger, job verification, agent registration, CSR submission, deployment, and status reporting. `negative_test.go` has 14 subtests covering error paths, 19 M11b endpoint tests, and 8 revocation endpoint tests (M15a+M15b): nonexistent resource lookups (404s), invalid request bodies (malformed JSON, missing required fields), invalid CSR submission, heartbeat for nonexistent agents, wrong HTTP methods on list endpoints, empty list responses, renewal on nonexistent certificates, expired certificate lifecycle, team/owner/agent group CRUD validation, revocation success, already-revoked rejection, not-found revocation, JSON CRL retrieval, DER CRL retrieval, OCSP response retrieval, and short-lived cert exemption. Both use a shared `setupTestServer()` that builds a fully-wired server with real postgres repositories and the Local CA issuer connector. A third file, `e2e_test.go`, contains 8 cross-milestone test functions with 48+ subtests that exercise features across milestones end-to-end: M10 agent metadata via heartbeat, M11 profiles/teams/owners/agent-groups CRUD, M12 issuer registry verification, M13 GUI operation endpoints, M14 stats and metrics, M15 revocation and CRL, M16 notification channels, and M20 enhanced query API (sorting, cursor pagination, sparse fields, time-range filters).
|
||||
**Integration tests** (`internal/integration/`) — Three test files exercising the full stack from HTTP request through router, handler, service, and repository layers. `lifecycle_test.go` covers the complete certificate lifecycle (team/owner creation through deployment and status reporting). `negative_test.go` covers error paths, endpoint validation, and revocation scenarios. `e2e_test.go` exercises cross-milestone features end-to-end (agent metadata, profiles, issuer registry, GUI operations, stats, revocation, notifications, enhanced query API).
|
||||
|
||||
**Frontend tests** (`web/src/api/client.test.ts`, `web/src/api/utils.test.ts`) — 86 Vitest tests covering the API client, stats/metrics endpoints, and utility functions. The API client tests mock `globalThis.fetch` and verify all endpoint functions (certificates, agents, jobs, policies, issuers, targets, notifications, audit, stats, metrics, health) send correct HTTP methods, URLs, headers, and request bodies. They also test API key management (store/retrieve/clear), auth header propagation, 401 event dispatching, and error handling (server messages, error fields, status text fallback). The stats/metrics endpoint tests verify correct query parameter handling and response shape validation. The utility tests use `vi.useFakeTimers()` for deterministic date testing and cover `formatDate`, `formatDateTime`, `timeAgo`, `daysUntil`, and `expiryColor`. The test environment uses jsdom with `@testing-library/jest-dom` matchers.
|
||||
**Go integration tests** (`deploy/test/integration_test.go`) — Runs against the live Docker Compose test environment with real CA backends (Local CA, Pebble ACME, step-ca). Covers health checks, agent heartbeat, issuance, renewal, revocation, CRL/OCSP, EST enrollment, S/MIME, discovery, network scanning, and deployment verification using `crypto/x509` for cert parsing and `crypto/tls` for live TLS verification.
|
||||
|
||||
**CLI tests** (`internal/cli/client_test.go`) — 14 tests covering all 10 CLI subcommands with httptest mock servers, PEM parsing for bulk import, auth header verification, and JSON/table output formatting.
|
||||
**Frontend tests** (`web/src/api/`) — Vitest tests covering the full API client (all endpoint functions with fetch mocking), stats/metrics endpoints, utility functions, and auth flows. Test environment uses jsdom with `@testing-library/jest-dom` matchers.
|
||||
|
||||
**CI pipeline** (`.github/workflows/ci.yml`) — Two parallel jobs: Go (build, vet, race detection, static analysis, vulnerability scanning, test with coverage, coverage threshold enforcement) and Frontend (TypeScript type check, Vitest test suite, Vite production build). The Go job runs `go test -race` on service, handler, middleware, and scheduler packages to catch data races. It runs `golangci-lint` with 11 linters (errcheck, govet, staticcheck, unused, gosimple, ineffassign, typecheck, gocritic, gosec, bodyclose, noctx) configured in `.golangci.yml`. It runs `govulncheck ./...` to scan dependencies for known CVEs. Coverage thresholds are enforced per-layer: service 60%, handler 60%, domain 40%, middleware 50%. These thresholds act as regression floors — they can only go up. Connector tests are included via `./internal/connector/issuer/...` and `./internal/connector/target/...` (covers Local CA, ACME, step-ca, NGINX, Apache, HAProxy, Traefik, and Caddy 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/`) — Issuer connectors (Local CA self-signed/sub-CA modes, ACME DNS-01/DNS-PERSIST-01, step-ca, OpenSSL, Vault PKI, DigiCert, Sectigo, Google CAS — all with httptest mock servers). Target connectors (NGINX, Apache, HAProxy, Traefik, Caddy, Envoy, IIS with mock PowerShell executor, F5 BIG-IP with mock iControl client, Postfix/Dovecot). Notifier connectors (Slack, Teams, PagerDuty, OpsGenie).
|
||||
|
||||
**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. Traefik and Caddy connectors have tests covering file-based deployment and (for Caddy) dual-mode API/file configuration. 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.
|
||||
**Scheduler tests** (`internal/scheduler/scheduler_test.go`) — Idempotency guards (`sync/atomic.Bool`), `WaitForCompletion` success and timeout paths, and multi-loop concurrency safety.
|
||||
|
||||
**Scheduler tests** (`internal/scheduler/scheduler_test.go`) — Tests for idempotency guards (`sync/atomic.Bool` CompareAndSwap prevents concurrent loop ticks), `WaitForCompletion` success and timeout paths, and multi-loop idempotency.
|
||||
**Fuzz tests** (`internal/validation/`, `internal/domain/`) — Go native fuzz tests for command validation (`ValidateShellCommand`, `ValidateDomainName`, `ValidateACMEToken`) and revocation domain parsing.
|
||||
|
||||
**Fuzz tests** (`internal/validation/command_fuzz_test.go`, `internal/domain/revocation_fuzz_test.go`) — Go native fuzz tests (`testing/fuzz`) for command validation functions and revocation domain parsing. These exercise `ValidateShellCommand`, `ValidateDomainName`, and `ValidateACMEToken` with random inputs to discover edge cases.
|
||||
|
||||
**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 — a `testcontainers-go` scaffolding for isolated PostgreSQL instances is planned. Target connectors for F5 BIG-IP and IIS are interface stubs (implementation planned for V3). 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.
|
||||
**CI pipeline** (`.github/workflows/ci.yml`) — Two parallel jobs. Go: build, vet, `go test -race`, `golangci-lint` (11 linters), `govulncheck`, test with coverage, per-layer coverage threshold enforcement (service 60%, handler 60%, domain 40%, middleware 50%). Frontend: TypeScript type check, Vitest, Vite production build.
|
||||
|
||||
## What's Next
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# certctl for cert-manager Users
|
||||
|
||||
You run cert-manager inside Kubernetes and it works well for in-cluster certificates. But you also have VMs, bare-metal servers, network appliances, and legacy systems outside the cluster. cert-manager can't reach those. This guide shows how certctl complements cert-manager to give you unified certificate visibility and automation across your entire infrastructure.
|
||||
|
||||
## Not a Replacement
|
||||
|
||||
cert-manager is the right tool for in-cluster certs. It's tightly integrated with Kubernetes:
|
||||
- Native CRDs (Certificate, ClusterIssuer, Issuer)
|
||||
- Automatic cert injection into Ingress and Service objects
|
||||
- Controller-driven renewal within the cluster
|
||||
|
||||
**certctl does not replace this.** Instead, it extends your certificate management to everything outside Kubernetes: VMs, bare metal, network appliances, Windows servers, and legacy systems.
|
||||
|
||||
## The Problem
|
||||
|
||||
Your setup:
|
||||
- **cert-manager**: handles all certs in Kubernetes (TLS for Ingress, service-to-service, internal services)
|
||||
- **Everything else**: NGINX/Apache on VMs, HAProxy load balancers on bare metal, network appliances, Windows servers with IIS — these are managed inconsistently. Maybe Certbot cron jobs, maybe manual renewal, maybe deprecated cert files sitting around.
|
||||
|
||||
Result:
|
||||
- No unified visibility — you don't know when non-Kubernetes certs expire
|
||||
- Renewal failures go unnoticed until the cert is already expired
|
||||
- Audit trail fragmented across multiple tools
|
||||
- Scaling to hundreds of machines becomes impossible
|
||||
|
||||
## The Solution
|
||||
|
||||
Deploy certctl control plane once (Docker Compose, Kubernetes Helm chart, or self-hosted). Deploy agents on your VMs, bare metal, and network appliances. One dashboard shows:
|
||||
- **All cert-manager certs** via discovery scanning (agents find cert-manager-issued certs copied to target machines, or scan the cluster directly)
|
||||
- **All certctl-managed certs** issued by shared issuers (ACME, step-ca, Vault PKI (planned), private CA)
|
||||
- **Unified renewal and deployment** across both worlds
|
||||
- **Single pane of glass** with expiration timeline, renewal status, deployment verification, audit trail
|
||||
|
||||
## How to Set Up
|
||||
|
||||
### 1. Install certctl Control Plane
|
||||
|
||||
**Option A: Docker Compose** (quickest for evaluation)
|
||||
```bash
|
||||
cd /opt/certctl
|
||||
docker compose up -d
|
||||
# Dashboard & API: http://localhost:8443
|
||||
```
|
||||
|
||||
**Option B: Kubernetes** (recommended for prod)
|
||||
```bash
|
||||
helm install certctl deploy/helm/certctl/ \
|
||||
--set auth.apiKey=YOUR_SECURE_KEY
|
||||
```
|
||||
|
||||
### 2. Deploy Agents to Non-Kubernetes Infrastructure
|
||||
|
||||
On each VM, bare-metal server, or appliance (via proxy agent):
|
||||
```bash
|
||||
# Linux amd64
|
||||
curl -sSL https://github.com/shankar0123/certctl/releases/download/v2.1.0/certctl-agent-linux-amd64 \
|
||||
-o /usr/local/bin/certctl-agent
|
||||
chmod +x /usr/local/bin/certctl-agent
|
||||
|
||||
# Config
|
||||
sudo tee /etc/certctl/agent.env > /dev/null <<EOF
|
||||
CERTCTL_SERVER_URL=http://certctl-control-plane:8443
|
||||
CERTCTL_API_KEY=your-api-key
|
||||
CERTCTL_DISCOVERY_DIRS=/etc/nginx/certs,/etc/ssl,/etc/letsencrypt/live
|
||||
CERTCTL_KEY_DIR=/var/lib/certctl/keys
|
||||
EOF
|
||||
sudo chmod 600 /etc/certctl/agent.env
|
||||
|
||||
# Start
|
||||
sudo systemctl start certctl-agent
|
||||
```
|
||||
|
||||
### 3. Enable Discovery Scanning
|
||||
|
||||
Agents scan configured directories and report back all existing certs. In the dashboard:
|
||||
- **Discovery** page: all found certs grouped by agent
|
||||
- Claim cert-manager certs to link them with Kubernetes metadata
|
||||
- Dismiss obsolete certs
|
||||
|
||||
### 4. Configure Shared Issuers
|
||||
|
||||
Set up the same issuer certctl uses for non-Kubernetes certs:
|
||||
- **ACME** (Let's Encrypt, for public certs)
|
||||
- **step-ca** (Smallstep, for internal certs)
|
||||
- **Vault PKI** (HashiCorp Vault, for enterprise PKI)
|
||||
- **Private CA** (your own internal root CA)
|
||||
|
||||
No new CA infrastructure needed. If cert-manager already uses your CA, certctl points to the same one.
|
||||
|
||||
### 5. Create Policies for Non-Kubernetes Certs
|
||||
|
||||
Go to **Policies** → **+ New Policy** to create enforcement rules:
|
||||
- **Name:** e.g., "VM Certificate Policy"
|
||||
- **Type:** `expiration_window` or `key_algorithm` (enforce renewal thresholds or crypto requirements)
|
||||
- **Severity:** `high`
|
||||
- **Config:** set your enforcement parameters
|
||||
|
||||
Certificates are linked to issuers and profiles when created or claimed from discovery. Policies add guardrails — enforcing key algorithm requirements, expiration windows, and other compliance rules across your fleet.
|
||||
|
||||
### 6. View Unified Inventory
|
||||
|
||||
**Dashboard** shows:
|
||||
- Certificate status heatmap (all 1000 certs: cert-manager + certctl)
|
||||
- Renewal job trends (both types)
|
||||
- Expiration timeline (30/60/90 days)
|
||||
- Agent fleet status (all infrastructure)
|
||||
|
||||
**Certificates** page filters by issuer (show me all ACME certs, or all step-ca certs):
|
||||
- cert-manager certs discovered from Kubernetes nodes
|
||||
- certctl-managed certs on VMs
|
||||
- Network appliance certs auto-discovered
|
||||
|
||||
## Shared Infrastructure
|
||||
|
||||
If cert-manager and certctl both use the same CA:
|
||||
- **ACME**: cert-manager uses ClusterIssuer + certctl uses ACME connector → same Let's Encrypt account, transparent coexistence
|
||||
- **step-ca**: cert-manager uses external issuer CRD + certctl uses step-ca connector → same provisioner, shared certificate inventory
|
||||
- **Vault PKI**: cert-manager uses external issuer CRD + certctl uses Vault connector → same mount, same audit trail
|
||||
|
||||
No conflict. They just issue certs through the same CA. certctl's discovery scanning finds cert-manager-issued certs and shows them alongside certctl-managed ones.
|
||||
|
||||
## Key Differences from cert-manager
|
||||
|
||||
| Feature | cert-manager | certctl |
|
||||
|---------|--------------|---------|
|
||||
| Target | In-cluster (Kubernetes) | Out-of-cluster (VMs, bare metal, appliances) |
|
||||
| Configuration | CRDs (Certificate, ClusterIssuer, Issuer) | API + Dashboard (JSON REST) |
|
||||
| Deployment | Injected into Secret objects, mounted by pods | Agent pulls work, deploys via target-specific API (file, service restart, proxy agent) |
|
||||
| Renewal | Controller watches Certificate CRDs, triggers renewal when needed | Scheduler checks thresholds, agents poll for work |
|
||||
| Audit | Kubernetes event log | Immutable append-only audit trail |
|
||||
| Visibility | Per-namespace, per-resource | Fleet-wide, unified inventory |
|
||||
|
||||
## Future Integration
|
||||
|
||||
On the roadmap (V4): **cert-manager external issuer** — certctl acts as a ClusterIssuer backend for Kubernetes. This would allow cert-manager to request certificates from certctl, which could issue them via any of its connectors (step-ca, Vault, private CA, etc.). Pure integration play; no breaking changes.
|
||||
|
||||
For now: cert-manager handles Kubernetes, certctl handles everything else. They coexist seamlessly.
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. Run through the [Quick Start](./quickstart.md) for a 5-minute demo
|
||||
2. Try the [Multi-Issuer example](../examples/multi-issuer/multi-issuer.md) — manages public and internal certs from one dashboard
|
||||
3. Explore [Architecture](./architecture.md#agents) for deployment patterns
|
||||
4. Check the [Helm Chart](../deploy/helm/certctl/) for production Kubernetes deployment
|
||||
@@ -183,13 +183,14 @@ Each section includes:
|
||||
|
||||
- **Health Endpoint** — `GET /health` returns 200 OK with service status. Consumed by Docker health checks and Kubernetes probes.
|
||||
- **Readiness Endpoint** — `GET /ready` returns 200 OK when the database is connected and migrations are applied.
|
||||
- **Background Scheduler Monitoring** — 6 background loops run on a fixed schedule:
|
||||
- **Background Scheduler Monitoring** — 7 background loops run on a fixed schedule:
|
||||
- Renewal loop: every 1 hour, scans for certificates approaching renewal threshold
|
||||
- Job processor loop: every 30 seconds, picks up pending/waiting jobs and advances their state
|
||||
- Health check loop: every 2 minutes, pings agents to detect downtime
|
||||
- Notification dispatcher loop: every 1 minute, sends queued alerts
|
||||
- Short-lived cert expiry loop: every 30 seconds, marks expired short-lived credentials
|
||||
- Network scanner loop: every 6 hours, scans enabled TLS endpoints for certificate discovery
|
||||
- Digest emailer loop: every 24 hours, sends scheduled certificate digest email to configured recipients
|
||||
Each loop includes error handling and logs failures via structured slog.
|
||||
- **Metrics Endpoints** — Two formats for monitoring integration:
|
||||
- `GET /api/v1/metrics` — JSON object with gauges, counters, and uptime for custom dashboards
|
||||
@@ -452,7 +453,7 @@ Each section includes:
|
||||
| | Metrics JSON Endpoint | `GET /api/v1/metrics` (gauges, counters, uptime) | ✅ | ✅ | Set thresholds, configure alerting |
|
||||
| | Stats API (time-series) | `GET /api/v1/stats/*` (summary, status, expiration, jobs, issuance) | ✅ | ✅ | Integrate into dashboards, SLO tracking |
|
||||
| | Structured Logging | `slog` middleware with request IDs | ✅ | ✅ | Aggregate logs to SIEM, define retention policy |
|
||||
| | Background Scheduler | 6 loops (renewal 1h, jobs 30s, health 2m, notifications 1m, short-lived 30s, network scan 6h) | ✅ | ✅ | Alert on scheduler loop failures |
|
||||
| | Background Scheduler | 7 loops (renewal 1h, jobs 30s, health 2m, notifications 1m, short-lived 30s, network scan 6h, digest 24h) | ✅ | ✅ | Alert on scheduler loop failures |
|
||||
| **CC7.2** Anomaly Detection | Immutable API Audit Trail | `internal/api/middleware/audit.go`, `GET /api/v1/audit` | ✅ | Enhanced (SIEM export) | Integrate into SIEM, search for anomalies, archive long-term |
|
||||
| | Expiration Threshold Alerting | Configurable per-policy (default 30/14/7/0 days) | ✅ | ✅ | Configure thresholds, integrate notifications |
|
||||
| | Status Auto-Transitions | Active → Expiring (30d) → Expired (0d) | ✅ | ✅ | Monitor status changes in audit trail |
|
||||
|
||||
+15
-2
@@ -125,9 +125,9 @@ Agents also report **metadata** about themselves — their operating system, CPU
|
||||
|
||||
### Deployment Targets
|
||||
|
||||
Targets are the systems where certificates actually get installed — NGINX web servers, Apache httpd servers, HAProxy load balancers, F5 BIG-IP appliances, Microsoft IIS servers. Each target type has a **connector** that knows how to deploy certificates to that specific system (e.g., writing files and reloading NGINX or Apache config, building a combined PEM for HAProxy).
|
||||
Targets are the systems where certificates actually get installed — NGINX web servers, Apache httpd servers, HAProxy load balancers, Traefik reverse proxies, Caddy servers, Envoy gateways, Postfix/Dovecot mail servers, Microsoft IIS servers, and network appliances. Each target type has a **connector** that knows how to deploy certificates to that specific system (e.g., writing files and reloading NGINX or Apache config, building a combined PEM for HAProxy).
|
||||
|
||||
For targets where an agent runs directly on the machine (NGINX, Apache, HAProxy, IIS), the agent deploys certificates locally — no remote access needed. For network appliances where you can't install an agent (F5 BIG-IP, Palo Alto, etc.), a **proxy agent** in the same network zone picks up the deployment job and calls the appliance's API. The server never initiates outbound connections to any target.
|
||||
For targets where an agent runs directly on the machine (NGINX, Apache, HAProxy, Traefik, Caddy, Envoy, Postfix, Dovecot, IIS), the agent deploys certificates locally — no remote access needed. For network appliances where you can't install an agent (F5 BIG-IP, Palo Alto, etc.), a **proxy agent** in the same network zone picks up the deployment job and calls the appliance's API. The server never initiates outbound connections to any target.
|
||||
|
||||
## The Certificate Lifecycle
|
||||
|
||||
@@ -183,6 +183,19 @@ Profiles are managed via the API (`/api/v1/profiles`) and the GUI, and can be as
|
||||
|
||||
For policies with `auto_renew` disabled, renewal jobs enter an **AwaitingApproval** state instead of processing immediately. An operator must explicitly approve or reject the renewal via the API or GUI. Approved jobs transition to Pending and are picked up by the scheduler. Rejected jobs are cancelled with an optional reason. This is useful for high-value certificates where you want human oversight before renewal.
|
||||
|
||||
### Renewal Timing: Thresholds vs. ARI (RFC 9702)
|
||||
|
||||
**Traditional approach (thresholds):** By default, certctl uses static renewal thresholds — renew a certificate at a fixed number of days before expiry (default: 30 days). This simple, predictable model works for most use cases: it avoids unnecessary renewals near expiry and gives you a predictable window to catch failures.
|
||||
|
||||
**Advanced approach (ACME ARI):** Some Certificate Authorities support ACME Renewal Information (RFC 9702), which allows the CA to tell certctl the optimal time to renew. Instead of guessing "renew 30 days before expiry," the CA responds with a precise `suggestedWindow` containing start and end times. This is useful when:
|
||||
- The CA is performing maintenance and wants to batch renewals in a specific window
|
||||
- The CA is coordinating a mass revocation (e.g., due to a compromise) and needs to control renewal timing
|
||||
- You want to avoid thundering herd renewal spikes by accepting the CA's suggested timing
|
||||
|
||||
**How it works:** Enable with `CERTCTL_ACME_ARI_ENABLED=true` on your ACME issuer. When a certificate approaches expiry, certctl queries the ARI endpoint with the certificate's DER encoding. The CA responds with a suggested renewal window. If the current time is within the window or past the start time, certctl renews immediately. Otherwise, it waits until the window opens.
|
||||
|
||||
**Graceful degradation:** If your CA doesn't support ARI (returns 404 from the ARI endpoint), certctl automatically falls back to the traditional threshold-based renewal. No configuration change needed — the fallback is transparent. Errors from the CA are logged as warnings and don't block the renewal process.
|
||||
|
||||
### Certificate Revocation
|
||||
|
||||
When a private key is compromised, a certificate is superseded, or a service is decommissioned, you need to revoke the certificate immediately — not wait for it to expire. Revocation tells clients "stop trusting this certificate right now."
|
||||
|
||||
+304
-26
@@ -21,9 +21,11 @@ Connectors extend certctl to integrate with external systems for certificate iss
|
||||
- [Built-in: Apache httpd](#built-in-apache-httpd)
|
||||
- [Built-in: HAProxy](#built-in-haproxy)
|
||||
- [Built-in: Traefik](#built-in-traefik)
|
||||
- [Built-in: Envoy](#built-in-envoy)
|
||||
- [Built-in: Postfix / Dovecot](#built-in-postfix--dovecot)
|
||||
- [Built-in: Caddy](#built-in-caddy)
|
||||
- [F5 BIG-IP (Interface Only)](#f5-big-ip-interface-only)
|
||||
- [IIS (Interface Only, Dual-Mode)](#iis-interface-only-dual-mode)
|
||||
- [IIS (Implemented, Dual-Mode)](#iis-implemented-dual-mode)
|
||||
4. [Notifier Connector](#notifier-connector)
|
||||
- [Interface](#interface-2)
|
||||
5. [Registering a Connector](#registering-a-connector)
|
||||
@@ -51,8 +53,8 @@ Connectors extend certctl to integrate with external systems for certificate iss
|
||||
|
||||
Three types of connectors:
|
||||
|
||||
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, Traefik, Caddy implemented; F5 via proxy agent, IIS dual-mode interface only; additional cloud and network targets 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, Vault PKI, DigiCert implemented; additional CA integrations planned)
|
||||
2. **Target Connector** — Deploys certificates to infrastructure (NGINX, Apache httpd, HAProxy, Traefik, Caddy, Envoy, Postfix, Dovecot, IIS implemented; F5 via proxy agent planned; additional cloud and network targets planned)
|
||||
3. **Notifier Connector** — Sends alerts about certificate events (Email, Webhooks, Slack, Microsoft Teams, PagerDuty, OpsGenie implemented)
|
||||
|
||||
All connectors accept JSON configuration at initialization, support config validation, and are registered in the service layer. Issuer connectors run on the control plane; target connectors run on agents. For network appliances where agents can't be installed, a **proxy agent** in the same network zone handles deployment — the server never initiates outbound connections.
|
||||
@@ -147,6 +149,8 @@ The Local CA issuer signs certificates using Go's `crypto/x509` library. It supp
|
||||
|
||||
**CRL and OCSP support (M15b):** The Local CA supports DER-encoded X.509 CRL generation via `GET /api/v1/crl/{issuer_id}` with 24-hour validity. An embedded OCSP responder at `GET /api/v1/ocsp/{issuer_id}/{serial}` returns signed OCSP responses for issued certificates (good/revoked/unknown status). Certificates with profile TTL < 1 hour automatically skip CRL/OCSP — expiry is treated as sufficient revocation for short-lived credentials.
|
||||
|
||||
**Extended Key Usage (EKU) support (M27):** The Local CA respects EKU constraints from certificate profiles and adjusts key usage flags accordingly. For S/MIME certificates (emailProtection EKU), it uses `DigitalSignature | ContentCommitment` instead of the TLS default. For TLS certificates (serverAuth/clientAuth EKU), it uses `DigitalSignature | KeyEncipherment`. This enables support for multiple certificate types — TLS, S/MIME, code signing, timestamping — from a single CA.
|
||||
|
||||
Configuration:
|
||||
```json
|
||||
{
|
||||
@@ -169,6 +173,8 @@ The ACME connector implements the full ACME v2 protocol using Go's `golang.org/x
|
||||
|
||||
**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.
|
||||
|
||||
**ACME Renewal Information (ARI, RFC 9702):** Instead of using fixed renewal thresholds (e.g., renew 30 days before expiry), certctl can ask the CA when it should renew. Enable with `CERTCTL_ACME_ARI_ENABLED=true`. The ARI protocol lets the CA specify a `suggestedWindow` (start and end times) for when you should renew — useful for distributing load during maintenance windows or coordinating mass revocation scenarios. Cert ID is computed as `base64url(SHA-256(DER cert))`. If the CA doesn't support ARI (404 response), certctl automatically falls back to threshold-based renewal with no operator intervention required.
|
||||
|
||||
HTTP-01 configuration:
|
||||
```json
|
||||
{
|
||||
@@ -308,12 +314,95 @@ The `GetCACertPEM()` method returns the PEM-encoded CA certificate chain, used b
|
||||
|
||||
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
|
||||
### Built-in: Vault PKI
|
||||
|
||||
The following issuer connectors are planned for future milestones:
|
||||
The Vault PKI connector integrates with HashiCorp Vault's PKI secrets engine using its native `/sign` API with token-based authentication. This is ideal for organizations using Vault as their internal certificate authority — synchronous issuance without the complexity of ACME or challenge solving.
|
||||
|
||||
- **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).
|
||||
**Configuration:**
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_VAULT_ADDR` | — | Vault server address (e.g., `https://vault.internal:8200`) |
|
||||
| `CERTCTL_VAULT_TOKEN` | — | Vault auth token with permissions on the PKI mount |
|
||||
| `CERTCTL_VAULT_MOUNT` | `pki` | PKI secrets engine mount path |
|
||||
| `CERTCTL_VAULT_ROLE` | — | PKI role name for certificate signing |
|
||||
| `CERTCTL_VAULT_TTL` | `8760h` | Certificate validity period (TTL) |
|
||||
|
||||
The connector is registered in the issuer registry under `iss-vault`. Vault issues certificates synchronously via the `/v1/{mount}/sign/{role}` API with `X-Vault-Token` header authentication. The issued certificate is parsed to extract serial number, validity dates, and chain information.
|
||||
|
||||
**Note:** CRL and OCSP are managed by Vault itself. Clients should validate certificate status against Vault's own CRL/OCSP endpoints (`GET /v1/{mount}/crl` and Vault's OCSP responder). certctl does not generate local CRL/OCSP for Vault-issued certificates. Revocation is recorded locally but Vault is the authoritative source.
|
||||
|
||||
Location: `internal/connector/issuer/vault/vault.go`
|
||||
|
||||
### Built-in: DigiCert CertCentral
|
||||
|
||||
The DigiCert connector integrates with DigiCert's CertCentral REST API for ordering and managing certificates from DigiCert's commercial CA. It supports both Domain Validated (DV) and Organization/Extended Validated (OV/EV) certificates, with async order processing.
|
||||
|
||||
**Configuration:**
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_DIGICERT_API_KEY` | — | DigiCert API key (X-DC-DEVKEY header) |
|
||||
| `CERTCTL_DIGICERT_ORG_ID` | — | DigiCert organization ID |
|
||||
| `CERTCTL_DIGICERT_PRODUCT_TYPE` | `ssl_basic` | Certificate product (e.g., `ssl_basic`, `ssl_plus`, `ssl_ev`) |
|
||||
| `CERTCTL_DIGICERT_BASE_URL` | `https://www.digicert.com/services/v2` | DigiCert API base URL |
|
||||
|
||||
The connector submits certificate orders to DigiCert's `/order/certificate/create` API. DV certificates may issue immediately; OV/EV certificates require validation (handled by DigiCert) and poll-based completion. The connector periodically checks order status via `/order/certificate/{order_id}` until the certificate is available.
|
||||
|
||||
**Authentication:** API key passed via `X-DC-DEVKEY` header, with organization ID in request body.
|
||||
|
||||
**Note:** CRL and OCSP are managed by DigiCert. Clients should validate certificate status against DigiCert's infrastructure. certctl records the revocation locally but does not notify DigiCert for revocation — use DigiCert's dashboard for revocation management.
|
||||
|
||||
Location: `internal/connector/issuer/digicert/digicert.go`
|
||||
|
||||
### Built-in: Sectigo SCM
|
||||
|
||||
The Sectigo connector integrates with Sectigo Certificate Manager's REST API for ordering and managing DV, OV, and EV certificates. Like DigiCert, it uses an async order model: submit an enrollment, receive an sslId, then poll for completion.
|
||||
|
||||
**Configuration:**
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_SECTIGO_CUSTOMER_URI` | — | Sectigo customer URI (organization identifier) |
|
||||
| `CERTCTL_SECTIGO_LOGIN` | — | API account login |
|
||||
| `CERTCTL_SECTIGO_PASSWORD` | — | API account password |
|
||||
| `CERTCTL_SECTIGO_ORG_ID` | — | Organization ID (integer) |
|
||||
| `CERTCTL_SECTIGO_CERT_TYPE` | — | Certificate type ID (integer, from `/ssl/v1/types`) |
|
||||
| `CERTCTL_SECTIGO_TERM` | `365` | Certificate validity in days |
|
||||
| `CERTCTL_SECTIGO_BASE_URL` | `https://cert-manager.com/api` | Sectigo API base URL |
|
||||
|
||||
The connector submits certificate enrollments to Sectigo's `/ssl/v1/enroll` API. DV certificates may issue immediately; OV/EV certificates require validation (handled by Sectigo) and poll-based completion. The connector periodically checks enrollment status via `/ssl/v1/{sslId}` and downloads the PEM bundle via `/ssl/v1/collect/{sslId}/pem` when issued.
|
||||
|
||||
**Authentication:** Three custom headers on every request — `customerUri`, `login`, and `password`.
|
||||
|
||||
**Note:** CRL and OCSP are managed by Sectigo. certctl records revocations locally and notifies Sectigo via `/ssl/v1/revoke/{sslId}`.
|
||||
|
||||
Location: `internal/connector/issuer/sectigo/sectigo.go`
|
||||
|
||||
### Built-in: Google CAS
|
||||
|
||||
Google Cloud Certificate Authority Service — managed private CA on GCP. Synchronous issuance via CAS REST API with OAuth2 service account auth.
|
||||
|
||||
| Setting | Required | Default | Description |
|
||||
|---------|----------|---------|-------------|
|
||||
| `CERTCTL_GOOGLE_CAS_PROJECT` | Yes | — | GCP project ID |
|
||||
| `CERTCTL_GOOGLE_CAS_LOCATION` | Yes | — | GCP region (e.g., `us-central1`) |
|
||||
| `CERTCTL_GOOGLE_CAS_CA_POOL` | Yes | — | CA pool name |
|
||||
| `CERTCTL_GOOGLE_CAS_CREDENTIALS` | Yes | — | Path to service account JSON |
|
||||
| `CERTCTL_GOOGLE_CAS_TTL` | No | `8760h` | Default certificate TTL |
|
||||
|
||||
**Authentication:** OAuth2 service account. The connector reads a service account JSON file, signs a JWT with the private key, and exchanges it for an access token at Google's token endpoint. Tokens are cached and refreshed automatically (5 min before expiry).
|
||||
|
||||
**Note:** CRL and OCSP are managed by Google CAS directly. certctl records revocations locally and notifies Google CAS via the revoke endpoint.
|
||||
|
||||
Location: `internal/connector/issuer/googlecas/googlecas.go`
|
||||
|
||||
### Coming in V2.2+
|
||||
|
||||
The following issuer connectors are planned for future releases:
|
||||
|
||||
- **Entrust** — Enterprise CA via Entrust API
|
||||
- **AWS ACM Private CA** — AWS-managed private CA
|
||||
|
||||
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.
|
||||
|
||||
@@ -543,51 +632,182 @@ When `mode` is `"api"`, the connector posts the certificate to the admin API end
|
||||
|
||||
Location: `internal/connector/target/caddy/caddy.go`
|
||||
|
||||
### F5 BIG-IP (Interface Only)
|
||||
### Built-in: Envoy
|
||||
|
||||
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 Envoy connector uses file-based certificate delivery — it writes certificate and key files to a directory that Envoy watches via its SDS (Secret Discovery Service) file-based configuration or static `filename` references in the bootstrap config. When files change, Envoy automatically picks up the new certificates without requiring a reload command.
|
||||
|
||||
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:
|
||||
```json
|
||||
{
|
||||
"cert_dir": "/etc/envoy/certs",
|
||||
"cert_filename": "cert.pem",
|
||||
"key_filename": "key.pem",
|
||||
"chain_filename": "chain.pem",
|
||||
"sds_config": true
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Default | Description |
|
||||
|-------|------|---------|-------------|
|
||||
| `cert_dir` | string | (required) | Directory where Envoy watches for certificate files |
|
||||
| `cert_filename` | string | `cert.pem` | Filename for the certificate (leaf + chain unless `chain_filename` is set) |
|
||||
| `key_filename` | string | `key.pem` | Filename for the private key |
|
||||
| `chain_filename` | string | (empty) | If set, chain is written to a separate file instead of appended to the cert |
|
||||
| `sds_config` | bool | `false` | If true, writes an `sds.json` file for Envoy's file-based SDS provider |
|
||||
|
||||
When `sds_config` is `true`, the connector writes an SDS JSON file (`{cert_dir}/sds.json`) containing a `tls_certificate` resource that points to the cert and key file paths. Envoy's file-based SDS (`path_config_source`) watches this file for changes, providing automatic hot-reload of certificates. This is the recommended approach for production Envoy deployments using dynamic TLS configuration.
|
||||
|
||||
When `sds_config` is `false` (the default), the connector simply writes cert and key files. Use this mode when Envoy's bootstrap config references the cert/key files directly via static `filename` fields in the TLS context.
|
||||
|
||||
Location: `internal/connector/target/envoy/envoy.go`
|
||||
|
||||
### Built-in: Postfix / Dovecot
|
||||
|
||||
The Postfix/Dovecot connector is a dual-mode mail server TLS connector. It writes certificate, key, and chain files to configured paths and reloads the mail service. The `mode` field selects between Postfix MTA and Dovecot IMAP/POP3, which determines default file paths and reload commands.
|
||||
|
||||
This connector pairs with certctl's S/MIME certificate support (email protection EKU, email SAN routing) for a complete email infrastructure story — TLS for transport encryption, S/MIME for end-to-end message signing and encryption.
|
||||
|
||||
**Postfix configuration:**
|
||||
```json
|
||||
{
|
||||
"mode": "postfix",
|
||||
"cert_path": "/etc/postfix/certs/cert.pem",
|
||||
"key_path": "/etc/postfix/certs/key.pem",
|
||||
"chain_path": "/etc/postfix/certs/chain.pem",
|
||||
"reload_command": "postfix reload",
|
||||
"validate_command": "postfix check"
|
||||
}
|
||||
```
|
||||
|
||||
**Dovecot configuration:**
|
||||
```json
|
||||
{
|
||||
"mode": "dovecot",
|
||||
"cert_path": "/etc/dovecot/certs/cert.pem",
|
||||
"key_path": "/etc/dovecot/certs/key.pem",
|
||||
"chain_path": "/etc/dovecot/certs/chain.pem",
|
||||
"reload_command": "doveadm reload",
|
||||
"validate_command": "doveconf -n"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Default (Postfix) | Default (Dovecot) | Description |
|
||||
|-------|------|-------------------|-------------------|-------------|
|
||||
| `mode` | string | `postfix` | `dovecot` | Service mode — determines defaults |
|
||||
| `cert_path` | string | `/etc/postfix/certs/cert.pem` | `/etc/dovecot/certs/cert.pem` | Path for certificate file |
|
||||
| `key_path` | string | `/etc/postfix/certs/key.pem` | `/etc/dovecot/certs/key.pem` | Path for private key (0600 permissions) |
|
||||
| `chain_path` | string | (empty) | (empty) | If set, chain written separately; otherwise appended to cert |
|
||||
| `reload_command` | string | `postfix reload` | `doveadm reload` | Command to reload the mail service |
|
||||
| `validate_command` | string | `postfix check` | `doveconf -n` | Optional config validation before reload |
|
||||
|
||||
All commands are validated against shell injection via `validation.ValidateShellCommand()`. File permissions: cert/chain 0644, key 0600.
|
||||
|
||||
Location: `internal/connector/target/postfix/postfix.go`
|
||||
|
||||
### F5 BIG-IP (Implemented)
|
||||
|
||||
The F5 BIG-IP target connector deploys certificates to F5 load balancers via the iControl REST API. F5 appliances can't run agents directly, so this connector uses the **proxy agent pattern**: a designated certctl agent in the same network zone polls for F5 deployment jobs and executes iControl REST calls on behalf of the control plane. Minimum supported BIG-IP version: 12.0+.
|
||||
|
||||
The deployment flow uses F5's transaction API for atomic updates: authenticate via token auth, upload cert/key/chain PEM files, install as crypto objects, update the SSL client profile within a transaction, and commit. If the transaction fails, F5 rolls back automatically and the connector cleans up uploaded crypto objects. Updating an SSL profile automatically takes effect on all bound virtual servers — no separate virtual server binding step is needed.
|
||||
|
||||
| Field | Type | Default | Description |
|
||||
|-------|------|---------|-------------|
|
||||
| `host` | string | *(required)* | F5 BIG-IP management hostname or IP |
|
||||
| `port` | int | `443` | iControl REST API port |
|
||||
| `username` | string | *(required)* | Administrative username |
|
||||
| `password` | string | *(required)* | Administrative password |
|
||||
| `partition` | string | `Common` | F5 partition for crypto objects and profiles |
|
||||
| `ssl_profile` | string | *(required)* | SSL client profile name to update |
|
||||
| `insecure` | bool | `true` | Skip TLS verification for management interface (self-signed certs common) |
|
||||
| `timeout` | int | `30` | HTTP timeout in seconds |
|
||||
|
||||
Configuration (defined, not yet functional):
|
||||
```json
|
||||
{
|
||||
"host": "f5.internal.example.com",
|
||||
"port": 443,
|
||||
"username": "admin",
|
||||
"password": "...",
|
||||
"partition": "Common",
|
||||
"ssl_profile": "/Common/clientssl_api"
|
||||
"ssl_profile": "clientssl_api",
|
||||
"insecure": true,
|
||||
"timeout": 30
|
||||
}
|
||||
```
|
||||
|
||||
Note: F5 credentials are stored on the proxy agent, not on the control plane server. This limits the credential blast radius to the proxy agent's network zone.
|
||||
F5 credentials are stored on the proxy agent, not on the control plane server. This limits the credential blast radius to the proxy agent's network zone. Config fields are validated against regex patterns to prevent injection.
|
||||
|
||||
Location: `internal/connector/target/f5/f5.go`
|
||||
|
||||
### IIS (Interface Only, Dual-Mode)
|
||||
### IIS (Implemented, Dual-Mode)
|
||||
|
||||
The IIS target connector supports two planned deployment modes:
|
||||
The IIS target connector supports two deployment modes — agent-local (recommended) and proxy agent WinRM for agentless targets.
|
||||
|
||||
**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.
|
||||
**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. The agent handles PEM-to-PFX conversion via `go-pkcs12`, computes SHA-1 thumbprint from the certificate, and executes parameterized PowerShell scripts for injection-safe binding management. This is the preferred approach: no remote access needed, no credential management, same pull-based model as NGINX/Apache/HAProxy.
|
||||
|
||||
**Proxy agent WinRM (for agentless targets):** For Windows servers where you don't want to install an agent, a nearby Windows agent acts as a proxy and reaches the IIS box via WinRM. The proxy agent picks up the deployment job, transfers the PFX bundle over WinRM, and runs the PowerShell commands remotely. WinRM credentials are stored on the proxy agent, not on the control plane.
|
||||
**Proxy agent WinRM (for agentless targets):** For Windows servers where you don't want to install an agent, a Linux or Windows proxy agent in the same network zone connects via WinRM (Windows Remote Management) and executes PowerShell commands remotely. The PFX bundle is base64-encoded, transferred inline in the WinRM session, decoded to a temp file on the remote host, imported, and the temp file is cleaned up in a `try/finally` block. WinRM credentials are configured on the target, not on the control plane. Uses the `masterzen/winrm` Go library with support for Basic, NTLM, and Kerberos authentication.
|
||||
|
||||
Configuration (defined, not yet functional):
|
||||
**Agent-local configuration:**
|
||||
```json
|
||||
{
|
||||
"mode": "local",
|
||||
"hostname": "iis-server.example.com",
|
||||
"site_name": "Default Web Site",
|
||||
"cert_store": "WebHosting",
|
||||
"winrm_host": "",
|
||||
"winrm_username": "",
|
||||
"winrm_password": "",
|
||||
"winrm_use_https": true
|
||||
"port": 443,
|
||||
"sni": true,
|
||||
"ip_address": "*",
|
||||
"binding_info": "www.example.com"
|
||||
}
|
||||
```
|
||||
|
||||
When `mode` is `"local"`, the `winrm_*` fields are ignored. When `mode` is `"proxy"`, the agent connects to the remote IIS server via WinRM using the provided credentials.
|
||||
**WinRM proxy configuration:**
|
||||
```json
|
||||
{
|
||||
"hostname": "iis-server.example.com",
|
||||
"site_name": "Default Web Site",
|
||||
"cert_store": "WebHosting",
|
||||
"port": 443,
|
||||
"sni": true,
|
||||
"ip_address": "*",
|
||||
"mode": "winrm",
|
||||
"winrm": {
|
||||
"winrm_host": "iis-server.example.com",
|
||||
"winrm_port": 5985,
|
||||
"winrm_username": "Administrator",
|
||||
"winrm_password": "...",
|
||||
"winrm_https": false,
|
||||
"winrm_insecure": false,
|
||||
"winrm_timeout": 60
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Location: `internal/connector/target/iis/iis.go`
|
||||
**Configuration Fields:**
|
||||
- `hostname` (string, required): IIS server hostname or FQDN
|
||||
- `site_name` (string, required): IIS website name (e.g., "Default Web Site")
|
||||
- `cert_store` (string, required): Certificate store for import (e.g., "WebHosting", "My")
|
||||
- `port` (number, default 443): HTTPS binding port
|
||||
- `sni` (boolean, default false): Enable Server Name Indication (SNI)
|
||||
- `ip_address` (string, default "*"): Specific IP to bind to, or "*" for all IPs
|
||||
- `binding_info` (string, optional): Host header for SNI bindings
|
||||
- `mode` (string, default "local"): Deployment mode — `local` (agent-local PowerShell) or `winrm` (remote via WinRM)
|
||||
|
||||
**WinRM fields (required when `mode` is `winrm`):**
|
||||
- `winrm.winrm_host` (string, required): Remote Windows server hostname or IP
|
||||
- `winrm.winrm_port` (number, default 5985 HTTP / 5986 HTTPS): WinRM listener port
|
||||
- `winrm.winrm_username` (string, required): Windows account with admin privileges
|
||||
- `winrm.winrm_password` (string, required): Account password
|
||||
- `winrm.winrm_https` (boolean, default false): Use HTTPS transport
|
||||
- `winrm.winrm_insecure` (boolean, default false): Skip TLS certificate verification
|
||||
- `winrm.winrm_timeout` (number, default 60): Operation timeout in seconds
|
||||
|
||||
**Security Model:**
|
||||
- PFX files are transient — generated with random passwords, deleted after import
|
||||
- In WinRM mode, PFX data is base64-encoded and transferred inline (no SMB/file share needed), with remote temp file cleanup in `try/finally`
|
||||
- PowerShell commands use parameterized values — IIS names and cert stores are regex-validated before script execution
|
||||
- Field names are validated against `^[a-zA-Z0-9 _\-\.]+$` to prevent PowerShell injection
|
||||
- Certificate thumbprints computed via SHA-1 for IIS binding lookups
|
||||
|
||||
Location: `internal/connector/target/iis/iis.go`, `internal/connector/target/iis/winrm.go`
|
||||
|
||||
## Notifier Connector
|
||||
|
||||
@@ -620,11 +840,69 @@ type Connector interface {
|
||||
|
||||
Built-in notifiers: **Email** (SMTP), **Webhook** (HTTP POST), **Slack** (incoming webhook), **Microsoft Teams** (MessageCard webhook), **PagerDuty** (Events API v2), and **OpsGenie** (Alert API v2).
|
||||
|
||||
### Email (SMTP) Notifier
|
||||
|
||||
The Email notifier sends transactional alerts and scheduled digests via SMTP. It bridges the connector-layer SMTP connector to the service-layer `Notifier` interface via the `NotifierAdapter`. Supports both plain text and HTML emails.
|
||||
|
||||
Configuration:
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_SMTP_HOST` | — | SMTP server hostname (required to enable) |
|
||||
| `CERTCTL_SMTP_PORT` | 587 | SMTP port (TLS) |
|
||||
| `CERTCTL_SMTP_USERNAME` | — | SMTP authentication username (optional) |
|
||||
| `CERTCTL_SMTP_PASSWORD` | — | SMTP authentication password (optional) |
|
||||
| `CERTCTL_SMTP_FROM_ADDRESS` | — | Email from address (required) |
|
||||
| `CERTCTL_SMTP_USE_TLS` | true | Enable TLS encryption |
|
||||
|
||||
Example:
|
||||
```bash
|
||||
export CERTCTL_SMTP_HOST=smtp.gmail.com
|
||||
export CERTCTL_SMTP_PORT=587
|
||||
export CERTCTL_SMTP_USERNAME=admin@example.com
|
||||
export CERTCTL_SMTP_PASSWORD=app-password-123
|
||||
export CERTCTL_SMTP_FROM_ADDRESS=certctl@example.com
|
||||
```
|
||||
|
||||
### Scheduled Certificate Digest
|
||||
|
||||
The `DigestService` generates aggregated certificate digest emails and sends them on a configurable schedule. This is useful for periodic briefings on certificate inventory health — expiring certs, status summary, active agents, job trends.
|
||||
|
||||
The digest HTML template includes:
|
||||
- Total certificates, expiring soon, expired, active agents (stats grid)
|
||||
- Jobs completed/failed summary (30 days)
|
||||
- Expiring certificates table (color-coded by urgency: 7d, 14d, 30d)
|
||||
- Auto-refresh and responsive email layout
|
||||
|
||||
**Scheduler Integration:** The 7th scheduler loop runs on configurable interval (default 24 hours). It does NOT run on startup — waits for first scheduled tick. Operation timeout is 5 minutes. Each loop execution is guarded by `sync/atomic.Bool` idempotency.
|
||||
|
||||
Configuration:
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CERTCTL_DIGEST_ENABLED` | false | Enable scheduled digest emails |
|
||||
| `CERTCTL_DIGEST_INTERVAL` | 24h | How often to send digest (any duration, e.g. 12h, 7d) |
|
||||
| `CERTCTL_DIGEST_RECIPIENTS` | — | Comma-separated email addresses. Falls back to certificate owner emails if empty |
|
||||
|
||||
API Endpoints:
|
||||
|
||||
- **`GET /api/v1/digest/preview`** — Render digest HTML for preview (no email sent)
|
||||
- **`POST /api/v1/digest/send`** — Trigger digest send immediately (outside of schedule)
|
||||
|
||||
Example:
|
||||
```bash
|
||||
# Preview digest
|
||||
curl http://localhost:8443/api/v1/digest/preview | jq '.html'
|
||||
|
||||
# Send digest immediately
|
||||
curl -X POST http://localhost:8443/api/v1/digest/send
|
||||
```
|
||||
|
||||
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` |
|
||||
| Email | `CERTCTL_SMTP_HOST` | SMTP email delivery. See Email Notifier section above |
|
||||
| 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) |
|
||||
|
||||
@@ -307,8 +307,8 @@ flowchart TD
|
||||
A --> F["ACME\n(Let's Encrypt)"]
|
||||
A --> G["step-ca\n(implemented)"]
|
||||
A --> H["OpenSSL / Custom CA\n(script-based)"]
|
||||
A --> J["DigiCert API\n(planned)"]
|
||||
A --> K["Vault PKI\n(planned)"]
|
||||
A --> J["DigiCert API\n(implemented)"]
|
||||
A --> K["Vault PKI\n(implemented)"]
|
||||
A --> L["Entrust / GlobalSign\n(planned)"]
|
||||
A --> M["Google CAS / EJBCA\n(planned)"]
|
||||
```
|
||||
@@ -1153,7 +1153,7 @@ flowchart TB
|
||||
API["REST API\nGo net/http"]
|
||||
SVC["Service Layer\nBusiness Logic"]
|
||||
REPO["Repository Layer\ndatabase/sql + lib/pq"]
|
||||
SCHED["Scheduler\n6 background loops"]
|
||||
SCHED["Scheduler\n7 background loops"]
|
||||
CONN["Connector Registry\nIssuer + Target + Notifier"]
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
# Deployment Examples
|
||||
|
||||
Five turnkey docker-compose scenarios, each runnable in under 5 minutes. Pick the one closest to your setup.
|
||||
|
||||
## Which Example Should I Use?
|
||||
|
||||
| I need to... | Example | Issuer | Target |
|
||||
|--------------|---------|--------|--------|
|
||||
| Get Let's Encrypt certs for NGINX on a public server | [ACME + NGINX](#acme--nginx) | ACME (HTTP-01) | NGINX |
|
||||
| Issue wildcard certs without opening port 80 | [Wildcard DNS-01](#wildcard-dns-01) | ACME (DNS-01) | Any |
|
||||
| Run an internal CA for services behind a firewall | [Private CA + Traefik](#private-ca--traefik) | Local CA | Traefik |
|
||||
| Use Smallstep step-ca as my PKI backend | [step-ca + HAProxy](#step-ca--haproxy) | step-ca | HAProxy |
|
||||
| Manage both public and internal certs from one dashboard | [Multi-Issuer](#multi-issuer) | ACME + Local CA | Mixed |
|
||||
|
||||
**Already using another tool?** See the migration sections below each example for Certbot, acme.sh, and cert-manager users.
|
||||
|
||||
---
|
||||
|
||||
## ACME + NGINX
|
||||
|
||||
**Scenario:** You have one or more public-facing domains, NGINX as the reverse proxy, and want automated Let's Encrypt certificates with HTTP-01 challenges.
|
||||
|
||||
**What it deploys:** certctl server + PostgreSQL + certctl agent + NGINX, all on one Docker network. The agent generates keys locally (ECDSA P-256), submits CSRs to the server, receives signed certs from Let's Encrypt, and deploys them to NGINX with automatic reload.
|
||||
|
||||
**Prerequisites:** A domain pointing to your server, ports 80 and 443 open, Docker Compose v20.10+.
|
||||
|
||||
```bash
|
||||
cd examples/acme-nginx
|
||||
cp .env.example .env # Edit with your domain and email
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The full walkthrough — including how HTTP-01 challenges work, adding multiple domains, switching to staging for testing, and a production checklist — is in the [example README](../examples/acme-nginx/acme-nginx.md).
|
||||
|
||||
**Migrating from Certbot?** certctl discovers your existing `/etc/letsencrypt/live/` certificates automatically. You keep your ACME account, disable the Certbot cron, and certctl takes over renewal with centralized visibility and deployment verification. The step-by-step process is in [Migrating from Certbot](migrate-from-certbot.md).
|
||||
|
||||
---
|
||||
|
||||
## Wildcard DNS-01
|
||||
|
||||
**Scenario:** You need wildcard certificates (`*.example.com`) or your servers aren't reachable from the internet (no port 80). DNS-01 validates ownership by creating a TXT record at your DNS provider.
|
||||
|
||||
**What it deploys:** certctl server + PostgreSQL + certctl agent. Includes a Cloudflare DNS hook script as a working reference — swap in your own DNS provider (Route53, Azure DNS, Google Cloud DNS, or any provider with an API).
|
||||
|
||||
**Prerequisites:** A domain, API credentials for your DNS provider, Docker Compose.
|
||||
|
||||
```bash
|
||||
cd examples/acme-wildcard-dns01
|
||||
cp .env.example .env # Edit with domain, email, DNS provider credentials
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The full walkthrough — including DNS-PERSIST-01 (set a TXT record once, never touch DNS again on renewals), adapting scripts for other providers, and propagation troubleshooting — is in the [example README](../examples/acme-wildcard-dns01/acme-wildcard-dns01.md).
|
||||
|
||||
**Migrating from acme.sh?** Your existing `dns_*` hook scripts are compatible with certctl's DNS-01 — they use the same pattern (shell scripts creating TXT records). The migration guide covers script adaptation, discovery of existing acme.sh certificates, and phasing out the acme.sh cron. See [Migrating from acme.sh](migrate-from-acmesh.md).
|
||||
|
||||
---
|
||||
|
||||
## Private CA + Traefik
|
||||
|
||||
**Scenario:** Internal services that don't need public CA validation. You run your own certificate authority — either a self-signed root for development, or a subordinate CA chained to your enterprise root (e.g., Active Directory Certificate Services).
|
||||
|
||||
**What it deploys:** certctl server + PostgreSQL + certctl agent + Traefik. The Local CA issuer signs certificates directly. Traefik watches a cert directory and auto-reloads when new files appear.
|
||||
|
||||
**Prerequisites:** Docker Compose. For sub-CA mode, you'll need a CA certificate and key signed by your enterprise root.
|
||||
|
||||
```bash
|
||||
cd examples/private-ca-traefik
|
||||
docker compose up -d # Self-signed mode (no .env needed for demo)
|
||||
```
|
||||
|
||||
The full walkthrough — including sub-CA setup with `CERTCTL_CA_CERT_PATH` and `CERTCTL_CA_KEY_PATH`, creating certificates via the API, monitoring deployments, and production hardening — is in the [example README](../examples/private-ca-traefik/private-ca-traefik.md).
|
||||
|
||||
---
|
||||
|
||||
## step-ca + HAProxy
|
||||
|
||||
**Scenario:** You use Smallstep's step-ca as your private PKI and want automated lifecycle management for certificates deployed to HAProxy load balancers.
|
||||
|
||||
**What it deploys:** certctl server + PostgreSQL + certctl agent + step-ca (with JWK provisioner) + HAProxy. certctl issues certs via step-ca's native `/sign` API, combines them into HAProxy's expected PEM format (cert + chain + key in one file), and reloads HAProxy.
|
||||
|
||||
**Prerequisites:** Docker Compose.
|
||||
|
||||
```bash
|
||||
cd examples/step-ca-haproxy
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The full walkthrough — including step-ca provisioner configuration, integrating with an existing step-ca instance, HAProxy PEM format details, and advanced features (approval workflows, policy-based renewal, multi-instance HAProxy) — is in the [example README](../examples/step-ca-haproxy/step-ca-haproxy.md).
|
||||
|
||||
---
|
||||
|
||||
## Multi-Issuer
|
||||
|
||||
**Scenario:** You manage both public-facing services (needing Let's Encrypt or another public CA) and internal services (using a private CA) and want a single dashboard for everything.
|
||||
|
||||
**What it deploys:** certctl server + PostgreSQL + certctl agent configured with both an ACME issuer and a Local CA issuer. Demonstrates issuer assignment via profiles — public services get ACME certs, internal services get Local CA certs, all visible in one inventory.
|
||||
|
||||
**Prerequisites:** Docker Compose. For real ACME certs, a public domain and port 80 access.
|
||||
|
||||
```bash
|
||||
cd examples/multi-issuer
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The full walkthrough — including profile-based issuer assignment, testing with ACME staging, Local CA enterprise sub-CA mode, and scaling beyond Docker Compose — is in the [example README](../examples/multi-issuer/multi-issuer.md).
|
||||
|
||||
**Using cert-manager for Kubernetes?** certctl complements cert-manager — cert-manager handles in-cluster certs, certctl handles everything outside: VMs, bare metal, network appliances, Windows servers. They can share the same CA (ACME, step-ca, Vault PKI). See [certctl for cert-manager Users](certctl-for-cert-manager-users.md).
|
||||
|
||||
---
|
||||
|
||||
## Beyond These Examples
|
||||
|
||||
These 5 scenarios cover the most common deployment patterns, but certctl supports 7 issuer backends and 10 target connectors. Once you have the basics running, you can mix and match:
|
||||
|
||||
**Issuers:** ACME (Let's Encrypt, ZeroSSL, Buypass, Google Trust Services), Local CA (self-signed or sub-CA), step-ca, Vault PKI, DigiCert CertCentral, OpenSSL/Custom CA script, Sectigo (coming soon).
|
||||
|
||||
**Targets:** NGINX, Apache, HAProxy, Traefik, Caddy, Envoy, IIS (local PowerShell or WinRM proxy), Postfix, Dovecot, F5 BIG-IP (coming soon).
|
||||
|
||||
See [Connector Reference](connectors.md) for configuration details on every issuer and target.
|
||||
+227
-23
@@ -7,7 +7,7 @@ Complete reference of all features shipped in the V2 release (as of March 2026).
|
||||
## API Surface
|
||||
|
||||
### Overview
|
||||
- **97 endpoints** across 21 resource domains under `/api/v1/` + `/.well-known/est/`
|
||||
- **99 endpoints** across 23 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
|
||||
@@ -78,7 +78,7 @@ curl -H "$AUTH" "$SERVER/api/v1/certificates?expires_before=2026-04-24T00:00:00Z
|
||||
|
||||
| Domain | Endpoints | Key Operations |
|
||||
|--------|-----------|-----------------|
|
||||
| **Certificates** | 11 | List, create, get, update (archive), versions, deployments, trigger renewal, trigger deployment, revoke |
|
||||
| **Certificates** | 13 | List, create, get, update (archive), versions, deployments, trigger renewal, trigger deployment, revoke, export (PEM/PKCS#12) |
|
||||
| **CRL & OCSP** | 3 | JSON CRL, DER CRL per issuer, OCSP responder |
|
||||
| **Issuers** | 6 | List, create, get, update, delete, test connection |
|
||||
| **Targets** | 5 | List, create, get, update, delete |
|
||||
@@ -96,6 +96,7 @@ curl -H "$AUTH" "$SERVER/api/v1/certificates?expires_before=2026-04-24T00:00:00Z
|
||||
| **Stats** | 5 | Dashboard summary, certificates by status, expiration timeline, job trends, issuance rate |
|
||||
| **Metrics** | 2 | JSON metrics (gauges, counters, uptime), Prometheus exposition format |
|
||||
| **Verification** | 2 | Submit verification result, get verification status |
|
||||
| **Digest** | 2 | Preview HTML digest, send digest immediately |
|
||||
| **EST (RFC 7030)** | 4 | CA certs (PKCS#7), simple enrollment, re-enrollment, CSR attributes |
|
||||
| **Health** | 4 | Health check, readiness check, auth info, auth check |
|
||||
|
||||
@@ -218,34 +219,86 @@ curl $SERVER/api/v1/ocsp/iss-local/ABC123DEF456
|
||||
|
||||
---
|
||||
|
||||
## Certificate Export
|
||||
|
||||
Operators need to export certificates for use in third-party systems or for compliance audits. certctl provides two export formats: PEM (cert + chain, JSON or file download) and PKCS#12 (cert + chain in a passwordless bundle for compatibility with systems like Java keystores and Windows certificate stores).
|
||||
|
||||
**Important:** Private keys are never exported — they remain on agents where they were generated. This is a core security property. Exports only bundle the public certificate material (cert + chain).
|
||||
|
||||
```bash
|
||||
# Export as PEM (returns JSON with base64-encoded data + chain)
|
||||
curl -H "$AUTH" "$SERVER/api/v1/certificates/mc-api-prod/export/pem"
|
||||
# {"certificate_pem":"-----BEGIN CERTIFICATE-----\n...", "chain_pem":"-----BEGIN CERTIFICATE-----\n..."}
|
||||
|
||||
# Export as PKCS#12 file (binary download, no password)
|
||||
curl -H "$AUTH" "$SERVER/api/v1/certificates/mc-api-prod/export/pkcs12" > cert.p12
|
||||
|
||||
# Via CLI
|
||||
certctl-cli certs export mc-api-prod --format pem --out cert.pem
|
||||
certctl-cli certs export mc-api-prod --format pkcs12 --out cert.p12
|
||||
```
|
||||
|
||||
| Field | Details |
|
||||
|-------|---------|
|
||||
| **Formats** | PEM (text, cert + chain), PKCS#12 (binary, cert + chain, passwordless) |
|
||||
| **Private Key Inclusion** | Never — private keys remain on agents |
|
||||
| **Audit Trail** | All exports recorded with actor, timestamp, export format |
|
||||
| **API Endpoints** | `GET /api/v1/certificates/{id}/export/pem`, `POST /api/v1/certificates/{id}/export/pkcs12` |
|
||||
| **GUI** | Export PEM and Export PKCS#12 buttons on certificate detail page |
|
||||
|
||||
---
|
||||
|
||||
## Certificate Profiles
|
||||
|
||||
### Profile Model
|
||||
Named enrollment profiles defining certificate issuance constraints. Profiles prevent drift — without them, different teams might issue certs with inconsistent key sizes, TTLs, or key algorithms. A profile says "all certs in this category must use ECDSA P-256, max 90-day TTL, serverAuth EKU only."
|
||||
Named enrollment profiles defining certificate issuance constraints. Profiles prevent drift — without them, different teams might issue certs with inconsistent key sizes, TTLs, or key algorithms. A profile says "all certs in this category must use ECDSA P-256, max 90-day TTL, serverAuth and clientAuth EKUs only."
|
||||
|
||||
Profiles also support **Extended Key Usage (EKU)** constraints, enabling S/MIME and device certificates. Common EKUs:
|
||||
- `serverAuth` — TLS server certificates (HTTPS, mail servers)
|
||||
- `clientAuth` — TLS client certificates (mutual TLS, device auth)
|
||||
- `emailProtection` — S/MIME signing and encryption
|
||||
- `codeSigning` — Code signing and software updates
|
||||
- `timeStamping` — Trusted timestamps
|
||||
|
||||
```bash
|
||||
# Create a profile enforcing short-lived certs with ECDSA keys
|
||||
# Create a TLS profile
|
||||
curl -X POST -H "$AUTH" -H "$CT" $SERVER/api/v1/profiles -d '{
|
||||
"name": "Short-Lived Service Mesh",
|
||||
"name": "Standard TLS",
|
||||
"allowed_key_algorithms": ["ECDSA"],
|
||||
"max_ttl_hours": 1,
|
||||
"max_ttl_hours": 2160,
|
||||
"allowed_ekus": ["serverAuth"]
|
||||
}'
|
||||
|
||||
# Create an S/MIME profile
|
||||
curl -X POST -H "$AUTH" -H "$CT" $SERVER/api/v1/profiles -d '{
|
||||
"name": "S/MIME Email",
|
||||
"allowed_key_algorithms": ["RSA", "ECDSA"],
|
||||
"max_ttl_hours": 8760,
|
||||
"allowed_ekus": ["emailProtection"]
|
||||
}'
|
||||
|
||||
# Create a multi-purpose profile
|
||||
curl -X POST -H "$AUTH" -H "$CT" $SERVER/api/v1/profiles -d '{
|
||||
"name": "Multi-Purpose",
|
||||
"allowed_key_algorithms": ["ECDSA"],
|
||||
"max_ttl_hours": 2160,
|
||||
"allowed_ekus": ["serverAuth", "clientAuth"]
|
||||
}'
|
||||
|
||||
# Assign profile to a certificate
|
||||
curl -X PUT -H "$AUTH" -H "$CT" $SERVER/api/v1/certificates/mc-api-prod -d '{
|
||||
"profile_id": "prof-short-lived"
|
||||
"profile_id": "prof-standard-tls"
|
||||
}'
|
||||
|
||||
# List all profiles
|
||||
curl -H "$AUTH" "$SERVER/api/v1/profiles" | jq '.data[] | {id, name, max_ttl_hours, allowed_key_algorithms}'
|
||||
curl -H "$AUTH" "$SERVER/api/v1/profiles" | jq '.data[] | {id, name, max_ttl_hours, allowed_key_algorithms, allowed_ekus}'
|
||||
|
||||
# Get profile details
|
||||
curl -H "$AUTH" "$SERVER/api/v1/profiles/prof-standard-tls" | jq .
|
||||
|
||||
# Update profile constraints
|
||||
curl -X PUT -H "$AUTH" -H "$CT" $SERVER/api/v1/profiles/prof-standard-tls -d '{
|
||||
"name": "Standard TLS", "max_ttl_hours": 2160, "allowed_key_algorithms": ["RSA", "ECDSA"]
|
||||
"name": "Standard TLS", "max_ttl_hours": 2160, "allowed_key_algorithms": ["RSA", "ECDSA"], "allowed_ekus": ["serverAuth"]
|
||||
}'
|
||||
```
|
||||
|
||||
@@ -255,14 +308,22 @@ curl -X PUT -H "$AUTH" -H "$CT" $SERVER/api/v1/profiles/prof-standard-tls -d '{
|
||||
| **Name** | Human-readable profile name |
|
||||
| **Allowed Key Algorithms** | RSA, ECDSA, Ed25519 with minimum key sizes (e.g., RSA 2048+, ECDSA P-256+) |
|
||||
| **Max TTL** | Maximum certificate lifetime (days or duration) |
|
||||
| **Allowed EKUs** | Extended key usage OIDs (serverAuth, clientAuth, etc.) |
|
||||
| **Allowed EKUs** | Extended key usage OIDs (serverAuth, clientAuth, emailProtection, codeSigning, timeStamping) |
|
||||
| **Required SANs** | Mandatory Subject Alternative Names (patterns or fixed values) |
|
||||
| **Short-Lived Support** | TTL < 1 hour triggers CRL/OCSP exemption |
|
||||
|
||||
### GUI Management
|
||||
- Full CRUD page with profile details
|
||||
- Crypto constraint badges visible in list view
|
||||
- EKU constraint badges visible in list view (serverAuth, clientAuth, emailProtection, etc.)
|
||||
- Profile assignment dropdown on certificate detail
|
||||
- S/MIME profile creation wizard with email SAN configuration
|
||||
|
||||
### S/MIME Support
|
||||
When a profile specifies `emailProtection` EKU, certctl adapts the issuance flow for email certificates:
|
||||
- **SAN handling** — email addresses in SANs are formatted as `rfc822Name` (not DNS names)
|
||||
- **Key usage** — S/MIME certs use `DigitalSignature | ContentCommitment` instead of the TLS default `DigitalSignature | KeyEncipherment`
|
||||
- **Agent CSR generation** — agents correctly distinguish DNS SANs from email SANs based on profile EKU
|
||||
- **Issuer constraints** — Local CA and other issuers thread EKUs through the signing pipeline
|
||||
|
||||
---
|
||||
|
||||
@@ -453,6 +514,148 @@ export CERTCTL_PAGERDUTY_SEVERITY="critical"
|
||||
|
||||
---
|
||||
|
||||
## ACME Renewal Information (ARI, RFC 9702)
|
||||
|
||||
Instead of using fixed renewal thresholds (renew 30 days before expiry), ACME ARI lets the CA tell certctl exactly when to renew. This is useful for distributing renewal load across maintenance windows and coordinating mass-revocation scenarios.
|
||||
|
||||
**How it works:**
|
||||
|
||||
```bash
|
||||
# Enable ARI on your ACME issuer
|
||||
export CERTCTL_ACME_ARI_ENABLED=true
|
||||
|
||||
# Certificates now query the ARI endpoint for suggested renewal windows
|
||||
# If the CA doesn't support ARI (404), certctl falls back to threshold-based renewal
|
||||
```
|
||||
|
||||
| Field | Details |
|
||||
|-------|---------|
|
||||
| **Protocol** | ACME Renewal Information (RFC 9702) |
|
||||
| **Cert ID Computation** | base64url(SHA-256(DER cert)) |
|
||||
| **Suggested Window** | Start and end times provided by CA |
|
||||
| **Renewal Timing** — If current time is after window start, renew immediately. Otherwise, wait until start time. |
|
||||
| **Fallback** | 404 from ARI endpoint triggers automatic fallback to threshold-based renewal |
|
||||
| **Configuration** | `CERTCTL_ACME_ARI_ENABLED=true` on ACME issuer config |
|
||||
| **Supported CAs** | Let's Encrypt (v2.1.0+), Sectigo, others gradually adopting |
|
||||
|
||||
**Benefits:**
|
||||
|
||||
- **Load Distribution** — CA specifies renewal window to avoid thundering herd spikes
|
||||
- **Coordination** — Support for mass revocation scenarios where CA controls timing
|
||||
- **No Over-Renewal** — Avoid unnecessary early renewals that waste your CA's capacity
|
||||
|
||||
---
|
||||
|
||||
## Scheduled Certificate Digest Emails
|
||||
|
||||
Scheduled HTML digest emails with certificate stats, expiration timeline, job health, and agent fleet overview. Useful for daily ops briefings and compliance reporting.
|
||||
|
||||
```bash
|
||||
# Configure SMTP
|
||||
export CERTCTL_SMTP_HOST=smtp.example.com
|
||||
export CERTCTL_SMTP_PORT=587
|
||||
export CERTCTL_SMTP_USERNAME=admin@example.com
|
||||
export CERTCTL_SMTP_PASSWORD=your-app-password
|
||||
export CERTCTL_SMTP_FROM_ADDRESS=certctl@example.com
|
||||
|
||||
# Enable digest
|
||||
export CERTCTL_DIGEST_ENABLED=true
|
||||
export CERTCTL_DIGEST_INTERVAL=24h
|
||||
export CERTCTL_DIGEST_RECIPIENTS=ops@example.com,security@example.com
|
||||
```
|
||||
|
||||
| Feature | Details |
|
||||
|---------|---------|
|
||||
| **Scheduler Loop** | 7th background loop, default 24-hour interval (configurable: 12h, 7d, etc.) |
|
||||
| **Startup Behavior** | Does NOT run on startup; waits for first scheduled tick |
|
||||
| **Operation Timeout** | 5 minutes per digest generation + send |
|
||||
| **Idempotency** — `sync/atomic.Bool` guard prevents concurrent digest executions |
|
||||
| **HTML Template** | Responsive email with stats grid (total, expiring, expired, agents), jobs summary (30-day), expiring certs table with color-coded urgency (7/14/30 days) |
|
||||
| **Recipients** | Comma-separated email addresses. Falls back to certificate owner emails if none configured. |
|
||||
| **API Endpoints** — `GET /api/v1/digest/preview` (HTML preview), `POST /api/v1/digest/send` (trigger immediately) |
|
||||
| **Configuration** — `CERTCTL_DIGEST_ENABLED`, `CERTCTL_DIGEST_INTERVAL` (default 24h), `CERTCTL_DIGEST_RECIPIENTS` |
|
||||
|
||||
**Digest Contents:**
|
||||
|
||||
- **Certificate Stats** — Total, active, expiring soon, expired, revoked
|
||||
- **Job Health** — Completed, failed (last 30 days)
|
||||
- **Agent Fleet** — Total agents online, offline, version distribution
|
||||
- **Expiring Certificates** — Table with CN, SANs, days remaining, owner, status badges
|
||||
|
||||
**Use Cases:**
|
||||
|
||||
- Daily ops briefing for certificate inventory health
|
||||
- Compliance reporting (audit trail + digest archive)
|
||||
- Stakeholder visibility (automated newsletter)
|
||||
|
||||
---
|
||||
|
||||
## Helm Chart for Kubernetes
|
||||
|
||||
Production-ready Helm chart for Kubernetes deployments with secure defaults and comprehensive configurability.
|
||||
|
||||
### Chart Components
|
||||
|
||||
| Component | Details |
|
||||
|-----------|---------|
|
||||
| **Server Deployment** | Configurable replicas (default 2), liveness/readiness probes, security context (non-root, read-only rootfs), resource limits, graceful shutdown |
|
||||
| **PostgreSQL StatefulSet** | Primary + replica, persistent volumes with configurable storage class/size (default 10Gi), automatic backup (via init container or sidecarsynchronous |
|
||||
| **Agent DaemonSet** | One agent per infrastructure node, key storage volume (agent_keys), server discovery via internal DNS |
|
||||
| **ConfigMap** | Issuer, target, and scheduler configuration; all certctl env vars exposed |
|
||||
| **Secret** — API key, database password, SMTP credentials (base64-encoded) |
|
||||
| **Ingress** — Optional with TLS, configurable hostname and certificate (via cert-manager or manual) |
|
||||
| **ServiceAccount** — RBAC with configurable annotations for Kubernetes audit logging |
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Install with custom values
|
||||
helm install certctl deploy/helm/certctl/ \
|
||||
--namespace certctl --create-namespace \
|
||||
--set server.auth.apiKey="your-secure-key" \
|
||||
--set postgresql.auth.password="your-db-password" \
|
||||
--set ingress.enabled=true \
|
||||
--set ingress.hosts[0].host="certctl.example.com" \
|
||||
--set ingress.annotations."cert-manager\.io/cluster-issuer"="letsencrypt-prod"
|
||||
```
|
||||
|
||||
### Key Values
|
||||
|
||||
| Value | Default | Description |
|
||||
|-------|---------|-------------|
|
||||
| `server.replicaCount` | 2 | Number of server replicas |
|
||||
| `server.auth.apiKey` | — | (required) API key for authentication |
|
||||
| `postgresql.auth.password` | — | (required) PostgreSQL password |
|
||||
| `postgresql.storage.size` | 10Gi | Database volume size |
|
||||
| `ingress.enabled` | false | Enable Ingress for public access |
|
||||
| `ingress.hosts[0].host` | certctl.example.com | Primary hostname |
|
||||
| `ingress.tls.enabled` | true | TLS on Ingress (requires cert-manager) |
|
||||
| `agent.enabled` | true | Deploy agent DaemonSet |
|
||||
| `smtp.enabled` | false | Enable SMTP for digest emails |
|
||||
| `smtp.host` | — | SMTP server hostname |
|
||||
|
||||
### Security Defaults
|
||||
|
||||
- **Non-root containers** — Server and agent run as unprivileged user
|
||||
- **Read-only filesystem** — Root filesystem mounted read-only (except /tmp)
|
||||
- **Network policies** — Optional KubernetesNetworkPolicy to restrict traffic
|
||||
- **Secrets** — API keys and passwords stored in K8s Secrets, never in ConfigMaps or environment defaults
|
||||
- **RBAC** — ServiceAccount with minimal required permissions
|
||||
|
||||
### Upgrade Path
|
||||
|
||||
```bash
|
||||
# Upgrade to a new certctl release
|
||||
helm upgrade certctl deploy/helm/certctl/ \
|
||||
--namespace certctl \
|
||||
-f my-values.yaml
|
||||
|
||||
# Rollback if needed
|
||||
helm rollback certctl [REVISION]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Agent Fleet
|
||||
|
||||
Agents are lightweight Go binaries deployed on your servers that handle the last mile — generating private keys locally, submitting CSRs, and deploying signed certificates to web servers. The control plane never touches private keys or initiates outbound connections, keeping your security perimeter intact.
|
||||
@@ -848,7 +1051,7 @@ curl -X POST -H "$AUTH" -H "$CT" $SERVER/api/v1/jobs/j-abc123/approve -d '{"reas
|
||||
3. **Approve** → `POST /api/v1/jobs/{id}/approve` → Job → `Running`
|
||||
4. **Reject** → `POST /api/v1/jobs/{id}/reject` + reason → Job → `Cancelled`
|
||||
|
||||
### Background Scheduler (6 loops)
|
||||
### Background Scheduler (7 loops)
|
||||
| Loop | Interval | Task |
|
||||
|------|----------|------|
|
||||
| **Renewal Checker** | 1 hour | Scan policies; trigger renewals if cert expires soon |
|
||||
@@ -857,6 +1060,7 @@ curl -X POST -H "$AUTH" -H "$CT" $SERVER/api/v1/jobs/j-abc123/approve -d '{"reas
|
||||
| **Notification Processor** | 1 minute | Send queued notifications (email, Slack, webhook, etc.) |
|
||||
| **Short-Lived Cleanup** | 30 seconds | Audit short-lived credential expirations |
|
||||
| **Network Scanner** | 6 hours | Scan enabled network targets; discover TLS certificates |
|
||||
| **Digest Emailer** | 24 hours | Send HTML certificate digest email to configured recipients |
|
||||
|
||||
All loops have configurable intervals via environment variables (`CERTCTL_SCHEDULER_*_INTERVAL`).
|
||||
|
||||
@@ -1064,7 +1268,7 @@ The web dashboard is the primary operational interface for certctl. Built with *
|
||||
### Docker Compose Deployment
|
||||
- **Services** — PostgreSQL 16, certctl server, agent
|
||||
- **Health Checks** — On all services (server health check, database readiness)
|
||||
- **Seed Data** — Demo dataset with 15 certs, 5 agents, 5 targets, policies, audit events
|
||||
- **Seed Data** — Demo dataset with 35 certs across 5 issuers, 8 agents, 8 targets, 90 days of job history, discovery data, network scans, policies, audit events
|
||||
- **Credentials** — Environment variables in `.env` file; app.key for API key
|
||||
|
||||
### PostgreSQL Schema
|
||||
@@ -1082,11 +1286,11 @@ The web dashboard is the primary operational interface for certctl. Built with *
|
||||
- **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
|
||||
- **Integration Tests** — End-to-end workflows (issuance→renewal→deployment)
|
||||
- **Unit Tests** — Extensive coverage across service, handler, middleware, domain, and connector layers
|
||||
- **Integration Tests** — End-to-end workflows (issuance→renewal→deployment) against live Docker Compose environment
|
||||
- **Negative Tests** — Malformed input, nonexistent resources, error conditions
|
||||
- **Frontend Tests** — 86 Vitest tests (API client, utilities, stats/metrics, full endpoint coverage)
|
||||
- **Total Coverage** — 900+ tests (Go + frontend combined)
|
||||
- **Frontend Tests** — Vitest suite covering API client, utilities, stats/metrics, and full endpoint coverage
|
||||
- **CI Gates** — Per-layer coverage thresholds (service 60%, handler 60%, domain 40%, middleware 50%), race detection, static analysis, vulnerability scanning
|
||||
|
||||
### Licensing
|
||||
- **License** — Business Source License 1.1 (BSL 1.1)
|
||||
@@ -1265,8 +1469,8 @@ Each guide includes an evidence summary table mapping specific criteria to certc
|
||||
| **Bulk revocation** | ✗ | ✓ | Planned V3 (paid) |
|
||||
| **Certificate health scores** | ✗ | ✓ | Planned V3 |
|
||||
| **Compliance scoring** | ✗ | ✓ | Planned V3 |
|
||||
| **DigiCert issuer** | ✗ | ✓ | Planned V3 |
|
||||
| **CT Log monitoring** | ✗ | ✓ | Planned V3 |
|
||||
| **DigiCert issuer** | ✗ | ✓ | Implemented (Beta) |
|
||||
| **Vault PKI issuer** | ✗ | ✓ | Implemented (Beta) |
|
||||
|
||||
---
|
||||
|
||||
@@ -1274,10 +1478,10 @@ Each guide includes an evidence summary table mapping specific criteria to certc
|
||||
|
||||
| Category | Count |
|
||||
|----------|-------|
|
||||
| **API Endpoints** | 95 (under /api/v1/ + /.well-known/est/) |
|
||||
| **API Endpoints** | 97 (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) |
|
||||
| **Issuer Connectors** | 6 (Local CA, ACME, step-ca, OpenSSL, Vault PKI, DigiCert) |
|
||||
| **Target Connectors** | 10 (9 impl: NGINX, Apache, HAProxy, Traefik, Caddy, Envoy, IIS, Postfix, Dovecot; 1 stub: F5) |
|
||||
| **Notifier Channels** | 6 (Email, Webhook, Slack, Teams, PagerDuty, OpsGenie) |
|
||||
| **Job Types** | 4 (Issuance, Renewal, Deployment, Validation) |
|
||||
| **Job States** | 7 (Pending, AwaitingCSR, AwaitingApproval, Running, Completed, Failed, Cancelled) |
|
||||
@@ -1288,6 +1492,6 @@ Each guide includes an evidence summary table mapping specific criteria to certc
|
||||
| **MCP Tools** | 76 (16 resource domains) |
|
||||
| **CLI Subcommands** | 10 |
|
||||
| **Database Tables** | 19 |
|
||||
| **Test Suite** | 900+ tests (Go backend + frontend) |
|
||||
| **Test Suite** | Extensively tested with CI-enforced coverage gates |
|
||||
| **Environment Variables** | 41+ configuration options |
|
||||
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
# Migrate from acme.sh to certctl
|
||||
|
||||
You use acme.sh to automate Let's Encrypt renewal across multiple servers. It works — but without centralized visibility, deployment verification, or policy enforcement.
|
||||
|
||||
This guide walks through moving your acme.sh workload to certctl while keeping your existing DNS provider setup.
|
||||
|
||||
## Why Migrate
|
||||
|
||||
**acme.sh strength:** Lightweight agent, works everywhere, integrates with any DNS provider via shell script hooks.
|
||||
|
||||
**acme.sh limitations:**
|
||||
- No inventory visibility — certificates scattered across servers, no unified view of expiry dates or renewal status
|
||||
- No deployment verification — cron job succeeds even if cert doesn't actually take effect on the service
|
||||
- No policy enforcement — no way to require approval, audit who renewed what, or prevent misconfigurations
|
||||
- No multi-server orchestration — each server manages its own renewals; no way to batch test or rollback
|
||||
|
||||
certctl adds a control plane that sees all your certificates, deploys with verification, enforces policy, and provides a complete audit trail. You keep the DNS-01 challenge scripts you already have.
|
||||
|
||||
## What You Keep
|
||||
|
||||
- **Existing certificates** — discovered automatically during migration, claimed in the dashboard
|
||||
- **DNS provider scripts** — acme.sh's `dns_*` hooks are shell-script compatible with certctl's DNS-01 implementation
|
||||
- **Same Let's Encrypt account** — ACME issuer in certctl uses the same account and email
|
||||
|
||||
## Migration Steps
|
||||
|
||||
### 1. Deploy certctl Server
|
||||
|
||||
Start with Docker Compose (5 minutes):
|
||||
|
||||
```bash
|
||||
git clone https://github.com/shankar0123/certctl.git
|
||||
cd certctl/deploy
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Access the dashboard at `http://localhost:8443` with API key from `.env` file.
|
||||
|
||||
### 2. Deploy Agents
|
||||
|
||||
On each server running acme.sh certs, install the certctl agent:
|
||||
|
||||
```bash
|
||||
curl -sSL https://raw.githubusercontent.com/shankar0123/certctl/master/install-agent.sh | bash
|
||||
# Prompted for server URL and API key
|
||||
```
|
||||
|
||||
Or manually:
|
||||
|
||||
```bash
|
||||
# Download and install agent binary
|
||||
wget https://github.com/shankar0123/certctl/releases/download/v2.1.0/certctl-agent-linux-amd64
|
||||
chmod +x certctl-agent-linux-amd64
|
||||
sudo mv certctl-agent-linux-amd64 /usr/local/bin/certctl-agent
|
||||
|
||||
# Create systemd unit
|
||||
sudo tee /etc/systemd/system/certctl-agent.service > /dev/null <<EOF
|
||||
[Unit]
|
||||
Description=certctl Agent
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/local/bin/certctl-agent
|
||||
Environment="CERTCTL_SERVER_URL=https://certctl.internal:8443"
|
||||
Environment="CERTCTL_API_KEY=your-api-key-here"
|
||||
Environment="CERTCTL_DISCOVERY_DIRS=~/.acme.sh"
|
||||
Restart=always
|
||||
RestartSec=10s
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now certctl-agent
|
||||
```
|
||||
|
||||
### 3. Discover Existing acme.sh Certificates
|
||||
|
||||
acme.sh stores certificates in `~/.acme.sh/<domain>/` (or `/etc/acme.sh/` if installed system-wide).
|
||||
|
||||
When you start the agent with `CERTCTL_DISCOVERY_DIRS` pointing to those directories, it scans for existing PEM/DER certificates and reports fingerprints to the control plane. The dashboard's **Discovery** page shows what was found.
|
||||
|
||||
Example agent systemd service (using home directory):
|
||||
|
||||
```bash
|
||||
Environment="CERTCTL_DISCOVERY_DIRS=/home/user/.acme.sh"
|
||||
```
|
||||
|
||||
Or for system-wide acme.sh:
|
||||
|
||||
```bash
|
||||
Environment="CERTCTL_DISCOVERY_DIRS=/etc/acme.sh"
|
||||
```
|
||||
|
||||
### 4. Claim Discovered Certificates
|
||||
|
||||
In the **Discovery** page:
|
||||
1. Review the "Unmanaged" certificates found by the agent
|
||||
2. Click **Claim** on each acme.sh certificate
|
||||
3. Enter the managed certificate ID to link it (e.g., `mc-api-prod`)
|
||||
|
||||
Once claimed, the certificate appears in the main **Certificates** page with ownership, renewal history, and deployment status.
|
||||
|
||||
### 5. Create an ACME Issuer
|
||||
|
||||
In **Issuers** → **+ New Issuer:**
|
||||
|
||||
1. Select **ACME** from the issuer type grid
|
||||
2. Fill in the type-specific fields: name, directory URL (`https://acme-v02.api.letsencrypt.org/directory`), and config
|
||||
|
||||
Or configure via environment variables:
|
||||
```bash
|
||||
export CERTCTL_ACME_DIRECTORY_URL=https://acme-v02.api.letsencrypt.org/directory
|
||||
export CERTCTL_ACME_EMAIL=your-email@example.com # same as your acme.sh account
|
||||
export CERTCTL_ACME_CHALLENGE_TYPE=dns-01
|
||||
```
|
||||
|
||||
### 6. Adapt Your DNS Provider Scripts
|
||||
|
||||
acme.sh uses `dns_*` hooks (e.g., `dns_cloudflare`) with predictable argument patterns. certctl's DNS-01 uses the same pattern, so your scripts often work with zero changes.
|
||||
|
||||
**acme.sh pattern:**
|
||||
```bash
|
||||
# acme.sh invokes: dns_cloudflare_add "domain" "record" "value"
|
||||
dns_cloudflare_add() {
|
||||
local full_domain=$1
|
||||
local record_name=$2
|
||||
local record_value=$3
|
||||
# ... DNS API call to create TXT record ...
|
||||
}
|
||||
```
|
||||
|
||||
**certctl pattern:**
|
||||
```bash
|
||||
# certctl invokes: /path/to/dns-present-script
|
||||
# Scripts receive environment variables:
|
||||
#!/bin/bash
|
||||
# CERTCTL_DNS_DOMAIN — domain name (e.g., "example.com")
|
||||
# CERTCTL_DNS_FQDN — full record name (e.g., "_acme-challenge.example.com")
|
||||
# CERTCTL_DNS_VALUE — TXT record value (key authorization digest)
|
||||
# CERTCTL_DNS_TOKEN — ACME challenge token
|
||||
# Create TXT record at "${CERTCTL_DNS_FQDN}" with value "${CERTCTL_DNS_VALUE}"
|
||||
```
|
||||
|
||||
**Example: Cloudflare DNS-01 adapter**
|
||||
|
||||
If you have an acme.sh Cloudflare hook, adapt it:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# /etc/certctl/dns/cloudflare-present.sh
|
||||
set -e
|
||||
|
||||
# certctl passes these environment variables:
|
||||
# CERTCTL_DNS_DOMAIN — domain name
|
||||
# CERTCTL_DNS_FQDN — full record name (e.g., "_acme-challenge.example.com")
|
||||
# CERTCTL_DNS_VALUE — TXT record value
|
||||
# CERTCTL_DNS_TOKEN — ACME challenge token
|
||||
|
||||
# Call your existing Cloudflare API (example using curl)
|
||||
curl -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \
|
||||
-H "X-Auth-Email: ${CF_EMAIL}" \
|
||||
-H "X-Auth-Key: ${CF_KEY}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"type\":\"TXT\",\"name\":\"${CERTCTL_DNS_FQDN}\",\"content\":\"${CERTCTL_DNS_VALUE}\"}"
|
||||
|
||||
echo "Created ${CERTCTL_DNS_FQDN}"
|
||||
```
|
||||
|
||||
DNS cleanup:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# /etc/certctl/dns/cloudflare-cleanup.sh
|
||||
|
||||
# certctl passes these environment variables:
|
||||
# CERTCTL_DNS_DOMAIN — domain name
|
||||
# CERTCTL_DNS_FQDN — full record name (e.g., "_acme-challenge.example.com")
|
||||
# CERTCTL_DNS_VALUE — TXT record value
|
||||
# CERTCTL_DNS_TOKEN — ACME challenge token
|
||||
|
||||
# Query and delete the TXT record
|
||||
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${RECORD_ID}" \
|
||||
-H "X-Auth-Email: ${CF_EMAIL}" \
|
||||
-H "X-Auth-Key: ${CF_KEY}"
|
||||
```
|
||||
|
||||
Configure the ACME issuer via environment variables:
|
||||
|
||||
```bash
|
||||
export CERTCTL_ACME_DIRECTORY_URL=https://acme-v02.api.letsencrypt.org/directory
|
||||
export CERTCTL_ACME_EMAIL=your-email@example.com
|
||||
export CERTCTL_ACME_CHALLENGE_TYPE=dns-01
|
||||
export CERTCTL_ACME_DNS_PRESENT_SCRIPT=/etc/certctl/dns/cloudflare-present.sh
|
||||
export CERTCTL_ACME_DNS_CLEANUP_SCRIPT=/etc/certctl/dns/cloudflare-cleanup.sh
|
||||
```
|
||||
|
||||
Or create the issuer through the dashboard: **Issuers** → **+ New Issuer** → select **ACME** → fill in the config fields.
|
||||
|
||||
### 7. Create Renewal Policies
|
||||
|
||||
In **Policies** → **+ New Policy:**
|
||||
|
||||
- **Name:** e.g., "ACME DNS-01 Policy"
|
||||
- **Type:** `expiration_window` (enforces renewal thresholds)
|
||||
- **Severity:** `high`
|
||||
- **Config:** set your renewal window (default: 30 days before expiry)
|
||||
|
||||
Renewal scheduling is driven by the certificate's assigned profile and issuer. Policies add enforcement guardrails on top.
|
||||
|
||||
### 8. Phase Out acme.sh Cron
|
||||
|
||||
Once you verify renewals work via certctl (manually trigger one in the dashboard first), remove the acme.sh cron job:
|
||||
|
||||
```bash
|
||||
# Remove acme.sh from crontab
|
||||
crontab -e
|
||||
# Delete the line: "0 0 * * * /home/user/.acme.sh/acme.sh --cron --home /home/user/.acme.sh"
|
||||
|
||||
# OR disable the cron service if installed
|
||||
sudo systemctl disable acme-renew.timer
|
||||
```
|
||||
|
||||
## DNS Script Compatibility
|
||||
|
||||
Most acme.sh DNS provider hooks need only minor changes:
|
||||
|
||||
| acme.sh | certctl |
|
||||
|---------|---------|
|
||||
| Called on every renewal | Called once per challenge window |
|
||||
| Receives: domain, record name, record value as arguments | Receives: `CERTCTL_DNS_DOMAIN`, `CERTCTL_DNS_FQDN`, `CERTCTL_DNS_VALUE`, `CERTCTL_DNS_TOKEN` as environment variables |
|
||||
| Must support multiple concurrent records | Same — cleanup removes the specific token |
|
||||
| Environment variables for credentials | Same — pass via agent systemd `Environment=` or `.env` file |
|
||||
|
||||
**Real example:** If you use Route53, acme.sh's `dns_aws` hook submits via AWS CLI. Adapt it to use `${CERTCTL_DNS_FQDN}` and `${CERTCTL_DNS_VALUE}` environment variables instead of positional arguments, and it works with certctl's DNS-01.
|
||||
|
||||
## Coexistence Period
|
||||
|
||||
During migration, run both acme.sh and certctl in parallel:
|
||||
|
||||
1. Keep acme.sh cron running (low overhead, serves as fallback)
|
||||
2. Configure certctl policies and test renewal on 1-2 non-critical domains
|
||||
3. Monitor certctl's audit trail and deployment logs
|
||||
4. Once confident, disable acme.sh cron on those domains
|
||||
5. Roll out to remaining domains
|
||||
|
||||
This way, if certctl renewal fails, acme.sh's cron still renews the cert (you'll see duplicate renewals in the audit trail, but no gap).
|
||||
|
||||
## Next: DNS-PERSIST-01 (Zero-Touch Renewals)
|
||||
|
||||
After migrating to certctl + DNS-01, consider upgrading to **DNS-PERSIST-01**. Instead of creating/deleting DNS records on every renewal, you create one persistent TXT record at `_validation-persist.<domain>` that never changes. Let's Encrypt then validates against that standing record forever.
|
||||
|
||||
Benefits:
|
||||
- **Zero operational overhead per renewal** — no DNS API calls during renewal
|
||||
- **Auditable** — DNS record created once, visible to the team, never modified
|
||||
- **Vendor-agnostic** — works with any DNS provider that supports TXT records
|
||||
|
||||
To enable:
|
||||
|
||||
```bash
|
||||
export CERTCTL_ACME_CHALLENGE_TYPE=dns-persist-01
|
||||
export CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN=letsencrypt.org
|
||||
export CERTCTL_ACME_DNS_PRESENT_SCRIPT=/etc/certctl/dns/cloudflare-present.sh
|
||||
```
|
||||
|
||||
certctl automatically falls back to DNS-01 if the CA doesn't support dns-persist-01 yet.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Try the [Wildcard DNS-01 example](../examples/acme-wildcard-dns01/acme-wildcard-dns01.md) — a working docker-compose with Cloudflare hooks you can adapt for your DNS provider
|
||||
- See [Connector Reference](connectors.md) for advanced ACME options (EAB, ARI, custom timeouts)
|
||||
- See [Discovery Guide](concepts.md#certificate-discovery) for managing discovered certificates at scale
|
||||
- See all [Deployment Examples](./examples.md) for other scenarios (ACME+NGINX, private CA, step-ca, multi-issuer)
|
||||
@@ -0,0 +1,172 @@
|
||||
# Migrating from Certbot to certctl
|
||||
|
||||
You have 50 Let's Encrypt certificates across 10 servers, managed by a mix of Certbot cron jobs and manual renewals. Certbot handles issuance, but you lack inventory visibility, centralized alerting, and audit trails. This guide walks you through moving to certctl while keeping your existing certificates and ACME account.
|
||||
|
||||
## Why Migrate
|
||||
|
||||
Certbot renews certs in isolation. If a renewal fails on one server, you don't know until the cert expires. certctl gives you a single pane of glass: see all certs across all servers, get alerts 30/14/7 days before expiry, track who renewed what when, and verify each deployment succeeded via TLS fingerprint validation.
|
||||
|
||||
## What You Keep
|
||||
|
||||
- Your existing Certbot ACME account key and Let's Encrypt account
|
||||
- All issued certificates in `/etc/letsencrypt/live/`
|
||||
- Certbot's renewal history and hooks
|
||||
|
||||
You will not re-issue any certificates. certctl discovers them and takes over renewal scheduling.
|
||||
|
||||
## Step-by-Step Migration
|
||||
|
||||
### 1. Deploy certctl Control Plane
|
||||
|
||||
Option A: Docker Compose (quickest for evaluation)
|
||||
```bash
|
||||
cd /opt/certctl
|
||||
docker compose up -d
|
||||
# Dashboard & API: http://localhost:8443
|
||||
# Default API key in logs (grep CERTCTL_API_KEY docker logs certctl-server)
|
||||
```
|
||||
|
||||
Option B: Kubernetes (Helm)
|
||||
```bash
|
||||
helm install certctl deploy/helm/certctl/ \
|
||||
--set auth.apiKey=YOUR_SECURE_KEY
|
||||
```
|
||||
|
||||
### 2. Deploy Agents to Each Server
|
||||
|
||||
On each of your 10 servers running Certbot:
|
||||
|
||||
```bash
|
||||
# Linux amd64 (adjust for your architecture)
|
||||
curl -sSL https://github.com/shankar0123/certctl/releases/download/v2.1.0/certctl-agent-linux-amd64 \
|
||||
-o /usr/local/bin/certctl-agent
|
||||
chmod +x /usr/local/bin/certctl-agent
|
||||
|
||||
# Create config
|
||||
sudo mkdir -p /etc/certctl /var/lib/certctl/keys
|
||||
sudo tee /etc/certctl/agent.env > /dev/null <<EOF
|
||||
CERTCTL_SERVER_URL=http://certctl-control-plane.example.com:8443
|
||||
CERTCTL_API_KEY=your-api-key-here
|
||||
CERTCTL_DISCOVERY_DIRS=/etc/letsencrypt/live
|
||||
CERTCTL_KEY_DIR=/var/lib/certctl/keys
|
||||
EOF
|
||||
sudo chmod 600 /etc/certctl/agent.env
|
||||
|
||||
# Start agent
|
||||
sudo systemctl start certctl-agent # if installed via script
|
||||
# OR manually:
|
||||
sudo certctl-agent --server https://... --api-key ... --discovery-dirs /etc/letsencrypt/live
|
||||
```
|
||||
|
||||
The agent will scan `/etc/letsencrypt/live/` and report all discovered certificates to the control plane.
|
||||
|
||||
### 3. Triage Discovered Certificates
|
||||
|
||||
In the certctl dashboard, go to **Discovery**:
|
||||
- See all discovered certs grouped by agent
|
||||
- Status shows "Unmanaged" for certificates not yet claimed
|
||||
- For each Certbot cert, click **Claim** and link it to managed inventory
|
||||
|
||||
The control plane now knows about all 50 certs and where they live.
|
||||
|
||||
### 4. Configure ACME Issuer
|
||||
|
||||
Go to **Issuers** → **+ New Issuer**:
|
||||
1. Select **ACME** from the issuer type grid
|
||||
2. Fill in the type-specific fields: name, directory URL (`https://acme-v02.api.letsencrypt.org/directory`), and any required config
|
||||
|
||||
Alternatively, configure via environment variables before starting the server:
|
||||
```bash
|
||||
export CERTCTL_ACME_DIRECTORY_URL=https://acme-v02.api.letsencrypt.org/directory
|
||||
export CERTCTL_ACME_EMAIL=your-email@example.com
|
||||
export CERTCTL_ACME_CHALLENGE_TYPE=http-01 # or dns-01 for wildcard certs
|
||||
```
|
||||
|
||||
For DNS-01, also set:
|
||||
```bash
|
||||
export CERTCTL_ACME_DNS_PRESENT_SCRIPT=/etc/certctl/dns/present.sh
|
||||
export CERTCTL_ACME_DNS_CLEANUP_SCRIPT=/etc/certctl/dns/cleanup.sh
|
||||
```
|
||||
|
||||
certctl uses the same Let's Encrypt account; no new credentials needed.
|
||||
|
||||
### 5. Create Renewal Policies
|
||||
|
||||
Go to **Policies** → **+ New Policy** to create enforcement rules:
|
||||
- Name: e.g., "ACME Renewal Policy"
|
||||
- Type: `expiration_window` (to enforce renewal thresholds)
|
||||
- Severity: `high`
|
||||
- Config: set your renewal threshold (default: 30 days before expiry)
|
||||
|
||||
Renewal scheduling is driven by the certificate's assigned profile and issuer. Policies add enforcement guardrails (key algorithm requirements, expiration windows, etc.).
|
||||
|
||||
### 6. Disable Certbot Cron, One Server at a Time
|
||||
|
||||
On the first server (start with a low-traffic one):
|
||||
|
||||
```bash
|
||||
# Stop Certbot renewal
|
||||
sudo systemctl disable certbot.timer
|
||||
sudo systemctl stop certbot.timer
|
||||
|
||||
# Or remove the cron job
|
||||
sudo rm /etc/cron.d/certbot # if managed by cron
|
||||
```
|
||||
|
||||
Monitor that server in the certctl dashboard. Certctl will renew the cert ~30 days before expiry.
|
||||
|
||||
### 7. Verify First Renewal Succeeds
|
||||
|
||||
Wait for the renewal to trigger (or manually trigger it in **Certificates** → select cert → **Renew**). Check the dashboard:
|
||||
- **Certificates** page: status transitions from `Active` to `Renewing` to `Active`
|
||||
- **Jobs** page: renewal job shows `Completed` status
|
||||
- **Verification** tab: TLS check confirms the new cert is deployed and live
|
||||
|
||||
After verifying, disable Certbot on the remaining 9 servers.
|
||||
|
||||
### 8. Enable Alerting
|
||||
|
||||
Configure notifiers via environment variables before starting the server:
|
||||
```bash
|
||||
# Example: Slack alerting
|
||||
export CERTCTL_SLACK_WEBHOOK_URL=https://hooks.slack.com/services/YOUR/WEBHOOK/URL
|
||||
docker compose up -d
|
||||
|
||||
# Or email alerting
|
||||
export CERTCTL_SMTP_HOST=smtp.gmail.com
|
||||
export CERTCTL_SMTP_PORT=587
|
||||
export CERTCTL_SMTP_USERNAME=your-email@gmail.com
|
||||
export CERTCTL_SMTP_PASSWORD=your-app-password
|
||||
export CERTCTL_SMTP_FROM_ADDRESS=certctl@example.com
|
||||
docker compose up -d
|
||||
|
||||
# Other options: CERTCTL_TEAMS_WEBHOOK_URL, CERTCTL_PAGERDUTY_ROUTING_KEY, CERTCTL_OPSGENIE_API_KEY
|
||||
```
|
||||
|
||||
Now you get 30/14/7-day warnings before any cert expires, across all 10 servers, in one place.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Renewal**: Agent polls certctl for work instead of Certbot cron triggering locally. Faster failure detection (agent heartbeat every 60 seconds vs. cron running once a day).
|
||||
- **Deployment**: certctl verifies post-deployment by probing the live TLS endpoint and comparing SHA-256 fingerprints. Catches reload failures silently.
|
||||
- **Audit Trail**: Every renewal, deployment, and alert is logged immutably. Answer "who renewed cert X when and why" within seconds.
|
||||
- **Alerting**: Threshold-based alerts to Slack/email/webhook 30/14/7 days before expiry, not when cert expires.
|
||||
|
||||
## Coexistence and Rollback
|
||||
|
||||
During migration, certctl and Certbot can run simultaneously. The agent will discover Certbot certs even while Certbot continues renewing them. Run both for a week to build confidence.
|
||||
|
||||
**If you need to rollback**: Re-enable Certbot cron on any server:
|
||||
```bash
|
||||
sudo systemctl enable certbot.timer
|
||||
sudo systemctl start certbot.timer
|
||||
```
|
||||
|
||||
certctl will stop renewing that cert when the policy is disabled. Certbot resumes as before. Your certificates and ACME account remain untouched.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Try the [ACME + NGINX example](../examples/acme-nginx/acme-nginx.md) — a working docker-compose you can run locally before deploying to production
|
||||
- Review the [Concepts Guide](./concepts.md) for terminology (profiles, policies, agents, jobs)
|
||||
- Explore [Network Discovery](./quickstart.md#network-discovery-agentless) to find certificates you didn't know about
|
||||
- See all [Deployment Examples](./examples.md) for other scenarios (wildcard DNS-01, private CA, step-ca, multi-issuer)
|
||||
+65
-14
@@ -43,6 +43,8 @@ On Linux, follow the official Docker install guide for your distribution.
|
||||
|
||||
## Start Everything
|
||||
|
||||
### Docker Compose (Quick Start)
|
||||
|
||||
```bash
|
||||
git clone https://github.com/shankar0123/certctl.git
|
||||
cd certctl
|
||||
@@ -58,6 +60,22 @@ cp deploy/.env.example deploy/.env
|
||||
docker compose -f deploy/docker-compose.yml up -d --build
|
||||
```
|
||||
|
||||
### Kubernetes with Helm
|
||||
|
||||
For production deployments on Kubernetes, use the Helm chart:
|
||||
|
||||
```bash
|
||||
helm install certctl deploy/helm/certctl/ \
|
||||
--create-namespace --namespace certctl \
|
||||
--set server.auth.apiKey="your-secure-api-key" \
|
||||
--set postgresql.auth.password="your-db-password" \
|
||||
--set ingress.enabled=true \
|
||||
--set ingress.hosts[0].host="certctl.example.com" \
|
||||
--set ingress.hosts[0].tls=true
|
||||
```
|
||||
|
||||
The chart includes: server Deployment (with configurable replicas, health probes, security context), PostgreSQL StatefulSet with persistent volumes, agent DaemonSet (one agent per infrastructure node), optional Ingress with TLS, and ServiceAccount with RBAC. All certctl configuration options are exposed in `values.yaml` — customize issuer settings, target connectors, scheduler intervals, and notifier credentials there.
|
||||
|
||||
Wait about 30 seconds for PostgreSQL to initialize, then verify:
|
||||
|
||||
```bash
|
||||
@@ -87,7 +105,7 @@ Open **http://localhost:8443** in your browser.
|
||||
>
|
||||
> **Key rotation:** `CERTCTL_AUTH_SECRET` accepts comma-separated keys (e.g., `CERTCTL_AUTH_SECRET=new-key,old-key`). Both keys are valid simultaneously, enabling zero-downtime rotation: add the new key, roll clients over, then remove the old key.
|
||||
|
||||
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.
|
||||
The dashboard comes pre-loaded with 35 demo certificates across 5 issuers, 8 agents, and 90 days of job history — expiring certs, expired certs, active certs, failed renewals, revocations, discovery scans, and approval workflows. A realistic snapshot of what certificate management looks like in a real organization.
|
||||
|
||||
### What you're looking at
|
||||
|
||||
@@ -109,7 +127,7 @@ Explore the sidebar: Certificates, Agents, Policies, Jobs, Audit Trail, Notifica
|
||||
|
||||
**"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.
|
||||
**"Show me the agent fleet"** — Click "Agents." Eight agents across Linux, macOS, and Windows platforms—most online, showing OS, architecture, IP, and version metadata. A ninth entry (server-scanner) is the sentinel agent used for network certificate discovery. 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.
|
||||
|
||||
@@ -346,6 +364,35 @@ export CERTCTL_API_KEY="test-key-123"
|
||||
./certctl-cli status # Health + stats
|
||||
```
|
||||
|
||||
## Scheduled Certificate Digest Emails
|
||||
|
||||
Enable automatic HTML digest emails with certificate stats, expiration timeline, and job health:
|
||||
|
||||
```bash
|
||||
# Set SMTP configuration
|
||||
export CERTCTL_SMTP_HOST=smtp.gmail.com
|
||||
export CERTCTL_SMTP_PORT=587
|
||||
export CERTCTL_SMTP_USERNAME=admin@example.com
|
||||
export CERTCTL_SMTP_PASSWORD=your-app-password
|
||||
export CERTCTL_SMTP_FROM_ADDRESS=certctl@example.com
|
||||
export CERTCTL_SMTP_USE_TLS=true
|
||||
|
||||
# Enable digest and set recipients
|
||||
export CERTCTL_DIGEST_ENABLED=true
|
||||
export CERTCTL_DIGEST_INTERVAL=24h
|
||||
export CERTCTL_DIGEST_RECIPIENTS=ops@example.com,security@example.com
|
||||
```
|
||||
|
||||
Preview the digest HTML before enabling scheduled delivery:
|
||||
```bash
|
||||
curl http://localhost:8443/api/v1/digest/preview | jq '.html' | grep -o '<html>' # Shows HTML is ready
|
||||
|
||||
# Trigger a digest send immediately (outside of schedule)
|
||||
curl -X POST http://localhost:8443/api/v1/digest/send
|
||||
```
|
||||
|
||||
If no recipients are configured (`CERTCTL_DIGEST_RECIPIENTS` empty), the digest falls back to certificate owner emails. Digests include total certificates, expiring soon, expired, active agents, completed/failed jobs (30-day summary), and a table of expiring certs color-coded by urgency (7/14/30 days).
|
||||
|
||||
## MCP Server (AI Integration)
|
||||
|
||||
```bash
|
||||
@@ -363,18 +410,19 @@ Exposes 78 MCP tools covering the REST API via stdio transport. Ask Claude: "Wha
|
||||
|
||||
| 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 |
|
||||
| Teams | 6 | Platform, Security, Payments, Frontend, Data, DevOps |
|
||||
| Owners | 6 | Alice, Bob, Carol, Dave, Eve, Frank |
|
||||
| Issuers | 5 | Local Dev CA, Let's Encrypt Staging, step-ca Internal, ZeroSSL (EAB), Custom OpenSSL CA |
|
||||
| Agents | 9 | 8 real agents (linux/darwin/windows, amd64/arm64) + server-scanner (network discovery) |
|
||||
| Targets | 8 | NGINX prod, NGINX staging, NGINX data, HAProxy, Apache, IIS, Traefik, Caddy |
|
||||
| Certificates | 35 | Active, Expiring, Expired, Failed, Revoked, RenewalInProgress, Wildcard, S/MIME |
|
||||
| Jobs | 50+ | 90 days of issuance, renewal, deployment jobs + 2 AwaitingApproval |
|
||||
| Discovered Certs | 12 | Unmanaged (filesystem + network), Managed (linked), Dismissed |
|
||||
| Discovery Scans | 8 | Historical + recent agent filesystem scans + network TLS scans |
|
||||
| Network Scan Targets | 4 | DC1 Web Servers, DC2 Application Tier, DMZ Public Endpoints, Edge Locations |
|
||||
| Audit Events | 55+ | 90 days of lifecycle events (issuance, renewal, deployment, revocation, discovery) |
|
||||
| Policies | 4 | Required owner, allowed environments, max lifetime, min renewal window |
|
||||
| Profiles | 4 | Standard TLS, Internal mTLS, Short-Lived, High Security |
|
||||
| Profiles | 5 | Standard TLS, Internal mTLS, Short-Lived, High Security, S/MIME Email |
|
||||
| Agent Groups | 5 | Linux agents, ARM agents, Production subnet, etc. |
|
||||
|
||||
## Dashboard Demo Mode
|
||||
@@ -413,7 +461,10 @@ The `-v` flag removes the PostgreSQL data volume for a clean slate.
|
||||
|
||||
## What's Next
|
||||
|
||||
**Ready to deploy with your stack?** The [Deployment Examples](examples.md) page has 5 turnkey docker-compose scenarios — pick the one closest to your setup and have it running in minutes. It also covers migration paths from Certbot, acme.sh, and cert-manager.
|
||||
|
||||
- **[Deployment Examples](examples.md)** — ACME+NGINX, wildcard DNS-01, private CA+Traefik, step-ca+HAProxy, multi-issuer
|
||||
- **[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
|
||||
- **[Connector Reference](connectors.md)** — Configuration for all 7 issuers and 10 targets
|
||||
- **[Concepts Guide](concepts.md)** — TLS certificates, CAs, and private keys explained from scratch
|
||||
|
||||
+1068
File diff suppressed because it is too large
Load Diff
+2166
-36
File diff suppressed because it is too large
Load Diff
+75
-40
@@ -1,82 +1,117 @@
|
||||
# Why certctl?
|
||||
|
||||
Certificate management is broken at every scale between "one domain on Let's Encrypt" and "Fortune 500 budget for Venafi."
|
||||
Certificate management is broken at every scale between "one domain on Let's Encrypt" and "Fortune 500 budget for Venafi." certctl fills that gap: a self-hosted platform that automates the entire certificate lifecycle, works with any CA, deploys to any server, and keeps private keys on your infrastructure. It's free, source-available, and you own everything.
|
||||
|
||||
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.
|
||||
## The Math That Forces the Decision
|
||||
|
||||
certctl fills that gap.
|
||||
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.
|
||||
|
||||
## The Problem
|
||||
At 47-day lifespans, a team managing 100 certificates is processing **7+ renewals per week**, every week, forever. At 200 certificates, it's two per day. Manual processes, calendar reminders, and certbot cron jobs don't scale to this — a single missed renewal becomes a production outage at 3 AM. Certificate lifecycle automation is no longer optional; the only question is what tool runs it.
|
||||
|
||||
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 Landscape Today
|
||||
|
||||
The existing options for automation are:
|
||||
If you're evaluating your options, here's what you'll find:
|
||||
|
||||
- **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.
|
||||
**ACME clients** (certbot, lego, acme.sh) handle issuance and renewal for Let's Encrypt and similar CAs, but they don't deploy to target servers, don't track inventory, don't support private CAs, and give you no audit trail or policy enforcement. You end up writing glue scripts and hoping they don't break.
|
||||
|
||||
**Kubernetes-native tools** (cert-manager) work well inside the cluster, but most organizations run mixed infrastructure — NGINX on VMs, HAProxy at the edge, IIS on Windows, maybe an F5. You need a separate solution for everything outside Kubernetes.
|
||||
|
||||
**Commercial SaaS platforms** handle more of the lifecycle but are proprietary, cloud-dependent, and priced per certificate. At 100 certs and 20 agents, SaaS pricing runs $3,000-5,000/year and scales linearly. You're paying rent on your own infrastructure's security.
|
||||
|
||||
**Enterprise platforms** (Venafi, Keyfactor, AppViewX) are comprehensive but start at $75K/year and require dedicated teams to operate. If you have a 50-server environment, the licensing costs more than the servers.
|
||||
|
||||
## 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:
|
||||
certctl 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.
|
||||
certctl agents generate ECDSA P-256 private keys locally. 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 — it never crosses the network.
|
||||
|
||||
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.
|
||||
This isn't a premium feature. It's the default behavior, free. Most alternatives either generate keys on the server (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:
|
||||
certctl works with any certificate authority, not just ACME providers. Seven issuer connectors ship today, all free:
|
||||
|
||||
- **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
|
||||
- **ACME v2** (Let's Encrypt, ZeroSSL, Google Trust Services, Buypass) — HTTP-01, DNS-01, DNS-PERSIST-01 challenges, External Account Binding, ACME Renewal Information (RFC 9702)
|
||||
- **HashiCorp Vault PKI** — `/v1/{mount}/sign/{role}` API, token auth
|
||||
- **DigiCert CertCentral** — async order model, OV/EV support
|
||||
- **step-ca** (Smallstep) — native /sign API with JWK provisioner auth
|
||||
- **Local CA** — self-signed or sub-CA mode (chain to ADCS or any enterprise root)
|
||||
- **OpenSSL / Custom CA** — delegate signing to any shell script
|
||||
- **EST enrollment** (RFC 7030) — device certs for WiFi/802.1X, MDM, IoT
|
||||
|
||||
Every issuer connector implements the same interface. Switching CAs or running multiple CAs in parallel requires zero code changes — just configuration.
|
||||
Every connector implements the same interface. Running multiple CAs in parallel — Let's Encrypt for public certs, Vault for internal services, your enterprise CA for legacy systems — is configuration, not code.
|
||||
|
||||
### 3. Post-Deployment Verification
|
||||
|
||||
Every other tool in this space stops at "the deployment command succeeded." certctl goes further: 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.
|
||||
Every other tool in this space stops at "the deployment command succeeded." certctl goes further: after deploying a certificate, the agent connects back to the live TLS endpoint and compares the SHA-256 fingerprint of the served certificate against what was deployed.
|
||||
|
||||
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 catches this.
|
||||
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 catches this automatically.
|
||||
|
||||
## What Else Ships Free
|
||||
|
||||
The three differentiators above get the headlines, but the feature surface is wider than most paid platforms:
|
||||
|
||||
**10 deployment targets** — NGINX, Apache, HAProxy, Traefik, Caddy, Envoy, IIS (local PowerShell + remote WinRM), Postfix, and Dovecot. All use a pluggable connector model. The control plane never initiates outbound connections — agents poll for work, meaning certctl works behind firewalls, across network zones, and in air-gapped environments.
|
||||
|
||||
**Network certificate discovery** — active TLS scanning of CIDR ranges finds certificates you didn't know existed. Agents also scan local filesystems for PEM/DER files. Everything feeds into a triage workflow where you claim, dismiss, or import discovered certs into management.
|
||||
|
||||
**Immutable audit trail** — every API call recorded (method, path, actor, body hash, status, latency). Every certificate lifecycle event tracked. Append-only, no update or delete. Mapped to SOC 2, PCI-DSS 4.0, and NIST SP 800-57 compliance frameworks with published evidence guides.
|
||||
|
||||
**Policy engine** — 5 rule types (allowed issuers, allowed domains, required metadata, allowed environments, renewal lead time) with violation tracking and severity levels.
|
||||
|
||||
**PKI compliance** — DER-encoded X.509 CRL signed by issuing CA, embedded OCSP responder, RFC 5280 revocation with all reason codes, short-lived certificate exemption.
|
||||
|
||||
**Prometheus metrics** — `/api/v1/metrics/prometheus` in standard exposition format. Works with Prometheus, Grafana Agent, Datadog Agent, Victoria Metrics.
|
||||
|
||||
**MCP server** — 80 tools exposing the entire API surface for AI-assisted certificate management via Claude, Cursor, or any MCP-compatible client. No other certificate platform offers this.
|
||||
|
||||
**Full REST API** — 97 OpenAPI 3.1-documented operations. CLI tool with 10 subcommands. Helm chart for Kubernetes deployment. Scheduled certificate digest emails. Certificate export in PEM and PKCS#12. S/MIME support with EKU-aware issuance.
|
||||
|
||||
**Extensively tested** — Go backend with race detection, static analysis (golangci-lint), and vulnerability scanning (govulncheck) on every commit. CI-enforced per-layer coverage thresholds. Frontend test suite. Every push is gated.
|
||||
|
||||
## How certctl Compares
|
||||
|
||||
### vs. CertKit
|
||||
### vs. ACME Clients
|
||||
|
||||
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.
|
||||
ACME clients solve one slice of the problem — issuance and renewal from ACME CAs. certctl replaces the ACME client, adds 6 more CA integrations, deploys the cert to the right server, verifies it's live, tracks it in an inventory, alerts on expiry, logs everything to an audit trail, and enforces policy. If you're currently running certbot behind a cron job and a prayer, certctl replaces all of it.
|
||||
|
||||
### vs. KeyTalk
|
||||
### vs. Agent-Based SaaS
|
||||
|
||||
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.
|
||||
The closest architectural competitors use the same agent model — local key generation, CSR submission, push-based deployment. Where certctl differs: it supports 7 issuer types (not just ACME), provides CRL/OCSP/revocation infrastructure (not just issuance), includes a policy engine and network discovery, and is source-available with no certificate limit. SaaS alternatives are typically proprietary, priced per certificate ($2+/cert/month), and cap their free tiers at 3-5 certificates. certctl is free for any number of certificates, forever.
|
||||
|
||||
### vs. Enterprise Platforms (Venafi, Keyfactor)
|
||||
### vs. Commercial PKI Platforms
|
||||
|
||||
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.
|
||||
On-prem or hosted commercial platforms offer broader cert type coverage (VPN certs, device auth, SCEP) and deeper CA integrations. The trade-off: no free tier, opaque pricing (often €13K+/year for 1,500 certs), proprietary codebases, and no public API documentation. certctl trades breadth of exotic cert types for full transparency — source-available code, 97-operation OpenAPI spec, and a free community edition with no artificial limits.
|
||||
|
||||
## Getting Started
|
||||
### vs. Enterprise Platforms
|
||||
|
||||
Venafi and Keyfactor offer decades of features at $75K-$250K+/year. certctl targets organizations that need 80% of those capabilities at a fraction of the cost. What certctl doesn't have yet: SSO/RBAC (coming in certctl Pro), vendor SLA-backed support. What certctl does have that enterprise platforms don't: an MCP server for AI-assisted management, ACME ARI (RFC 9702) for CA-directed renewal timing, and a deployment model that works in 5 minutes instead of 5 months.
|
||||
|
||||
## Who Should Look Elsewhere
|
||||
|
||||
certctl isn't the right tool for everyone:
|
||||
|
||||
- **Single-domain sites** — if you have one certificate on one server, certbot is fine. certctl is designed for managing tens to hundreds of certificates across multiple servers and CAs.
|
||||
- **Pure Kubernetes environments** — if every workload runs in-cluster and you're happy with cert-manager, there's no reason to add another tool. certctl shines when your infrastructure extends beyond Kubernetes.
|
||||
- **Organizations that need a vendor SLA today** — certctl is source-available software maintained by a small team. If you need contractual uptime guarantees and a support hotline, an enterprise platform is the right choice (for now).
|
||||
|
||||
## See It Running
|
||||
|
||||
The demo seeds 32 certificates across 7 issuers, 8 agents, 6 deployment targets, and 180 days of realistic history — jobs, audit events, discovery scans, approval workflows — so you can explore every feature immediately.
|
||||
|
||||
```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
|
||||
cd certctl/deploy && docker compose up -d
|
||||
# Dashboard at 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.
|
||||
See the [Quickstart Guide](quickstart.md) for a full walkthrough, or explore the [5 turnkey examples](../examples/) for specific scenarios (ACME+NGINX, wildcard DNS-01, private CA+Traefik, step-ca+HAProxy, multi-issuer).
|
||||
|
||||
## 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.
|
||||
certctl is source-available under the [Business Source License 1.1](../LICENSE). Free for any use except offering a competing managed service. 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.
|
||||
You own your data, your keys, and your deployment.
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
# certctl + NGINX + Let's Encrypt
|
||||
|
||||
This example demonstrates certctl's core use case: **automatically manage TLS certificates for NGINX using Let's Encrypt (ACME HTTP-01 challenges).**
|
||||
|
||||
## What This Does
|
||||
|
||||
- Deploys certctl server (control plane) with PostgreSQL
|
||||
- Deploys certctl agent on the same network (in production: on your NGINX server)
|
||||
- Configures Let's Encrypt as the certificate issuer via ACME v2
|
||||
- Demonstrates HTTP-01 challenge solving (requires port 80 open to the internet)
|
||||
- Shows how to set up 3 example domains for certificate enrollment and renewal
|
||||
- Automatically renews certificates 30 days before expiration
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["Your Domain (example.com)"]
|
||||
B["Let's Encrypt ACME"]
|
||||
C["certctl Server (control plane)"]
|
||||
D["certctl Agent (on NGINX server)"]
|
||||
E["NGINX Reverse Proxy"]
|
||||
|
||||
A -->|HTTP-01 validation<br/>port 80| B
|
||||
B -->|CSR submission| C
|
||||
C -->|API polling| D
|
||||
D -->|deploy cert+key| E
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **Docker & Docker Compose** (v20.10+)
|
||||
2. **A domain name** pointing to your server (e.g., `example.com`)
|
||||
3. **Ports 80 and 443 open** to the internet (ACME HTTP-01 needs port 80)
|
||||
4. **Valid email address** for Let's Encrypt account (errors and renewal notices)
|
||||
|
||||
If you don't have a real domain or can't open port 80, see [Customization Tips](#customization-tips) below.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Clone or copy this example
|
||||
|
||||
```bash
|
||||
cd examples/acme-nginx
|
||||
```
|
||||
|
||||
### 2. Create a `.env` file with your settings
|
||||
|
||||
```bash
|
||||
cat > .env <<'EOF'
|
||||
# Your email for Let's Encrypt account
|
||||
ACME_EMAIL=admin@example.com
|
||||
|
||||
# Database password (change this in production!)
|
||||
DB_PASSWORD=certctl-demo-password
|
||||
|
||||
# Agent API key (generate a real one in production)
|
||||
AGENT_API_KEY=agent-demo-key
|
||||
|
||||
# Server port (certctl listens here internally on 8443; expose as needed)
|
||||
SERVER_PORT=8443
|
||||
EOF
|
||||
```
|
||||
|
||||
### 3. (Optional) Create an NGINX config
|
||||
|
||||
If you have a real domain and want NGINX to route traffic:
|
||||
|
||||
```bash
|
||||
cat > nginx.conf <<'EOF'
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
# HTTP block for ACME challenges
|
||||
server {
|
||||
listen 80;
|
||||
server_name example.com www.example.com api.example.com;
|
||||
|
||||
# ACME challenge directory (certctl writes validation files here)
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
# Redirect HTTP to HTTPS
|
||||
location / {
|
||||
return 301 https://$server_name$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
# HTTPS block (certificates deployed here by certctl agent)
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name example.com www.example.com api.example.com;
|
||||
|
||||
ssl_certificate /etc/nginx/ssl/example.com.crt;
|
||||
ssl_certificate_key /etc/nginx/ssl/example.com.key;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
location / {
|
||||
proxy_pass http://upstream-service;
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
```
|
||||
|
||||
Or just accept the default empty NGINX config for demonstration.
|
||||
|
||||
### 4. Start the stack
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Monitor logs:
|
||||
```bash
|
||||
docker compose logs -f certctl-server certctl-agent
|
||||
```
|
||||
|
||||
### 5. Access the dashboard
|
||||
|
||||
Navigate to `http://localhost:8443` (or your `SERVER_PORT`)
|
||||
|
||||
You should see:
|
||||
- An empty certificate inventory (no certs issued yet)
|
||||
- One ACME issuer ("iss-acme") configured and ready
|
||||
- One agent ("nginx-agent-01") online and heartbeating
|
||||
|
||||
### 6. Create a certificate profile
|
||||
|
||||
In the certctl dashboard:
|
||||
1. Go to **Profiles** (sidebar)
|
||||
2. Click **New Profile**
|
||||
3. Set:
|
||||
- Name: `acme-prod`
|
||||
- Key Type: `RSA-2048` (or `ECDSA-P256`)
|
||||
- Max TTL: `90 days`
|
||||
- Allowed Key Types: `RSA-2048, ECDSA-P256`
|
||||
4. Save
|
||||
|
||||
### 7. Request a certificate
|
||||
|
||||
In the certctl dashboard:
|
||||
1. Go to **Certificates** (sidebar)
|
||||
2. Click **Request New Certificate**
|
||||
3. Set:
|
||||
- Common Name: `example.com`
|
||||
- SANs: `www.example.com`, `api.example.com` (optional)
|
||||
- Issuer: `iss-acme` (Let's Encrypt)
|
||||
- Profile: `acme-prod`
|
||||
4. Click **Request**
|
||||
|
||||
Behind the scenes:
|
||||
- Server creates an `Issuance` job
|
||||
- Agent polls for work, fetches the job
|
||||
- Agent generates a P-256 key (never sent to server)
|
||||
- Agent submits CSR to server
|
||||
- Server sends CSR to Let's Encrypt ACME
|
||||
- Let's Encrypt provides HTTP-01 challenge token
|
||||
- Server downloads ACME challenge, returns to agent
|
||||
- Agent deploys challenge file to NGINX `/.well-known/acme-challenge/`
|
||||
- Let's Encrypt validates (HTTP GET to `http://example.com/.well-known/acme-challenge/...`)
|
||||
- Let's Encrypt issues certificate
|
||||
- Server receives certificate, passes to agent
|
||||
- Agent deploys cert+key to `/etc/nginx/ssl/example.com.crt` + `.key`
|
||||
- Agent reloads NGINX (`nginx -s reload`)
|
||||
- Certificate is now active
|
||||
|
||||
### 8. View the certificate
|
||||
|
||||
In the dashboard:
|
||||
1. Go to **Certificates**
|
||||
2. Click the certificate to see:
|
||||
- Common name, SANs, serial number
|
||||
- Issuer (Let's Encrypt), not-before/after dates
|
||||
- Status (Active, Expiring in N days, Expired)
|
||||
- Deployment history (timestamps, agent name, target)
|
||||
- Next auto-renewal date (30 days before expiration)
|
||||
|
||||
### 9. Set up automatic renewal
|
||||
|
||||
The server automatically checks for certificates expiring within 30 days and triggers renewal. You can:
|
||||
- Adjust the threshold in the certificate's policy
|
||||
- Manually trigger renewal via dashboard button
|
||||
- View renewal job status and history
|
||||
|
||||
## How It Works
|
||||
|
||||
### Certificate Lifecycle
|
||||
|
||||
1. **Request** — Operator creates certificate request via dashboard or API
|
||||
2. **CSR Generation** — Agent generates private key locally, submits CSR to server
|
||||
3. **ACME Challenge** — Server communicates with Let's Encrypt ACME, obtains challenge
|
||||
4. **Challenge Proof** — Agent deploys challenge proof to NGINX
|
||||
5. **Issuance** — Let's Encrypt validates, issues certificate
|
||||
6. **Deployment** — Agent receives certificate, deploys to NGINX SSL directory
|
||||
7. **Reload** — Agent signals NGINX to reload (`nginx -s reload`)
|
||||
8. **Verification** — Agent optionally verifies the live TLS endpoint (handshake fingerprint)
|
||||
9. **Renewal** — 30 days before expiration, process repeats automatically
|
||||
|
||||
### HTTP-01 Challenge
|
||||
|
||||
ACME HTTP-01 works like this:
|
||||
1. Let's Encrypt generates random token (e.g., `abc123def456`)
|
||||
2. Server returns token to agent
|
||||
3. Agent writes file: `/.well-known/acme-challenge/abc123def456` with value (random key material)
|
||||
4. Let's Encrypt performs HTTP GET to `http://example.com/.well-known/acme-challenge/abc123def456`
|
||||
5. If content matches, domain ownership is proven
|
||||
6. Certificate is issued
|
||||
|
||||
**Requirements:**
|
||||
- Port 80 must be open to the internet
|
||||
- DNS must resolve your domain to your server
|
||||
- NGINX must serve `/.well-known/acme-challenge/` (or certctl mounts a separate directory)
|
||||
|
||||
### Agent Key Generation
|
||||
|
||||
Keys are generated **on the agent**, never on the server:
|
||||
1. Agent creates ECDSA P-256 keypair using `crypto/ecdsa`
|
||||
2. Private key is stored locally on agent at `/var/lib/certctl/keys/` (readable only by certctl process)
|
||||
3. Agent creates CSR (certificate signing request) with private key
|
||||
4. Agent submits CSR to server
|
||||
5. Server never sees the private key
|
||||
6. Certificate is returned, agent stores it alongside key
|
||||
7. Both key and cert used for NGINX deployment
|
||||
|
||||
This keeps private keys in the infrastructure where they're used, following zero-trust principles.
|
||||
|
||||
## Adding More Domains
|
||||
|
||||
### Option 1: Additional SANs on Same Certificate
|
||||
|
||||
Edit the existing certificate in the dashboard:
|
||||
1. Click the certificate
|
||||
2. Edit SANs to add `mail.example.com`, `ftp.example.com`, etc.
|
||||
3. Trigger renewal
|
||||
4. Agent generates new CSR with all SANs
|
||||
5. Let's Encrypt validates each SAN (HTTP-01 for each)
|
||||
6. Single certificate with multiple SANs is issued
|
||||
|
||||
### Option 2: Separate Certificates per Domain
|
||||
|
||||
If you want separate certificates (different issuance schedules, different targets):
|
||||
1. Dashboard → **Certificates** → **Request New Certificate**
|
||||
2. Common Name: `subdomain.example.com`
|
||||
3. Set same issuer and profile
|
||||
4. Request
|
||||
|
||||
Each domain gets its own cert, key, and renewal schedule.
|
||||
|
||||
### Wildcard Certificates (Not HTTP-01)
|
||||
|
||||
HTTP-01 does **not** support wildcard (`*.example.com`). To issue wildcards, use DNS-01 challenge (see [acme-wildcard-dns01](../acme-wildcard-dns01/) example).
|
||||
|
||||
## Customization Tips
|
||||
|
||||
### Using Let's Encrypt Staging (for testing)
|
||||
|
||||
Staging has higher rate limits and doesn't require real domains:
|
||||
|
||||
```bash
|
||||
# In .env or docker-compose.yml override:
|
||||
CERTCTL_ACME_DIRECTORY_URL=https://acme-staging-v02.api.letsencrypt.org/directory
|
||||
```
|
||||
|
||||
Staging certificates won't be trusted by browsers (fake CA), but you can test the full flow without hitting production rate limits.
|
||||
|
||||
### Disabling Port 80 Requirement (Demo Mode)
|
||||
|
||||
If you can't open port 80, use ACME DNS-01 instead (requires DNS provider integration). See [acme-wildcard-dns01](../acme-wildcard-dns01/) example.
|
||||
|
||||
Or use Local CA for internal testing:
|
||||
```bash
|
||||
# Switch issuer to Local CA (not public-trusted, but no challenge needed)
|
||||
CERTCTL_ACME_DIRECTORY_URL= # Leave empty to disable ACME
|
||||
# (then configure Local CA instead)
|
||||
```
|
||||
|
||||
### Custom NGINX Config
|
||||
|
||||
Replace `nginx.conf` with your own before `docker compose up`. The agent doesn't manage the NGINX config — it only deploys certificates. You're responsible for:
|
||||
- Configuring SSL paths (`ssl_certificate`, `ssl_certificate_key`)
|
||||
- Setting up challenge directory (`/.well-known/acme-challenge/`)
|
||||
- Pointing NGINX to agent-deployed certificates
|
||||
|
||||
### Database Persistence
|
||||
|
||||
PostgreSQL data is stored in the `postgres_data` volume. To reset:
|
||||
```bash
|
||||
docker compose down -v # Destroy all volumes
|
||||
```
|
||||
|
||||
### Viewing Agent Logs
|
||||
|
||||
```bash
|
||||
docker compose logs -f certctl-agent
|
||||
```
|
||||
|
||||
Look for:
|
||||
- `Heartbeat successful` — agent is communicating with server
|
||||
- `CSR submitted` — key generation and CSR submission worked
|
||||
- `Deployment succeeded` — certificate deployed to NGINX
|
||||
- `NGINX reload` — signal sent to reload
|
||||
|
||||
### Testing ACME Without Real Domain
|
||||
|
||||
Use `nip.io` (free DNS service):
|
||||
1. Deploy to a server with a public IP
|
||||
2. Use domain: `<your-ip>.nip.io` (e.g., `203.0.113.45.nip.io`)
|
||||
3. Let's Encrypt will validate to that IP
|
||||
4. Change ACME_EMAIL to a real email you control
|
||||
|
||||
## Production Checklist
|
||||
|
||||
Before running in production:
|
||||
|
||||
- [ ] Change `DB_PASSWORD` to a strong random password
|
||||
- [ ] Generate a real API key for the agent (don't use the demo key)
|
||||
- [ ] Enable `CERTCTL_AUTH_TYPE=api-key` and enforce authentication
|
||||
- [ ] Use Let's Encrypt production directory (not staging)
|
||||
- [ ] Configure `CERTCTL_CORS_ORIGINS` to restrict cross-origin access
|
||||
- [ ] Use `CERTCTL_KEYGEN_MODE=agent` (default, but verify)
|
||||
- [ ] Set `CERTCTL_LOG_LEVEL=warn` to reduce log noise
|
||||
- [ ] Configure email notifications for certificate expiration alerts
|
||||
- [ ] Set up log aggregation (Datadog, ELK, Splunk, etc.)
|
||||
- [ ] Use docker secrets or external secret manager for credentials (not .env)
|
||||
- [ ] Run agent on actual NGINX servers (not co-located with server for HA)
|
||||
- [ ] Set up monitoring and alerting on agent heartbeat and job completion
|
||||
- [ ] Implement backup/restore for PostgreSQL
|
||||
- [ ] Use TLS for certctl server (terminate at reverse proxy or load balancer)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Agent heartbeat failing
|
||||
```bash
|
||||
docker compose logs certctl-agent
|
||||
# Check: CERTCTL_SERVER_URL, CERTCTL_API_KEY, network connectivity
|
||||
```
|
||||
|
||||
### ACME challenge failing
|
||||
```bash
|
||||
# Ensure port 80 is open: curl http://example.com/.well-known/acme-challenge/test
|
||||
# Check NGINX is running and serving /.well-known/acme-challenge/
|
||||
# Verify DNS resolves domain to your server: dig example.com
|
||||
```
|
||||
|
||||
### NGINX reload failing
|
||||
Check agent permissions on NGINX socket and that NGINX is reachable from agent container.
|
||||
|
||||
### Let's Encrypt rate limited
|
||||
Let's Encrypt has rate limits (50 certs per domain per week). Use staging to test, or wait a week.
|
||||
|
||||
### Certificate not deployed to NGINX
|
||||
Check agent logs for deployment errors. Verify `/etc/nginx/ssl` volume is writable by agent container.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- **Wildcard certificates**: See [acme-wildcard-dns01](../acme-wildcard-dns01/) example
|
||||
- **Multiple issuers**: See [multi-issuer](../multi-issuer/) example
|
||||
- **Private CA**: See [private-ca-traefik](../private-ca-traefik/) example
|
||||
- **Dashboard deep dive**: Read [docs/quickstart.md](../../docs/quickstart.md)
|
||||
- **REST API**: Explore [api/openapi.yaml](../../api/openapi.yaml)
|
||||
|
||||
## Support
|
||||
|
||||
For issues or questions:
|
||||
- Check [docs/troubleshooting.md](../../docs/troubleshooting.md)
|
||||
- Open an issue on GitHub
|
||||
- Review server and agent logs: `docker compose logs -f`
|
||||
@@ -0,0 +1,146 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
# PostgreSQL database for certctl
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: certctl-postgres-acme-nginx
|
||||
environment:
|
||||
POSTGRES_DB: certctl
|
||||
POSTGRES_USER: certctl
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-certctl-dev-password}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U certctl -d certctl']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl server (control plane)
|
||||
certctl-server:
|
||||
image: ghcr.io/shankar0123/certctl-server:latest
|
||||
container_name: certctl-server-acme-nginx
|
||||
environment:
|
||||
# Database
|
||||
CERTCTL_DATABASE_URL: postgres://certctl:${DB_PASSWORD:-certctl-dev-password}@postgres:5432/certctl?sslmode=disable
|
||||
|
||||
# Server settings
|
||||
CERTCTL_SERVER_PORT: 8443
|
||||
CERTCTL_SERVER_HOST: 0.0.0.0
|
||||
|
||||
# Auth (disabled for demo; production should use API keys)
|
||||
CERTCTL_AUTH_TYPE: none
|
||||
|
||||
# CORS (allow agent communication)
|
||||
CERTCTL_CORS_ORIGINS: '*'
|
||||
|
||||
# Key generation mode (agent-side in production, server-side for demo)
|
||||
CERTCTL_KEYGEN_MODE: agent
|
||||
|
||||
# ACME issuer configuration
|
||||
# This registers the Let's Encrypt ACME issuer
|
||||
CERTCTL_ACME_DIRECTORY_URL: https://acme-v02.api.letsencrypt.org/directory
|
||||
CERTCTL_ACME_EMAIL: ${ACME_EMAIL:-admin@example.com}
|
||||
CERTCTL_ACME_CHALLENGE_TYPE: http-01
|
||||
|
||||
# Local CA as fallback for internal services (optional)
|
||||
CERTCTL_CA_CERT_PATH: /etc/certctl/ca.crt
|
||||
CERTCTL_CA_KEY_PATH: /etc/certctl/ca.key
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
ports:
|
||||
- '${SERVER_PORT:-8443}:8443'
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- certctl-network
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'curl -sf http://localhost:8443/health || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl agent (runs on the target machine with NGINX)
|
||||
# In this example, the agent is in the same compose file for simplicity.
|
||||
# In production, the agent runs on each server that needs certificates.
|
||||
certctl-agent:
|
||||
image: ghcr.io/shankar0123/certctl-agent:latest
|
||||
container_name: certctl-agent-acme-nginx
|
||||
environment:
|
||||
# Control plane connection
|
||||
CERTCTL_SERVER_URL: http://certctl-server:8443
|
||||
CERTCTL_API_KEY: ${AGENT_API_KEY:-agent-demo-key}
|
||||
|
||||
# Key generation (agent-side keys, never sent to server)
|
||||
CERTCTL_KEYGEN_MODE: agent
|
||||
CERTCTL_KEY_DIR: /var/lib/certctl/keys
|
||||
|
||||
# Discovery (scan existing certs so operator knows what's already deployed)
|
||||
CERTCTL_DISCOVERY_DIRS: /etc/nginx/ssl
|
||||
|
||||
# Heartbeat interval
|
||||
CERTCTL_HEARTBEAT_INTERVAL: 30s
|
||||
|
||||
# Agent metadata (self-reported)
|
||||
CERTCTL_AGENT_NAME: nginx-agent-01
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
volumes:
|
||||
# Mount NGINX config and cert directories
|
||||
# In production, these would be the actual NGINX paths
|
||||
- nginx_certs:/etc/nginx/ssl
|
||||
- nginx_conf:/etc/nginx/conf.d
|
||||
# Agent key storage (persisted across restarts)
|
||||
- agent_keys:/var/lib/certctl/keys
|
||||
depends_on:
|
||||
certctl-server:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# NGINX reverse proxy / web server
|
||||
# This is where certificates will be deployed
|
||||
nginx:
|
||||
image: nginx:alpine
|
||||
container_name: certctl-nginx-acme-nginx
|
||||
ports:
|
||||
- '80:80'
|
||||
- '443:443'
|
||||
volumes:
|
||||
- nginx_conf:/etc/nginx/conf.d
|
||||
- nginx_certs:/etc/nginx/ssl
|
||||
# Default NGINX config (if not provided by agent)
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
depends_on:
|
||||
- certctl-agent
|
||||
networks:
|
||||
- certctl-network
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'wget --quiet --tries=1 --spider http://localhost/ || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
certctl-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
driver: local
|
||||
nginx_certs:
|
||||
driver: local
|
||||
nginx_conf:
|
||||
driver: local
|
||||
agent_keys:
|
||||
driver: local
|
||||
@@ -0,0 +1,306 @@
|
||||
# ACME Wildcard DNS-01 Example
|
||||
|
||||
**What this does:** Issues wildcard certificates (e.g., `*.example.com`) from Let's Encrypt using DNS-01 challenge validation.
|
||||
|
||||
This example is ideal for:
|
||||
- Issuing wildcard certificates (`*.example.com`)
|
||||
- Services behind NAT, firewalls, or non-public networks
|
||||
- Batch issuance of multiple domains in parallel
|
||||
- Internal PKI with public DNS names
|
||||
- Scenarios where you have programmatic access to your DNS provider's API
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before running this example, you need:
|
||||
|
||||
1. **A domain name** (e.g., `example.com`) that you control and can manage DNS records for
|
||||
2. **DNS provider credentials:**
|
||||
- **Cloudflare** (example included): API token with DNS:write permission + Zone ID
|
||||
- **Route53 (AWS)**: AWS access key + secret key
|
||||
- **Azure DNS**: Azure subscription ID + credentials
|
||||
- **Other providers**: See "Adapting for Other DNS Providers" below
|
||||
3. **Docker and Docker Compose** installed
|
||||
|
||||
## Quick Start (Cloudflare)
|
||||
|
||||
### Step 1: Get Cloudflare Credentials
|
||||
|
||||
1. Log in to [Cloudflare Dashboard](https://dash.cloudflare.com)
|
||||
2. Select your domain (e.g., `example.com`)
|
||||
3. In the sidebar, find **Zone ID** (copy this)
|
||||
4. Go to **Account Settings > API Tokens**
|
||||
5. Create a new token with these scopes:
|
||||
- **Zone > Zone:Read** (to list DNS records)
|
||||
- **Zone > DNS:Write** (to create/delete challenge records)
|
||||
6. Copy the API token
|
||||
|
||||
### Step 2: Set Environment Variables
|
||||
|
||||
Create a `.env` file in this directory:
|
||||
|
||||
```bash
|
||||
# .env
|
||||
CLOUDFLARE_API_TOKEN=your-api-token-here
|
||||
CLOUDFLARE_ZONE_ID=your-zone-id-here
|
||||
ACME_EMAIL=admin@example.com
|
||||
DB_PASSWORD=your-secure-db-password
|
||||
```
|
||||
|
||||
Or export them in your shell:
|
||||
|
||||
```bash
|
||||
export CLOUDFLARE_API_TOKEN="your-api-token-here"
|
||||
export CLOUDFLARE_ZONE_ID="your-zone-id-here"
|
||||
export ACME_EMAIL="admin@example.com"
|
||||
export DB_PASSWORD="your-secure-db-password"
|
||||
```
|
||||
|
||||
### Step 3: Make DNS Scripts Executable
|
||||
|
||||
```bash
|
||||
chmod +x dns-hooks/*.sh
|
||||
```
|
||||
|
||||
### Step 4: Start the Stack
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
This starts:
|
||||
- **certctl-server** (port 8443): Control plane and ACME orchestrator
|
||||
- **postgres**: Certificate metadata database
|
||||
- **certctl-agent**: Certificate deployment agent
|
||||
|
||||
### Step 5: Access the Dashboard
|
||||
|
||||
Open your browser to `http://localhost:8443`
|
||||
|
||||
### Step 6: Create a Wildcard Certificate
|
||||
|
||||
1. Go to **Issuers** page
|
||||
2. Verify the ACME issuer is registered
|
||||
3. Go to **Certificates** > **New Certificate**
|
||||
4. Fill in:
|
||||
- **Issuer:** ACME (Let's Encrypt)
|
||||
- **Common Name:** `*.example.com`
|
||||
- **Subject Alt Names:** `example.com` (to also cover the root domain)
|
||||
5. Click **Request**
|
||||
|
||||
The renewal job will:
|
||||
1. Send a request to Let's Encrypt
|
||||
2. Run `dns-hooks/cloudflare-present.sh` to create `_acme-challenge.example.com` TXT record
|
||||
3. Wait for Let's Encrypt to verify the TXT record
|
||||
4. Issue the certificate
|
||||
5. Run `dns-hooks/cloudflare-cleanup.sh` to delete the temporary TXT record
|
||||
|
||||
### Step 7: Monitor the Job
|
||||
|
||||
Go to **Jobs** page to see the renewal progress:
|
||||
- **AwaitingCSR**: Agent is generating the CSR
|
||||
- **Running**: ACME challenge in progress (DNS record being validated)
|
||||
- **Completed**: Certificate issued and stored
|
||||
- **Failed**: Check logs for errors (e.g., DNS provider API issues)
|
||||
|
||||
## How DNS-01 Works
|
||||
|
||||
The DNS-01 challenge proves you own a domain by creating a DNS TXT record:
|
||||
|
||||
```
|
||||
_acme-challenge.example.com TXT "acme-validation-token-xxxxx"
|
||||
```
|
||||
|
||||
Let's Encrypt then queries this TXT record. Once verified, it issues the certificate and certctl cleans up the TXT record.
|
||||
|
||||
**Why DNS-01 is better than HTTP-01 for wildcards:**
|
||||
- HTTP-01 requires a public web server; DNS-01 works anywhere
|
||||
- Wildcard certificates require DNS proof (not HTTP)
|
||||
- DNS challenges can be solved for multiple domains in parallel
|
||||
- No need for public IP or inbound port 80/443
|
||||
|
||||
## Adapting for Other DNS Providers
|
||||
|
||||
The example uses Cloudflare, but certctl supports **any DNS provider via pluggable shell scripts**.
|
||||
|
||||
### AWS Route53
|
||||
|
||||
Replace the `CERTCTL_ACME_DNS_PRESENT_SCRIPT` and `CERTCTL_ACME_DNS_CLEANUP_SCRIPT` in `docker-compose.yml` with:
|
||||
- `./dns-hooks/route53-present.sh`
|
||||
- `./dns-hooks/route53-cleanup.sh`
|
||||
|
||||
Example script outline (using AWS CLI):
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
DOMAIN="$1"
|
||||
VALIDATION_TOKEN="$2"
|
||||
|
||||
# Get Route53 hosted zone ID for the domain
|
||||
ZONE_ID=$(aws route53 list-hosted-zones --query \
|
||||
"HostedZones[?Name=='$DOMAIN.'].Id" --output text | cut -d'/' -f3)
|
||||
|
||||
# Create TXT record
|
||||
aws route53 change-resource-record-sets \
|
||||
--hosted-zone-id "$ZONE_ID" \
|
||||
--change-batch "{
|
||||
\"Changes\": [{
|
||||
\"Action\": \"CREATE\",
|
||||
\"ResourceRecordSet\": {
|
||||
\"Name\": \"_acme-challenge.$DOMAIN\",
|
||||
\"Type\": \"TXT\",
|
||||
\"TTL\": 120,
|
||||
\"ResourceRecords\": [{\"Value\": \"\\\"$VALIDATION_TOKEN\\\"\"}]
|
||||
}
|
||||
}]
|
||||
}"
|
||||
```
|
||||
|
||||
### Azure DNS
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
DOMAIN="$1"
|
||||
VALIDATION_TOKEN="$2"
|
||||
|
||||
# Set Azure credentials via environment variables
|
||||
# AZURE_SUBSCRIPTION_ID, AZURE_RESOURCE_GROUP, AZURE_TENANT_ID, etc.
|
||||
|
||||
az network dns record-set txt create \
|
||||
--resource-group "$AZURE_RESOURCE_GROUP" \
|
||||
--zone-name "$DOMAIN" \
|
||||
--name "_acme-challenge" \
|
||||
--ttl 120 \
|
||||
--txt-value "$VALIDATION_TOKEN"
|
||||
```
|
||||
|
||||
### Generic DNS Provider (using dig + TSIG)
|
||||
|
||||
If your DNS provider supports NSUPDATE (RFC 2136):
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
DOMAIN="$1"
|
||||
VALIDATION_TOKEN="$2"
|
||||
|
||||
nsupdate <<EOF
|
||||
zone $DOMAIN
|
||||
update add _acme-challenge.$DOMAIN 120 TXT "$VALIDATION_TOKEN"
|
||||
send
|
||||
EOF
|
||||
```
|
||||
|
||||
### Manual DNS (for testing)
|
||||
|
||||
Replace scripts with no-ops during testing:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
echo "Please create: _acme-challenge.$1 TXT $2"
|
||||
sleep 60 # Manual wait for you to create the record
|
||||
```
|
||||
|
||||
## Alternative: DNS-PERSIST-01 (Standing Records)
|
||||
|
||||
If your DNS provider supports it, use **DNS-PERSIST-01** for zero-maintenance renewals.
|
||||
|
||||
Instead of creating a new TXT record for each renewal, you create one standing record once:
|
||||
|
||||
```
|
||||
_validation-persist.example.com TXT "letsencrypt.org; accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/12345678"
|
||||
```
|
||||
|
||||
Then every renewal uses the same record — no cleanup scripts needed!
|
||||
|
||||
To enable in `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
CERTCTL_ACME_CHALLENGE_TYPE: dns-persist-01
|
||||
CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN: letsencrypt.org
|
||||
```
|
||||
|
||||
Certctl will:
|
||||
1. Fetch your ACME account URI
|
||||
2. Create the standing `_validation-persist` record once
|
||||
3. Reuse it for all future renewals (no per-renewal DNS updates)
|
||||
|
||||
## Security Notes
|
||||
|
||||
1. **API Token Scope:** Restrict Cloudflare/AWS tokens to DNS:write only (not full account access)
|
||||
2. **Key Generation:** This example uses agent-side key generation (`CERTCTL_KEYGEN_MODE=agent`), which is production-standard. Private keys never leave the agent.
|
||||
3. **Script Safety:** The DNS scripts run in the certctl-server container. For production:
|
||||
- Validate script inputs (already done in certctl code)
|
||||
- Log all API calls
|
||||
- Monitor for failed DNS operations
|
||||
- Use a separate proxy agent for DNS operations if needed
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### DNS record not created
|
||||
|
||||
Check the server logs:
|
||||
|
||||
```bash
|
||||
docker logs certctl-server-dns01
|
||||
```
|
||||
|
||||
Look for lines like:
|
||||
- `[certctl DNS-01] Creating DNS record: _acme-challenge.example.com`
|
||||
- `Error: Cloudflare API failed: ...`
|
||||
|
||||
**Common issues:**
|
||||
- Missing or invalid `CLOUDFLARE_API_TOKEN`
|
||||
- Invalid `CLOUDFLARE_ZONE_ID`
|
||||
- API token doesn't have DNS:write permission
|
||||
- Domain not in your Cloudflare account
|
||||
|
||||
### DNS propagation timeout
|
||||
|
||||
If the TLS negotiation fails, it might be DNS caching. Increase the wait time in the script:
|
||||
|
||||
```bash
|
||||
sleep 30 # Increase from 10 to 30 seconds
|
||||
```
|
||||
|
||||
### Let's Encrypt rate limits
|
||||
|
||||
Let's Encrypt has strict rate limits:
|
||||
- 50 certificates per registered domain per week
|
||||
- 5 duplicate certificates per domain per week
|
||||
|
||||
For testing, use the **staging directory**:
|
||||
|
||||
```yaml
|
||||
CERTCTL_ACME_DIRECTORY_URL: https://acme-staging-v02.api.letsencrypt.org/directory
|
||||
```
|
||||
|
||||
(Staging certs won't be trusted by browsers, but don't count against rate limits.)
|
||||
|
||||
### Job fails with "CSR generation timeout"
|
||||
|
||||
If your DNS provider is very slow, increase the timeout in the cleanup script or add a longer wait time:
|
||||
|
||||
```bash
|
||||
sleep 60 # Wait 1 minute for DNS propagation
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Monitor renewals:** Set up notifications (email, Slack, PagerDuty) for renewal events
|
||||
2. **Deploy certificates:** Configure target connectors (NGINX, HAProxy, Traefik) to automatically deploy issued certs
|
||||
3. **Multi-domain:** Use certificate profiles to group wildcard + subdomain certs
|
||||
4. **Backup DNS scripts:** Version control your DNS provider scripts in git
|
||||
|
||||
## Files in This Example
|
||||
|
||||
- **docker-compose.yml** — Container stack definition with ACME DNS-01 configuration
|
||||
- **dns-hooks/cloudflare-present.sh** — Creates `_acme-challenge` TXT record (Cloudflare)
|
||||
- **dns-hooks/cloudflare-cleanup.sh** — Deletes `_acme-challenge` TXT record (Cloudflare)
|
||||
- **README.md** — This file
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [certctl Documentation](../../docs/)
|
||||
- [ACME Specification (RFC 8555)](https://tools.ietf.org/html/rfc8555)
|
||||
- [DNS-01 Challenge Details](https://letsencrypt.org/docs/challenge-types/#dns-01)
|
||||
- [DNS-PERSIST-01 (IETF Draft)](https://datatracker.ietf.org/doc/html/draft-ietf-acme-dns-persist)
|
||||
- [Let's Encrypt Documentation](https://letsencrypt.org/docs/)
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/bin/bash
|
||||
|
||||
#
|
||||
# Cloudflare DNS-01 Challenge Script (CLEANUP)
|
||||
#
|
||||
# This script removes a DNS TXT record after ACME DNS-01 challenge validation.
|
||||
# Called by certctl after certificate issuance to clean up temporary challenge records.
|
||||
#
|
||||
# certctl sets these environment variables before invoking this script:
|
||||
# CERTCTL_DNS_DOMAIN - Base domain (e.g., "example.com")
|
||||
# CERTCTL_DNS_FQDN - Full challenge FQDN (e.g., "_acme-challenge.example.com")
|
||||
# CERTCTL_DNS_VALUE - Challenge value/token that was in the TXT record
|
||||
#
|
||||
# You must set these environment variables before running:
|
||||
# CLOUDFLARE_API_TOKEN - Cloudflare API token with DNS:write permission
|
||||
# CLOUDFLARE_ZONE_ID - Cloudflare zone ID for your domain
|
||||
#
|
||||
# Error Handling:
|
||||
# This script exits 0 on success, non-zero on failure.
|
||||
# If cleanup fails, certctl logs the error but doesn't block renewals.
|
||||
#
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Get values from certctl environment variables
|
||||
DOMAIN="${CERTCTL_DNS_DOMAIN:-}"
|
||||
RECORD_NAME="${CERTCTL_DNS_FQDN:-}"
|
||||
VALIDATION_TOKEN="${CERTCTL_DNS_VALUE:-}"
|
||||
|
||||
# Validate inputs
|
||||
if [[ -z "$DOMAIN" || -z "$RECORD_NAME" || -z "$VALIDATION_TOKEN" ]]; then
|
||||
echo "Error: Required certctl environment variables not set (CERTCTL_DNS_DOMAIN, CERTCTL_DNS_FQDN, CERTCTL_DNS_VALUE)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate environment
|
||||
if [[ -z "${CLOUDFLARE_API_TOKEN:-}" ]]; then
|
||||
echo "Error: CLOUDFLARE_API_TOKEN environment variable not set" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ -z "${CLOUDFLARE_ZONE_ID:-}" ]]; then
|
||||
echo "Error: CLOUDFLARE_ZONE_ID environment variable not set" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate RECORD_NAME (set by certctl above)
|
||||
RECORD_TYPE="TXT"
|
||||
|
||||
# Cloudflare API endpoint
|
||||
CF_API="https://api.cloudflare.com/client/v4"
|
||||
CF_ZONE="$CLOUDFLARE_ZONE_ID"
|
||||
CF_TOKEN="$CLOUDFLARE_API_TOKEN"
|
||||
|
||||
echo "[certctl DNS-01] Cleaning up DNS record: $RECORD_NAME"
|
||||
|
||||
# Step 1: Find the record ID
|
||||
RECORD_ID=$(curl -s -X GET \
|
||||
"$CF_API/zones/$CF_ZONE/dns_records?name=$RECORD_NAME&type=$RECORD_TYPE" \
|
||||
-H "Authorization: Bearer $CF_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
| jq -r '.result | if length > 0 then .[0].id else "" end')
|
||||
|
||||
if [[ -z "$RECORD_ID" ]]; then
|
||||
echo "[certctl DNS-01] Record not found (already deleted?). Skipping cleanup."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Step 2: Delete the record (DELETE /zones/{zone_id}/dns_records/{record_id})
|
||||
echo "[certctl DNS-01] Deleting DNS record (ID: $RECORD_ID)..."
|
||||
RESPONSE=$(curl -s -X DELETE \
|
||||
"$CF_API/zones/$CF_ZONE/dns_records/$RECORD_ID" \
|
||||
-H "Authorization: Bearer $CF_TOKEN" \
|
||||
-H "Content-Type: application/json")
|
||||
|
||||
# Check response success
|
||||
SUCCESS=$(echo "$RESPONSE" | jq -r '.success')
|
||||
if [[ "$SUCCESS" != "true" ]]; then
|
||||
ERROR=$(echo "$RESPONSE" | jq -r '.errors[0].message // "Unknown error"')
|
||||
echo "Warning: Cloudflare API failed to delete record: $ERROR" >&2
|
||||
# Don't exit 1 here — DNS cleanup is best-effort; cleanup failures shouldn't block certs
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "[certctl DNS-01] Successfully deleted DNS record"
|
||||
exit 0
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/bin/bash
|
||||
|
||||
#
|
||||
# Cloudflare DNS-01 Challenge Script (PRESENT)
|
||||
#
|
||||
# This script creates a DNS TXT record for ACME DNS-01 challenge validation.
|
||||
# Called by certctl during the renewal process to prove domain ownership.
|
||||
#
|
||||
# certctl sets these environment variables before invoking this script:
|
||||
# CERTCTL_DNS_DOMAIN - Base domain (e.g., "example.com")
|
||||
# CERTCTL_DNS_FQDN - Full challenge FQDN (e.g., "_acme-challenge.example.com")
|
||||
# CERTCTL_DNS_VALUE - Challenge value/token to place in the TXT record
|
||||
#
|
||||
# You must set these environment variables before running:
|
||||
# CLOUDFLARE_API_TOKEN - Cloudflare API token with DNS:write permission
|
||||
# CLOUDFLARE_ZONE_ID - Cloudflare zone ID for your domain
|
||||
# (Find at: https://dash.cloudflare.com > Select Domain > Zone ID in sidebar)
|
||||
#
|
||||
# Error Handling:
|
||||
# This script exits 0 on success, non-zero on failure.
|
||||
# certctl will retry the renewal if this script fails.
|
||||
#
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Get values from certctl environment variables
|
||||
DOMAIN="${CERTCTL_DNS_DOMAIN:-}"
|
||||
RECORD_NAME="${CERTCTL_DNS_FQDN:-}"
|
||||
VALIDATION_TOKEN="${CERTCTL_DNS_VALUE:-}"
|
||||
|
||||
# Validate inputs
|
||||
if [[ -z "$DOMAIN" || -z "$RECORD_NAME" || -z "$VALIDATION_TOKEN" ]]; then
|
||||
echo "Error: Required certctl environment variables not set (CERTCTL_DNS_DOMAIN, CERTCTL_DNS_FQDN, CERTCTL_DNS_VALUE)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate environment
|
||||
if [[ -z "${CLOUDFLARE_API_TOKEN:-}" ]]; then
|
||||
echo "Error: CLOUDFLARE_API_TOKEN environment variable not set" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ -z "${CLOUDFLARE_ZONE_ID:-}" ]]; then
|
||||
echo "Error: CLOUDFLARE_ZONE_ID environment variable not set" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate RECORD_NAME (set by certctl above)
|
||||
RECORD_TYPE="TXT"
|
||||
RECORD_TTL=120 # Short TTL for challenge records (1-2 min)
|
||||
|
||||
# Cloudflare API endpoint
|
||||
CF_API="https://api.cloudflare.com/client/v4"
|
||||
CF_ZONE="$CLOUDFLARE_ZONE_ID"
|
||||
CF_TOKEN="$CLOUDFLARE_API_TOKEN"
|
||||
|
||||
echo "[certctl DNS-01] Creating DNS record: $RECORD_NAME = $VALIDATION_TOKEN"
|
||||
|
||||
# Step 1: Check if record already exists (GET /zones/{zone_id}/dns_records)
|
||||
# This is optional but helps with idempotency
|
||||
EXISTING=$(curl -s -X GET \
|
||||
"$CF_API/zones/$CF_ZONE/dns_records?name=$RECORD_NAME&type=$RECORD_TYPE" \
|
||||
-H "Authorization: Bearer $CF_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
| jq -r '.result | if length > 0 then .[0].id else "" end')
|
||||
|
||||
if [[ -n "$EXISTING" ]]; then
|
||||
echo "[certctl DNS-01] Record already exists (ID: $EXISTING). Updating..."
|
||||
# Update existing record
|
||||
RESPONSE=$(curl -s -X PUT \
|
||||
"$CF_API/zones/$CF_ZONE/dns_records/$EXISTING" \
|
||||
-H "Authorization: Bearer $CF_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"type\": \"$RECORD_TYPE\",
|
||||
\"name\": \"$RECORD_NAME\",
|
||||
\"content\": \"$VALIDATION_TOKEN\",
|
||||
\"ttl\": $RECORD_TTL
|
||||
}")
|
||||
else
|
||||
echo "[certctl DNS-01] Creating new DNS record..."
|
||||
# Create new record
|
||||
RESPONSE=$(curl -s -X POST \
|
||||
"$CF_API/zones/$CF_ZONE/dns_records" \
|
||||
-H "Authorization: Bearer $CF_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"type\": \"$RECORD_TYPE\",
|
||||
\"name\": \"$RECORD_NAME\",
|
||||
\"content\": \"$VALIDATION_TOKEN\",
|
||||
\"ttl\": $RECORD_TTL
|
||||
}")
|
||||
fi
|
||||
|
||||
# Check response success
|
||||
SUCCESS=$(echo "$RESPONSE" | jq -r '.success')
|
||||
if [[ "$SUCCESS" != "true" ]]; then
|
||||
ERROR=$(echo "$RESPONSE" | jq -r '.errors[0].message // "Unknown error"')
|
||||
echo "Error: Cloudflare API failed: $ERROR" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
RECORD_ID=$(echo "$RESPONSE" | jq -r '.result.id')
|
||||
echo "[certctl DNS-01] Successfully created/updated DNS record (ID: $RECORD_ID)"
|
||||
echo "[certctl DNS-01] Waiting for DNS propagation..."
|
||||
sleep 10
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,171 @@
|
||||
version: '3.8'
|
||||
|
||||
# ACME Wildcard DNS-01 Example
|
||||
#
|
||||
# This example demonstrates how to use certctl with Let's Encrypt to issue wildcard
|
||||
# certificates (*.example.com) using DNS-01 challenge validation.
|
||||
#
|
||||
# DNS-01 is ideal for:
|
||||
# - Wildcard certificates (*.domain.com)
|
||||
# - Services behind NAT or non-public networks
|
||||
# - Batch certificate issuance (multiple domains in parallel)
|
||||
#
|
||||
# It works by:
|
||||
# 1. certctl creates a renewal job for a wildcard certificate
|
||||
# 2. Let's Encrypt sends an ACME challenge: "create _acme-challenge TXT record with value X"
|
||||
# 3. certctl runs the dns-present.sh script to create the TXT record via your DNS provider API
|
||||
# 4. Let's Encrypt verifies the TXT record exists
|
||||
# 5. Certificate is issued
|
||||
# 6. certctl runs dns-cleanup.sh to remove the TXT record
|
||||
#
|
||||
# This compose file also demonstrates:
|
||||
# - ACME issuer with DNS-01 challenge type
|
||||
# - Pluggable DNS provider scripts (Cloudflare example included; adapt for Route53, Azure DNS, etc.)
|
||||
# - Wildcard and multi-SAN certificate support
|
||||
# - Agent-side key generation (production-ready)
|
||||
|
||||
services:
|
||||
# PostgreSQL database for certctl metadata
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: certctl-postgres-dns01
|
||||
environment:
|
||||
POSTGRES_DB: certctl
|
||||
POSTGRES_USER: certctl
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-certctl-dev-password}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U certctl -d certctl']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl server (control plane + ACME orchestration)
|
||||
certctl-server:
|
||||
image: ghcr.io/shankar0123/certctl-server:latest
|
||||
container_name: certctl-server-dns01
|
||||
environment:
|
||||
# Database
|
||||
CERTCTL_DATABASE_URL: postgres://certctl:${DB_PASSWORD:-certctl-dev-password}@postgres:5432/certctl?sslmode=disable
|
||||
|
||||
# Server settings
|
||||
CERTCTL_SERVER_PORT: 8443
|
||||
CERTCTL_SERVER_HOST: 0.0.0.0
|
||||
|
||||
# Auth (disabled for demo; production should use API keys with CERTCTL_AUTH_TYPE=api-key)
|
||||
CERTCTL_AUTH_TYPE: none
|
||||
|
||||
# CORS (allow agent communication)
|
||||
CERTCTL_CORS_ORIGINS: '*'
|
||||
|
||||
# Key generation mode (agent-side: keys never leave agents; production standard)
|
||||
CERTCTL_KEYGEN_MODE: agent
|
||||
|
||||
# ===== ACME Issuer Configuration (DNS-01 Wildcard) =====
|
||||
# Let's Encrypt production directory (ACME v2)
|
||||
CERTCTL_ACME_DIRECTORY_URL: https://acme-v02.api.letsencrypt.org/directory
|
||||
|
||||
# Email for certificate expiration notices and account recovery
|
||||
CERTCTL_ACME_EMAIL: ${ACME_EMAIL:-admin@example.com}
|
||||
|
||||
# Challenge type: dns-01 (not http-01, which doesn't support wildcards)
|
||||
CERTCTL_ACME_CHALLENGE_TYPE: dns-01
|
||||
|
||||
# DNS present script: creates _acme-challenge TXT record
|
||||
# The script is mounted from ./dns-hooks/cloudflare-present.sh
|
||||
# Arguments: $1 = domain (e.g., "example.com"), $2 = validation token
|
||||
CERTCTL_ACME_DNS_PRESENT_SCRIPT: /etc/certctl/dns-hooks/cloudflare-present.sh
|
||||
|
||||
# DNS cleanup script: removes _acme-challenge TXT record
|
||||
# Arguments: $1 = domain, $2 = validation token
|
||||
CERTCTL_ACME_DNS_CLEANUP_SCRIPT: /etc/certctl/dns-hooks/cloudflare-cleanup.sh
|
||||
|
||||
# Optional: DNS propagation wait time (seconds) before proceeding to next challenge
|
||||
# Default is 30s; increase if your DNS propagates slowly
|
||||
# Set via CERTCTL_ACME_DNS_PROPAGATION_WAIT in code, or rely on default
|
||||
|
||||
# Optional: Let's Encrypt Renewal Information (RFC 9702) for CA-directed renewal timing
|
||||
# CERTCTL_ACME_ARI_ENABLED: "true"
|
||||
|
||||
# Local CA as fallback for internal services (optional)
|
||||
CERTCTL_CA_CERT_PATH: /etc/certctl/ca.crt
|
||||
CERTCTL_CA_KEY_PATH: /etc/certctl/ca.key
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
|
||||
ports:
|
||||
- '${SERVER_PORT:-8443}:8443'
|
||||
|
||||
volumes:
|
||||
# Mount DNS provider scripts (adapt these for your DNS provider)
|
||||
- ./dns-hooks:/etc/certctl/dns-hooks:ro
|
||||
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
networks:
|
||||
- certctl-network
|
||||
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'curl -sf http://localhost:8443/health || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl agent (manages certificate deployment on target hosts)
|
||||
# In production, run agents on each host that needs certificates.
|
||||
# For demo, we include one agent in this compose.
|
||||
certctl-agent:
|
||||
image: ghcr.io/shankar0123/certctl-agent:latest
|
||||
container_name: certctl-agent-dns01
|
||||
environment:
|
||||
# Control plane connection
|
||||
CERTCTL_SERVER_URL: http://certctl-server:8443
|
||||
CERTCTL_API_KEY: ${AGENT_API_KEY:-agent-demo-key}
|
||||
|
||||
# Key generation (agent-side keys: production-standard security model)
|
||||
CERTCTL_KEYGEN_MODE: agent
|
||||
CERTCTL_KEY_DIR: /var/lib/certctl/keys
|
||||
|
||||
# Discovery (scan existing certs so operator knows what's already deployed)
|
||||
CERTCTL_DISCOVERY_DIRS: /etc/letsencrypt/live:/etc/ssl/certs
|
||||
|
||||
# Heartbeat interval (how often agent checks for work)
|
||||
CERTCTL_HEARTBEAT_INTERVAL: 30s
|
||||
|
||||
# Agent metadata (self-reported to server)
|
||||
CERTCTL_AGENT_NAME: wildcard-agent-01
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
|
||||
volumes:
|
||||
# Agent persistent key storage (survives restarts)
|
||||
- agent_keys:/var/lib/certctl/keys
|
||||
|
||||
depends_on:
|
||||
certctl-server:
|
||||
condition: service_healthy
|
||||
|
||||
networks:
|
||||
- certctl-network
|
||||
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
certctl-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
driver: local
|
||||
agent_keys:
|
||||
driver: local
|
||||
@@ -0,0 +1,150 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
# PostgreSQL database for certctl
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: certctl-postgres-multi-issuer
|
||||
environment:
|
||||
POSTGRES_DB: certctl
|
||||
POSTGRES_USER: certctl
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-certctl-dev-password}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U certctl -d certctl']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl server (control plane)
|
||||
# Configured with BOTH ACME (Let's Encrypt) and Local CA issuers
|
||||
certctl-server:
|
||||
image: ghcr.io/shankar0123/certctl-server:latest
|
||||
container_name: certctl-server-multi-issuer
|
||||
environment:
|
||||
# Database
|
||||
CERTCTL_DATABASE_URL: postgres://certctl:${DB_PASSWORD:-certctl-dev-password}@postgres:5432/certctl?sslmode=disable
|
||||
|
||||
# Server settings
|
||||
CERTCTL_SERVER_PORT: 8443
|
||||
CERTCTL_SERVER_HOST: 0.0.0.0
|
||||
|
||||
# Auth (disabled for demo; production should use API keys)
|
||||
CERTCTL_AUTH_TYPE: none
|
||||
|
||||
# CORS (allow agent communication)
|
||||
CERTCTL_CORS_ORIGINS: '*'
|
||||
|
||||
# Key generation mode (agent-side in production, server-side for demo)
|
||||
CERTCTL_KEYGEN_MODE: server
|
||||
|
||||
# ACME issuer (Let's Encrypt for public-facing services)
|
||||
# Change CERTCTL_ACME_EMAIL to your email and CERTCTL_ACME_CHALLENGE_TYPE as needed
|
||||
CERTCTL_ACME_DIRECTORY_URL: https://acme-v02.api.letsencrypt.org/directory
|
||||
CERTCTL_ACME_EMAIL: ${ACME_EMAIL:-admin@example.com}
|
||||
CERTCTL_ACME_CHALLENGE_TYPE: http-01
|
||||
|
||||
# Local CA issuer (for internal services - self-signed or sub-CA)
|
||||
# Set these paths if you have an existing CA cert+key for sub-CA mode
|
||||
# Otherwise, leave empty for self-signed CA generation
|
||||
CERTCTL_CA_CERT_PATH: ${CA_CERT_PATH:-}
|
||||
CERTCTL_CA_KEY_PATH: ${CA_KEY_PATH:-}
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
ports:
|
||||
- '${SERVER_PORT:-8443}:8443'
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- certctl-network
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'curl -sf http://localhost:8443/health || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl agent (manages certificates on NGINX and application servers)
|
||||
certctl-agent:
|
||||
image: ghcr.io/shankar0123/certctl-agent:latest
|
||||
container_name: certctl-agent-multi-issuer
|
||||
environment:
|
||||
# Control plane connection
|
||||
CERTCTL_SERVER_URL: http://certctl-server:8443
|
||||
CERTCTL_API_KEY: ${AGENT_API_KEY:-agent-demo-key}
|
||||
|
||||
# Key generation (agent-side keys, never sent to server)
|
||||
CERTCTL_KEYGEN_MODE: server
|
||||
CERTCTL_KEY_DIR: /var/lib/certctl/keys
|
||||
|
||||
# Discovery (scan existing certs to track what's already deployed)
|
||||
CERTCTL_DISCOVERY_DIRS: /etc/nginx/ssl:/etc/app/ssl
|
||||
|
||||
# Heartbeat interval
|
||||
CERTCTL_HEARTBEAT_INTERVAL: 30s
|
||||
|
||||
# Agent metadata
|
||||
CERTCTL_AGENT_NAME: multi-issuer-agent-01
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
volumes:
|
||||
# Mount NGINX cert directories
|
||||
- nginx_certs:/etc/nginx/ssl
|
||||
- nginx_conf:/etc/nginx/conf.d
|
||||
# Mount application service cert directory
|
||||
- app_certs:/etc/app/ssl
|
||||
# Agent key storage (persisted across restarts)
|
||||
- agent_keys:/var/lib/certctl/keys
|
||||
depends_on:
|
||||
certctl-server:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# NGINX reverse proxy / web server
|
||||
# This is where public TLS certs (from ACME) will be deployed
|
||||
nginx:
|
||||
image: nginx:alpine
|
||||
container_name: certctl-nginx-multi-issuer
|
||||
ports:
|
||||
- '80:80'
|
||||
- '443:443'
|
||||
volumes:
|
||||
- nginx_conf:/etc/nginx/conf.d
|
||||
- nginx_certs:/etc/nginx/ssl
|
||||
# Default NGINX config
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
depends_on:
|
||||
- certctl-agent
|
||||
networks:
|
||||
- certctl-network
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'wget --quiet --tries=1 --spider http://localhost/ || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
certctl-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
driver: local
|
||||
nginx_certs:
|
||||
driver: local
|
||||
nginx_conf:
|
||||
driver: local
|
||||
app_certs:
|
||||
driver: local
|
||||
agent_keys:
|
||||
driver: local
|
||||
@@ -0,0 +1,244 @@
|
||||
# Multi-Issuer Example: ACME + Local CA
|
||||
|
||||
This example demonstrates certctl managing **both public and internal certificates from a single dashboard**. Public-facing services use Let's Encrypt (ACME), while internal services use a private Local CA — all visible and managed in one place.
|
||||
|
||||
## The Use Case
|
||||
|
||||
You have:
|
||||
- **Public-facing services** (web app, API, etc.) that need TLS certs signed by a trusted public CA (Let's Encrypt)
|
||||
- **Internal services** (databases, microservices, middleware) that need TLS certs but don't require public trust
|
||||
- **One team** managing certs across both, needing unified visibility and automated renewal
|
||||
|
||||
With certctl, both issuer types are configured and available. You assign each certificate to the appropriate issuer via its profile or at enrollment time. The dashboard shows all certs together, with renewal status, expiration timelines, and audit trails — regardless of which CA issued them.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Server ["certctl Server (Control Plane)"]
|
||||
A["Let's Encrypt ACME issuer<br/>(HTTP-01 challenges)"]
|
||||
B["Local CA issuer<br/>(self-signed or sub-CA mode)"]
|
||||
C["PostgreSQL database<br/>(cert inventory, audit, jobs)"]
|
||||
end
|
||||
|
||||
subgraph Agent ["certctl Agent"]
|
||||
D["Discovers existing certs<br/>(/etc/nginx/ssl, /etc/app/ssl)"]
|
||||
E["Polls server for<br/>renewal/issuance/deployment jobs"]
|
||||
F["Generates keys locally<br/>(agent-side crypto)"]
|
||||
G["Deploys certs to NGINX<br/>and app service directories"]
|
||||
end
|
||||
|
||||
subgraph Targets ["Target Services"]
|
||||
H["NGINX (public TLS)<br/>(Let's Encrypt certs)"]
|
||||
I["App Services (internal TLS)<br/>(Local CA certs)"]
|
||||
end
|
||||
|
||||
Server -->|API polling| Agent
|
||||
Agent -->|Deploy| H
|
||||
Agent -->|Deploy| I
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Docker & Docker Compose** — containers run everything
|
||||
- **Port access** — 80 (HTTP-01 challenges) and 443 (HTTPS) for Let's Encrypt
|
||||
- **Domain for ACME** (optional) — if using real Let's Encrypt, not needed for demo
|
||||
- **Internet connectivity** — to reach Let's Encrypt's API (demo can use staging directory)
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Clone or navigate to this directory
|
||||
|
||||
```bash
|
||||
cd examples/multi-issuer
|
||||
```
|
||||
|
||||
### 2. Set environment variables (optional, defaults provided)
|
||||
|
||||
```bash
|
||||
# Email for Let's Encrypt account
|
||||
export ACME_EMAIL="your-email@example.com"
|
||||
|
||||
# Database password (for demo, default is fine)
|
||||
export DB_PASSWORD="certctl-dev-password"
|
||||
|
||||
# Agent API key
|
||||
export AGENT_API_KEY="agent-demo-key"
|
||||
|
||||
# Server port (default 8443)
|
||||
export SERVER_PORT="8443"
|
||||
```
|
||||
|
||||
### 3. Start the services
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
This spins up:
|
||||
- **PostgreSQL** database (certctl data store)
|
||||
- **certctl server** with ACME and Local CA issuers configured
|
||||
- **certctl agent** discovering existing certs and polling for work
|
||||
- **NGINX** web server (target for public TLS certs)
|
||||
|
||||
### 4. Access the dashboard
|
||||
|
||||
Open your browser to **http://localhost:8443** (or your configured SERVER_PORT)
|
||||
|
||||
You should see:
|
||||
- Empty cert inventory (fresh start)
|
||||
- Two configured issuers: "ACME" and "Local CA"
|
||||
- One registered agent ("multi-issuer-agent-01")
|
||||
|
||||
### 5. Create test certificates
|
||||
|
||||
In the dashboard:
|
||||
|
||||
**For a public cert (Let's Encrypt):**
|
||||
1. Go to **Certificates** > **+ New Certificate**
|
||||
2. Common Name: `example.com` (or a test domain you control)
|
||||
3. Issuer: Select "ACME"
|
||||
4. Profile: Select default or create one (key type: RSA 2048, TTL: 90 days)
|
||||
5. Create → The server submits an ACME order
|
||||
|
||||
**For an internal cert (Local CA):**
|
||||
1. Go to **Certificates** > **+ New Certificate**
|
||||
2. Common Name: `internal-api.internal` (or any internal name)
|
||||
3. Issuer: Select "Local CA"
|
||||
4. Profile: Select default
|
||||
5. Create → The server issues immediately from the private CA
|
||||
|
||||
### 6. Monitor in the dashboard
|
||||
|
||||
- **Dashboard** — see cert counts by status and issuer
|
||||
- **Certificates** page — filter by issuer, see renewal status, expiration timeline
|
||||
- **Audit Trail** — track all operations (issuance, renewals, deployments)
|
||||
- **Agents** — view agent health and pending work
|
||||
|
||||
## How Issuer Assignment Works
|
||||
|
||||
### Via Profiles
|
||||
Create a profile for each issuer type:
|
||||
- Profile **public-tls** → Issuer: ACME, TTL: 90 days, allowed domains: `*.example.com`
|
||||
- Profile **internal-tls** → Issuer: Local CA, TTL: 1 year, allowed SANs: internal DNS names
|
||||
|
||||
Then create certificates using the appropriate profile.
|
||||
|
||||
### Via Direct Assignment
|
||||
When creating a certificate, explicitly select the issuer. The certificate remembers which issuer it belongs to.
|
||||
|
||||
## ACME Configuration
|
||||
|
||||
The server is configured with Let's Encrypt's production directory:
|
||||
|
||||
```yaml
|
||||
CERTCTL_ACME_DIRECTORY_URL: https://acme-v02.api.letsencrypt.org/directory
|
||||
CERTCTL_ACME_EMAIL: admin@example.com
|
||||
CERTCTL_ACME_CHALLENGE_TYPE: http-01
|
||||
```
|
||||
|
||||
**For testing without a real domain**, use Let's Encrypt's staging directory:
|
||||
|
||||
```bash
|
||||
# Edit docker-compose.yml and change:
|
||||
CERTCTL_ACME_DIRECTORY_URL: https://acme-staging-v02.api.letsencrypt.org/directory
|
||||
```
|
||||
|
||||
Staging certs are untrusted (for testing only) but unlimited rate limits.
|
||||
|
||||
## Local CA Configuration
|
||||
|
||||
The Local CA issuer can operate in two modes:
|
||||
|
||||
### Mode 1: Self-Signed (Default)
|
||||
Leave `CERTCTL_CA_CERT_PATH` and `CERTCTL_CA_KEY_PATH` empty. The server generates a self-signed root CA on first run.
|
||||
|
||||
```yaml
|
||||
CERTCTL_CA_CERT_PATH: ""
|
||||
CERTCTL_CA_KEY_PATH: ""
|
||||
```
|
||||
|
||||
**Use case:** Development, testing, internal services that trust a self-signed root.
|
||||
|
||||
### Mode 2: Sub-CA (Enterprise)
|
||||
Provide an existing CA cert + key (e.g., from your organization's PKI). The Local CA issues certs signed by that intermediate.
|
||||
|
||||
```bash
|
||||
# In docker-compose.yml, volume-mount your CA cert+key:
|
||||
volumes:
|
||||
- /path/to/ca.crt:/etc/certctl/ca.crt:ro
|
||||
- /path/to/ca.key:/etc/certctl/ca.key:ro
|
||||
|
||||
# And set env vars:
|
||||
CERTCTL_CA_CERT_PATH: /etc/certctl/ca.crt
|
||||
CERTCTL_CA_KEY_PATH: /etc/certctl/ca.key
|
||||
```
|
||||
|
||||
**Use case:** Enterprise internal PKI where certs need to chain to a trusted root (e.g., Windows ADCS, OpenSSL, Vault PKI).
|
||||
|
||||
## Deployment Flow
|
||||
|
||||
When you create a certificate and assign it for deployment:
|
||||
|
||||
1. **Issuance** — Server calls the issuer connector (ACME or Local CA)
|
||||
- ACME: submit challenge, poll until DNS/HTTP validated, retrieve cert
|
||||
- Local CA: generate and sign immediately
|
||||
|
||||
2. **Agent picks up work** — Agent polls `/api/v1/agents/{id}/work`
|
||||
|
||||
3. **Agent deployment** — Agent places cert+key in the target directory
|
||||
- NGINX: `/etc/nginx/ssl/` (mounted volume)
|
||||
- App services: `/etc/app/ssl/` (mounted volume)
|
||||
|
||||
4. **Service reload** — Agent triggers reload (NGINX: `nginx -s reload`, etc.)
|
||||
|
||||
5. **Dashboard reflects status** — Job transitions from `Running` → `Completed`, cert shows as `Active`
|
||||
|
||||
## Scaling Beyond Docker Compose
|
||||
|
||||
In production:
|
||||
|
||||
- **Deploy certctl server** on a single node (or HA cluster with external PostgreSQL)
|
||||
- **Deploy certctl agents** on each server needing cert management
|
||||
- **Point agents to server URL** via `CERTCTL_SERVER_URL` env var
|
||||
- **Configure issuers on server** via env vars or (in V3+) the dashboard UI
|
||||
- **Use profiles to segment issuers** — operators select a profile at cert creation time
|
||||
|
||||
Each agent independently manages its local cert inventory and deployments. The server coordinates all agent work and provides the unified dashboard.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Certs aren't being issued
|
||||
- Check server logs: `docker compose logs certctl-server`
|
||||
- Verify issuer configuration: Dashboard → Issuers, click "Test Connection"
|
||||
- For ACME, ensure ports 80/443 are open and your domain resolves
|
||||
|
||||
### Agent can't reach server
|
||||
- Check network: `docker compose exec certctl-agent curl http://certctl-server:8443/health`
|
||||
- Verify `CERTCTL_SERVER_URL` environment variable
|
||||
|
||||
### No issuers showing up
|
||||
- Ensure env vars are set on the server container
|
||||
- Restart server: `docker compose restart certctl-server`
|
||||
- Check server logs for validation errors
|
||||
|
||||
### Let's Encrypt rate limits
|
||||
- Use the staging directory for testing (unlimited, untrusted certs)
|
||||
- Production directory: 50 certs per domain per week
|
||||
- Read more: https://letsencrypt.org/docs/rate-limits/
|
||||
|
||||
## Next Steps
|
||||
|
||||
- **Create a certificate profile** — Dashboard → Profiles → + New Profile
|
||||
- **Configure team ownership** — Dashboard → Owners/Teams (assign certs to teams)
|
||||
- **Set renewal policies** — Dashboard → Policies (expiration thresholds, auto-renewal)
|
||||
- **Enable notifications** — Configure Slack/Teams webhook to get alerts on renewals and expirations
|
||||
- **Explore discovery** — Agent scans `/etc/nginx/ssl` and `/etc/app/ssl`, Dashboard → Discovery shows what's already deployed
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [certctl Architecture](../../docs/architecture.md)
|
||||
- [ACME Connector Docs](../../docs/connectors.md#acme-letsencrypt)
|
||||
- [Local CA Connector Docs](../../docs/connectors.md#local-ca)
|
||||
- [Agent Configuration](../../docs/agent.md)
|
||||
- [Deployment Targets](../../docs/connectors.md#deployment-targets)
|
||||
@@ -0,0 +1,182 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
# PostgreSQL database for certctl
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: certctl-postgres-private-ca
|
||||
environment:
|
||||
POSTGRES_DB: certctl
|
||||
POSTGRES_USER: certctl
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-certctl-dev-password}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U certctl -d certctl']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl server (control plane) with Local CA in sub-CA mode
|
||||
certctl-server:
|
||||
image: ghcr.io/shankar0123/certctl-server:latest
|
||||
container_name: certctl-server-private-ca
|
||||
environment:
|
||||
# Database
|
||||
CERTCTL_DATABASE_URL: postgres://certctl:${DB_PASSWORD:-certctl-dev-password}@postgres:5432/certctl?sslmode=disable
|
||||
|
||||
# Server settings
|
||||
CERTCTL_SERVER_PORT: 8443
|
||||
CERTCTL_SERVER_HOST: 0.0.0.0
|
||||
|
||||
# Auth (disabled for demo; production should use API keys)
|
||||
CERTCTL_AUTH_TYPE: none
|
||||
|
||||
# CORS (allow agent and Traefik communication)
|
||||
CERTCTL_CORS_ORIGINS: '*'
|
||||
|
||||
# Key generation mode (agent-side in production, server-side for demo)
|
||||
CERTCTL_KEYGEN_MODE: server
|
||||
|
||||
# Local CA configuration
|
||||
# For self-signed CA (default, no paths set):
|
||||
# - CA generates a self-signed root certificate
|
||||
# - All issued certificates chain to this root
|
||||
#
|
||||
# For sub-CA mode (provide both paths):
|
||||
# - Load pre-signed CA certificate and key from these paths
|
||||
# - All issued certificates chain to your enterprise root CA
|
||||
# - Requires: CA cert must have IsCA=true and KeyUsageCertSign
|
||||
# - Supports: RSA, ECDSA, PKCS#8 key formats
|
||||
#
|
||||
# To use sub-CA mode:
|
||||
# 1. Place your enterprise CA cert at ./ca-cert.pem
|
||||
# 2. Place your enterprise CA key at ./ca-key.pem
|
||||
# 3. Uncomment the two lines below
|
||||
# 4. Restart the service
|
||||
#
|
||||
# CERTCTL_CA_CERT_PATH: /etc/certctl/ca-cert.pem
|
||||
# CERTCTL_CA_KEY_PATH: /etc/certctl/ca-key.pem
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
ports:
|
||||
- '${SERVER_PORT:-8443}:8443'
|
||||
volumes:
|
||||
# Mount directory for CA cert/key (for sub-CA mode)
|
||||
# Copy your enterprise CA cert+key here:
|
||||
# cp /path/to/your/ca.pem ./ca-cert.pem
|
||||
# cp /path/to/your/ca-key.pem ./ca-key.pem
|
||||
- ./ca-certs:/etc/certctl:ro
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- certctl-network
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'curl -sf http://localhost:8443/health || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl agent (deploys certs to Traefik)
|
||||
certctl-agent:
|
||||
image: ghcr.io/shankar0123/certctl-agent:latest
|
||||
container_name: certctl-agent-private-ca
|
||||
environment:
|
||||
# Control plane connection
|
||||
CERTCTL_SERVER_URL: http://certctl-server:8443
|
||||
CERTCTL_API_KEY: ${AGENT_API_KEY:-agent-demo-key}
|
||||
|
||||
# Key generation (agent-side keys, never sent to server)
|
||||
CERTCTL_KEYGEN_MODE: server
|
||||
CERTCTL_KEY_DIR: /var/lib/certctl/keys
|
||||
|
||||
# Discovery (scan for existing certs in Traefik's directory)
|
||||
CERTCTL_DISCOVERY_DIRS: /etc/traefik/certs
|
||||
|
||||
# Heartbeat interval
|
||||
CERTCTL_HEARTBEAT_INTERVAL: 30s
|
||||
|
||||
# Agent metadata (self-reported)
|
||||
CERTCTL_AGENT_NAME: traefik-agent-01
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
volumes:
|
||||
# Mount Traefik cert directory for deployment
|
||||
- traefik_certs:/etc/traefik/certs
|
||||
# Agent key storage (persisted across restarts)
|
||||
- agent_keys:/var/lib/certctl/keys
|
||||
depends_on:
|
||||
certctl-server:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# Traefik reverse proxy / edge router
|
||||
# Certificates deployed by certctl-agent are automatically loaded from the certs directory
|
||||
traefik:
|
||||
image: traefik:v3.0
|
||||
container_name: certctl-traefik-private-ca
|
||||
command:
|
||||
# Enable dashboard and API
|
||||
- '--api.insecure=true'
|
||||
- '--api.dashboard=true'
|
||||
|
||||
# File provider: watch the certs directory for dynamic config updates
|
||||
- '--providers.file.directory=/etc/traefik/dynamic'
|
||||
- '--providers.file.watch=true'
|
||||
|
||||
# Entry points (HTTP and HTTPS)
|
||||
- '--entrypoints.web.address=:80'
|
||||
- '--entrypoints.websecure.address=:443'
|
||||
- '--entrypoints.websecure.http.tls=true'
|
||||
|
||||
# Global TLS settings
|
||||
- '--entryPoints.websecure.http.tls.certResolver=internal'
|
||||
|
||||
# Logging
|
||||
- '--log.level=info'
|
||||
- '--accesslog=true'
|
||||
ports:
|
||||
# HTTP
|
||||
- '80:80'
|
||||
# HTTPS
|
||||
- '443:443'
|
||||
# Dashboard (http://localhost:8080)
|
||||
- '8080:8080'
|
||||
volumes:
|
||||
# Mount Traefik config directory
|
||||
- ./traefik-config:/etc/traefik/dynamic:ro
|
||||
# Mount cert directory (where certctl deploys certs)
|
||||
- traefik_certs:/etc/traefik/certs:ro
|
||||
# Allow Traefik to read Docker socket (optional, for container labeling)
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
networks:
|
||||
- certctl-network
|
||||
depends_on:
|
||||
- certctl-agent
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'curl -sf http://localhost:8080/ping || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
certctl-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
driver: local
|
||||
traefik_certs:
|
||||
driver: local
|
||||
agent_keys:
|
||||
driver: local
|
||||
@@ -0,0 +1,345 @@
|
||||
# Private CA + Traefik Example
|
||||
|
||||
This example demonstrates certctl managing certificates for **internal services without public CA dependency**. Ideal for enterprise environments where:
|
||||
|
||||
- All services are internal (VPN, private networks)
|
||||
- You need unified certificate lifecycle management across multiple internal apps
|
||||
- You want automatic cert deployment to your reverse proxy
|
||||
- You may have an existing enterprise root CA (ADCS, OpenCA, etc.)
|
||||
|
||||
## What's Included
|
||||
|
||||
- **certctl server** with Local CA issuer (self-signed or sub-CA mode)
|
||||
- **certctl agent** that deploys certificates to Traefik
|
||||
- **Traefik** reverse proxy with file provider for dynamic cert discovery
|
||||
- **PostgreSQL** database for certificate storage and audit trail
|
||||
- Automatic certificate discovery for existing certs in Traefik
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["certctl-server<br/>(control plane)<br/>(Local CA issuer)"]
|
||||
B["certctl-agent<br/>(certificate deployer)"]
|
||||
C["Traefik<br/>(watches cert directory)"]
|
||||
D["[Internal Services]"]
|
||||
|
||||
A -->|REST API<br/>job polling| B
|
||||
B -->|Write cert/key files| C
|
||||
C -->|TLS handshakes| D
|
||||
```
|
||||
|
||||
## Quick Start (Self-Signed CA)
|
||||
|
||||
The simplest way to get running in 2 minutes:
|
||||
|
||||
```bash
|
||||
# 1. Create directory structure
|
||||
mkdir -p traefik-config ca-certs
|
||||
|
||||
# 2. Create a minimal Traefik dynamic config
|
||||
cat > traefik-config/default.yaml << 'EOF'
|
||||
# Traefik will auto-load certificates from /etc/traefik/certs
|
||||
# Certctl deploys {cert-id}.crt and {cert-id}.key files here
|
||||
http:
|
||||
routers:
|
||||
api:
|
||||
rule: "Host(`api.internal.local`)"
|
||||
service: api-service
|
||||
tls: {}
|
||||
services:
|
||||
api-service:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: "http://localhost:3000"
|
||||
EOF
|
||||
|
||||
# 3. Start the stack
|
||||
docker compose up -d
|
||||
|
||||
# 4. Access the dashboards
|
||||
# - certctl: http://localhost:8443 (API only, use the CLI or direct HTTP calls)
|
||||
# - Traefik dashboard: http://localhost:8080
|
||||
```
|
||||
|
||||
The self-signed CA will be automatically generated on first startup.
|
||||
|
||||
## Using Sub-CA Mode (Enterprise Root CA)
|
||||
|
||||
If you have an existing enterprise CA (ADCS, OpenCA, etc.) and want issued certs to chain to your root:
|
||||
|
||||
```bash
|
||||
# 1. Create directory structure
|
||||
mkdir -p traefik-config ca-certs
|
||||
|
||||
# 2. Copy your enterprise CA cert and key
|
||||
cp /path/to/your/enterprise-ca.crt ca-certs/ca-cert.pem
|
||||
cp /path/to/your/enterprise-ca-key.pem ca-certs/ca-key.pem
|
||||
|
||||
# 3. Edit docker-compose.yml and uncomment the sub-CA env vars:
|
||||
# CERTCTL_CA_CERT_PATH: /etc/certctl/ca-cert.pem
|
||||
# CERTCTL_CA_KEY_PATH: /etc/certctl/ca-key.pem
|
||||
|
||||
# 4. Create the dynamic config (same as above)
|
||||
mkdir -p traefik-config
|
||||
cat > traefik-config/default.yaml << 'EOF'
|
||||
http:
|
||||
routers:
|
||||
api:
|
||||
rule: "Host(`api.internal.local`)"
|
||||
service: api-service
|
||||
tls: {}
|
||||
services:
|
||||
api-service:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: "http://localhost:3000"
|
||||
EOF
|
||||
|
||||
# 5. Start the stack
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
**Requirements for sub-CA mode:**
|
||||
- CA certificate must have `X509v3 Basic Constraints: CA:TRUE`
|
||||
- CA certificate must have `X509v3 Key Usage: Certificate Sign`
|
||||
- Key format: RSA, ECDSA, or PKCS#8
|
||||
- Paths: must be absolute paths to mounted files
|
||||
|
||||
## Creating a Certificate
|
||||
|
||||
Once the stack is running:
|
||||
|
||||
```bash
|
||||
# 1. Create a certificate profile in certctl (defines allowed key types, TTL, etc.)
|
||||
curl -X POST http://localhost:8443/api/v1/profiles \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"id": "prof-internal",
|
||||
"name": "Internal Services",
|
||||
"description": "For internal APIs and web apps",
|
||||
"max_ttl_hours": 8760,
|
||||
"key_types": ["rsa-2048", "ecdsa-p256"]
|
||||
}'
|
||||
|
||||
# 2. Create a renewal policy (defines issuer, renewal thresholds, etc.)
|
||||
curl -X POST http://localhost:8443/api/v1/policies \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"id": "pol-internal",
|
||||
"name": "Internal Renewal Policy",
|
||||
"issuer_id": "iss-local",
|
||||
"profile_id": "prof-internal",
|
||||
"renewal_threshold_days": 30,
|
||||
"alert_thresholds_days": [30, 14, 7, 0]
|
||||
}'
|
||||
|
||||
# 3. Create a certificate (triggers issuance immediately)
|
||||
curl -X POST http://localhost:8443/api/v1/certificates \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"common_name": "api.internal.local",
|
||||
"sans": ["app.internal.local", "www.internal.local"],
|
||||
"policy_id": "pol-internal"
|
||||
}'
|
||||
|
||||
# 4. Create a Traefik target (agent will deploy to this)
|
||||
curl -X POST http://localhost:8443/api/v1/targets \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"id": "target-traefik-01",
|
||||
"name": "Traefik Primary",
|
||||
"type": "traefik",
|
||||
"config": {
|
||||
"cert_dir": "/etc/traefik/certs"
|
||||
}
|
||||
}'
|
||||
|
||||
# 5. Create a deployment job (agent picks this up and deploys)
|
||||
curl -X POST http://localhost:8443/api/v1/certificates/{cert-id}/deploy \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"target_ids": ["target-traefik-01"]
|
||||
}'
|
||||
```
|
||||
|
||||
Once deployed, Traefik automatically loads the new certificate from the certs directory.
|
||||
|
||||
## How It Works
|
||||
|
||||
### Certificate Lifecycle
|
||||
|
||||
1. **Issue** — certctl-server generates certificate from Local CA (self-signed or sub-CA)
|
||||
2. **Store** — certificate stored in PostgreSQL with full audit trail
|
||||
3. **Deploy** — certctl-agent writes `{cert-id}.crt` + `{cert-id}.key` to `/etc/traefik/certs`
|
||||
4. **Reload** — Traefik file provider detects new files and hot-loads them (zero downtime)
|
||||
5. **Monitor** — certctl tracks deployment status and renewal timelines
|
||||
|
||||
### Self-Signed CA
|
||||
|
||||
- Generated automatically on first startup if `CERTCTL_CA_CERT_PATH` and `CERTCTL_CA_KEY_PATH` are not set
|
||||
- Certificate stored in server's in-memory state (not persisted)
|
||||
- All issued certs chain to this self-signed root
|
||||
- Use this for: demos, development, internal labs
|
||||
|
||||
### Sub-CA Mode
|
||||
|
||||
- Requires you to provide an existing CA certificate and key
|
||||
- Issued certificates chain to your enterprise root CA
|
||||
- All issued certs are trustworthy to systems with your root CA in their trust store
|
||||
- Use this for: production internal services, compliance requirements, enterprise PKI
|
||||
|
||||
## File Organization
|
||||
|
||||
```
|
||||
private-ca-traefik/
|
||||
├── docker-compose.yml # Stack definition
|
||||
├── traefik-config/ # Traefik dynamic config (you create)
|
||||
│ └── default.yaml # Routing rules and TLS settings
|
||||
├── ca-certs/ # CA certificate and key (for sub-CA mode)
|
||||
│ ├── ca-cert.pem # Your enterprise CA certificate
|
||||
│ └── ca-key.pem # Your enterprise CA private key
|
||||
└── README.md # This file
|
||||
```
|
||||
|
||||
## Monitoring
|
||||
|
||||
### certctl Dashboard
|
||||
The server provides a REST API on port 8443. Example queries:
|
||||
|
||||
```bash
|
||||
# List all certificates
|
||||
curl http://localhost:8443/api/v1/certificates
|
||||
|
||||
# Check certificate status
|
||||
curl http://localhost:8443/api/v1/certificates/{cert-id}
|
||||
|
||||
# View audit trail
|
||||
curl http://localhost:8443/api/v1/audit
|
||||
|
||||
# Check renewal policy compliance
|
||||
curl http://localhost:8443/api/v1/policies/{policy-id}
|
||||
```
|
||||
|
||||
### Traefik Dashboard
|
||||
http://localhost:8080 shows:
|
||||
- HTTP routers and services
|
||||
- TLS certificates currently loaded
|
||||
- Request/response metrics
|
||||
|
||||
### Logs
|
||||
```bash
|
||||
# certctl server logs
|
||||
docker compose logs certctl-server
|
||||
|
||||
# certctl agent logs
|
||||
docker compose logs certctl-agent
|
||||
|
||||
# Traefik logs
|
||||
docker compose logs traefik
|
||||
```
|
||||
|
||||
## Customizing Traefik Config
|
||||
|
||||
Edit `traefik-config/default.yaml` to add routers for your services:
|
||||
|
||||
```yaml
|
||||
http:
|
||||
routers:
|
||||
# Internal API
|
||||
api:
|
||||
rule: "Host(`api.internal.local`)"
|
||||
service: api-service
|
||||
tls: {}
|
||||
|
||||
# Web application
|
||||
webapp:
|
||||
rule: "Host(`app.internal.local`)"
|
||||
service: webapp-service
|
||||
tls: {}
|
||||
|
||||
services:
|
||||
api-service:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: "http://api-backend:3000"
|
||||
|
||||
webapp-service:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: "http://webapp-backend:3001"
|
||||
```
|
||||
|
||||
Changes are picked up automatically (file watcher enabled).
|
||||
|
||||
## Production Considerations
|
||||
|
||||
1. **Use sub-CA mode** — chain to your enterprise root for full trust
|
||||
2. **Enable API key authentication** — set `CERTCTL_AUTH_TYPE: api-key` and `CERTCTL_API_KEY`
|
||||
3. **Use agent-side key generation** — set `CERTCTL_KEYGEN_MODE: agent` (keys never leave agents)
|
||||
4. **Back up PostgreSQL** — certificate data is authoritative; database loss means certificate loss
|
||||
5. **Monitor renewal windows** — set up alerts on policy thresholds
|
||||
6. **Rotate CA keys regularly** — plan for future CA refresh (sub-CA mode)
|
||||
7. **Audit certificate usage** — review `certctl_audit_events` for compliance
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Certificates not deploying
|
||||
```bash
|
||||
# Check agent is healthy
|
||||
docker compose logs certctl-agent | grep heartbeat
|
||||
|
||||
# Check deployment job status
|
||||
curl http://localhost:8443/api/v1/jobs | jq '.[] | select(.type == "Deployment")'
|
||||
|
||||
# Check Traefik is watching the directory
|
||||
docker compose exec traefik ls -la /etc/traefik/certs/
|
||||
```
|
||||
|
||||
### Traefik not reloading certs
|
||||
```bash
|
||||
# Verify file provider is enabled (check docker-compose.yml command)
|
||||
# Verify certs volume is mounted at /etc/traefik/certs
|
||||
# Check Traefik logs
|
||||
docker compose logs traefik | grep "file"
|
||||
```
|
||||
|
||||
### CA cert not loading in sub-CA mode
|
||||
```bash
|
||||
# Verify file permissions
|
||||
docker compose exec certctl-server ls -la /etc/certctl/
|
||||
|
||||
# Check server logs for CA loading errors
|
||||
docker compose logs certctl-server | grep -i "ca\|cert"
|
||||
|
||||
# Verify CA certificate format
|
||||
openssl x509 -in ca-certs/ca-cert.pem -text -noout | grep -A 3 "Basic Constraints"
|
||||
```
|
||||
|
||||
## Cleanup
|
||||
|
||||
```bash
|
||||
# Stop all services
|
||||
docker compose down
|
||||
|
||||
# Remove all data (certificates, database, etc.)
|
||||
docker compose down -v
|
||||
|
||||
# Remove CA cert files (if using custom CA)
|
||||
rm -rf ca-certs/
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Add more services** — create additional routers and backends in `traefik-config/default.yaml`
|
||||
2. **Set up renewal automation** — configure renewal policies with thresholds
|
||||
3. **Integrate with monitoring** — expose certctl metrics to Prometheus
|
||||
4. **Enable notifications** — configure email/Slack alerts on certificate events
|
||||
5. **Scale to multiple environments** — deploy separate certctl stacks per environment (dev/staging/prod)
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [certctl Architecture](../../docs/architecture.md)
|
||||
- [Traefik File Provider](https://doc.traefik.io/traefik/providers/file/)
|
||||
- [Local CA Sub-CA Mode](../../docs/connectors.md#local-ca)
|
||||
- [Certificate Profiles](../../docs/quickstart.md#profiles)
|
||||
@@ -0,0 +1,204 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
# PostgreSQL database for certctl
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: certctl-postgres-stepca-haproxy
|
||||
environment:
|
||||
POSTGRES_DB: certctl
|
||||
POSTGRES_USER: certctl
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-certctl-dev-password}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U certctl -d certctl']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# Smallstep step-ca (internal private CA)
|
||||
# Initialized with default admin token and provisioner configuration
|
||||
step-ca:
|
||||
image: smallstep/step-ca:latest
|
||||
container_name: step-ca-stepca-haproxy
|
||||
environment:
|
||||
# step-ca root password (for key encryption)
|
||||
STEPPATH: /home/step/step-ca
|
||||
# Provisioner password will be set up below
|
||||
volumes:
|
||||
# Persist step-ca configuration and keys
|
||||
- step_ca_data:/home/step/step-ca
|
||||
- ./step-ca-init.sh:/opt/step-ca-init.sh:ro
|
||||
entrypoint: /bin/sh
|
||||
command:
|
||||
- -c
|
||||
- |
|
||||
# Initialize step-ca if not already done
|
||||
if [ ! -f /home/step/step-ca/config/ca.json ]; then
|
||||
echo "Initializing step-ca..."
|
||||
step ca init \
|
||||
--name="certctl-demo-ca" \
|
||||
--dns=step-ca \
|
||||
--address=0.0.0.0:9000 \
|
||||
--provisioner=admin \
|
||||
--provisioner-password-file=<(echo "${STEP_CA_PASSWORD:-stepca-demo-password}") \
|
||||
--password-file=<(echo "${STEP_CA_PASSWORD:-stepca-demo-password}") \
|
||||
--deployment-type=standalone \
|
||||
--acme 2>&1 || true
|
||||
fi
|
||||
|
||||
# Add a JWK provisioner for certctl if not present
|
||||
if ! step ca provisioner list 2>/dev/null | grep -q "certctl"; then
|
||||
echo "Adding certctl JWK provisioner..."
|
||||
step ca provisioner add certctl \
|
||||
--type=JWK \
|
||||
--password-file=<(echo "${STEP_CA_PROVISIONER_PASSWORD:-certctl-provisioner-demo}") \
|
||||
2>&1 || true
|
||||
fi
|
||||
|
||||
# Start step-ca
|
||||
echo "Starting step-ca..."
|
||||
step-ca /home/step/step-ca/config/ca.json \
|
||||
--password-file=<(echo "${STEP_CA_PASSWORD:-stepca-demo-password}")
|
||||
ports:
|
||||
- '9000:9000'
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'step ca health --insecure || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl server (control plane)
|
||||
certctl-server:
|
||||
image: ghcr.io/shankar0123/certctl-server:latest
|
||||
container_name: certctl-server-stepca-haproxy
|
||||
environment:
|
||||
# Database
|
||||
CERTCTL_DATABASE_URL: postgres://certctl:${DB_PASSWORD:-certctl-dev-password}@postgres:5432/certctl?sslmode=disable
|
||||
|
||||
# Server settings
|
||||
CERTCTL_SERVER_PORT: 8443
|
||||
CERTCTL_SERVER_HOST: 0.0.0.0
|
||||
|
||||
# Auth (disabled for demo; production should use API keys)
|
||||
CERTCTL_AUTH_TYPE: none
|
||||
|
||||
# CORS (allow agent communication)
|
||||
CERTCTL_CORS_ORIGINS: '*'
|
||||
|
||||
# Key generation mode (agent-side in production, server-side for demo)
|
||||
CERTCTL_KEYGEN_MODE: agent
|
||||
|
||||
# step-ca issuer configuration
|
||||
# step-ca runs on step-ca:9000 in this compose network
|
||||
CERTCTL_STEPCA_URL: https://step-ca:9000
|
||||
CERTCTL_STEPCA_ROOT_CERT_PATH: /etc/certctl/step-ca-root.crt
|
||||
CERTCTL_STEPCA_PROVISIONER: certctl
|
||||
CERTCTL_STEPCA_KEY_PATH: /etc/certctl/step-ca-provisioner.json
|
||||
CERTCTL_STEPCA_PASSWORD: ${STEP_CA_PROVISIONER_PASSWORD:-certctl-provisioner-demo}
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
volumes:
|
||||
# Mount step-ca certs for TLS verification (auto-generated by step-ca init)
|
||||
- step_ca_data:/home/step/step-ca/config:ro
|
||||
ports:
|
||||
- '${SERVER_PORT:-8443}:8443'
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
step-ca:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- certctl-network
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'curl -sf http://localhost:8443/health || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
restart: unless-stopped
|
||||
|
||||
# certctl agent (runs on the target machine with HAProxy)
|
||||
certctl-agent:
|
||||
image: ghcr.io/shankar0123/certctl-agent:latest
|
||||
container_name: certctl-agent-stepca-haproxy
|
||||
environment:
|
||||
# Control plane connection
|
||||
CERTCTL_SERVER_URL: http://certctl-server:8443
|
||||
CERTCTL_API_KEY: ${AGENT_API_KEY:-agent-demo-key}
|
||||
|
||||
# Key generation (agent-side keys, never sent to server)
|
||||
CERTCTL_KEYGEN_MODE: agent
|
||||
CERTCTL_KEY_DIR: /var/lib/certctl/keys
|
||||
|
||||
# Discovery (scan existing certs so operator knows what's already deployed)
|
||||
CERTCTL_DISCOVERY_DIRS: /etc/haproxy/ssl
|
||||
|
||||
# Heartbeat interval
|
||||
CERTCTL_HEARTBEAT_INTERVAL: 30s
|
||||
|
||||
# Agent metadata (self-reported)
|
||||
CERTCTL_AGENT_NAME: haproxy-agent-01
|
||||
|
||||
# Logging
|
||||
CERTCTL_LOG_LEVEL: info
|
||||
volumes:
|
||||
# Mount HAProxy config and cert directories
|
||||
# In production, these would be the actual HAProxy paths
|
||||
- haproxy_certs:/etc/haproxy/ssl
|
||||
- haproxy_conf:/etc/haproxy
|
||||
# Agent key storage (persisted across restarts)
|
||||
- agent_keys:/var/lib/certctl/keys
|
||||
depends_on:
|
||||
certctl-server:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- certctl-network
|
||||
restart: unless-stopped
|
||||
|
||||
# HAProxy reverse proxy / load balancer
|
||||
# This is where certificates will be deployed
|
||||
haproxy:
|
||||
image: haproxy:2.9-alpine
|
||||
container_name: certctl-haproxy-stepca-haproxy
|
||||
ports:
|
||||
- '80:80'
|
||||
- '443:443'
|
||||
volumes:
|
||||
- haproxy_conf:/etc/haproxy
|
||||
- haproxy_certs:/etc/haproxy/ssl
|
||||
# Default HAProxy config
|
||||
- ./haproxy.cfg:/etc/haproxy/haproxy.cfg:ro
|
||||
depends_on:
|
||||
- certctl-agent
|
||||
networks:
|
||||
- certctl-network
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'wget --quiet --tries=1 --spider http://localhost:8080/stats || exit 1']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
certctl-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
driver: local
|
||||
step_ca_data:
|
||||
driver: local
|
||||
haproxy_certs:
|
||||
driver: local
|
||||
haproxy_conf:
|
||||
driver: local
|
||||
agent_keys:
|
||||
driver: local
|
||||
@@ -0,0 +1,69 @@
|
||||
global
|
||||
log stdout local0
|
||||
log stdout local1 notice
|
||||
chroot /var/lib/haproxy
|
||||
stats socket /run/haproxy/admin.sock mode 660 level admin
|
||||
stats timeout 30s
|
||||
user haproxy
|
||||
group haproxy
|
||||
daemon
|
||||
|
||||
# Default SSL options for modern TLS
|
||||
tune.ssl.default-dh-param 2048
|
||||
ssl-default-bind-ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option dontlognull
|
||||
timeout connect 5000
|
||||
timeout client 50000
|
||||
timeout server 50000
|
||||
errorfile 400 /etc/haproxy/errors/400.http
|
||||
errorfile 403 /etc/haproxy/errors/403.http
|
||||
errorfile 408 /etc/haproxy/errors/408.http
|
||||
errorfile 500 /etc/haproxy/errors/500.http
|
||||
errorfile 502 /etc/haproxy/errors/502.http
|
||||
errorfile 503 /etc/haproxy/errors/503.http
|
||||
errorfile 504 /etc/haproxy/errors/504.http
|
||||
|
||||
# Statistics endpoint (accessible on port 8080)
|
||||
listen stats
|
||||
bind *:8080
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 30s
|
||||
stats admin if TRUE
|
||||
|
||||
# Example HTTPS frontend with certificate from certctl
|
||||
# This frontend will serve HTTPS on port 443 using a combined PEM file
|
||||
# deployed by certctl to /etc/haproxy/ssl/cert.pem
|
||||
frontend https_in
|
||||
# HTTP redirect to HTTPS
|
||||
bind *:80
|
||||
mode http
|
||||
acl is_http hdr(X-Forwarded-Proto) http
|
||||
redirect scheme https code 301 if !is_https
|
||||
|
||||
# HTTPS with certificate
|
||||
# In production, certctl will manage cert.pem and reload HAProxy after deployment
|
||||
bind *:443 ssl crt /etc/haproxy/ssl/cert.pem strict-sni
|
||||
mode http
|
||||
option httplog
|
||||
|
||||
# Default backend
|
||||
default_backend http_backend
|
||||
|
||||
# Example backend (simple web service placeholder)
|
||||
backend http_backend
|
||||
mode http
|
||||
option httpchk GET /
|
||||
server local_app 127.0.0.1:8000 check disabled
|
||||
|
||||
# Health endpoint (useful for certctl agent deployment verification)
|
||||
frontend health
|
||||
bind *:9999
|
||||
mode http
|
||||
monitor-uri /health
|
||||
@@ -0,0 +1,355 @@
|
||||
# step-ca + HAProxy Example
|
||||
|
||||
This example demonstrates certctl managing certificates issued by **Smallstep step-ca** and deploying them to **HAProxy**.
|
||||
|
||||
## Scenario
|
||||
|
||||
You're a Smallstep user running step-ca as your internal PKI. You have HAProxy load balancers that need certificates. This setup:
|
||||
|
||||
1. **step-ca** issues certificates (via JWK provisioner, no challenge solving)
|
||||
2. **certctl** manages the certificate lifecycle (renewal policies, deployment, audit)
|
||||
3. **HAProxy** serves HTTPS with certificates managed by certctl
|
||||
|
||||
This is the natural choice if you're already invested in step-ca and want to consolidate certificate lifecycle management without learning Let's Encrypt, DNS-01 challenges, or external integrations.
|
||||
|
||||
## What's Included
|
||||
|
||||
| Service | Image | Purpose |
|
||||
|---------|-------|---------|
|
||||
| **step-ca** | `smallstep/step-ca:latest` | Private internal CA |
|
||||
| **certctl-server** | `ghcr.io/shankar0123/certctl-server:latest` | Certificate management control plane |
|
||||
| **certctl-agent** | `ghcr.io/shankar0123/certctl-agent:latest` | Agent running on HAProxy server |
|
||||
| **haproxy** | `haproxy:2.9-alpine` | Reverse proxy / load balancer |
|
||||
| **postgres** | `postgres:16-alpine` | certctl audit trail + config storage |
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Docker and Docker Compose
|
||||
- Curl (to interact with APIs)
|
||||
|
||||
### 1. Start Everything
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
This will:
|
||||
- Initialize step-ca with a self-signed root CA
|
||||
- Create a JWK provisioner named `certctl` (pre-configured credentials)
|
||||
- Start certctl-server (connected to step-ca)
|
||||
- Start the certctl-agent (ready to deploy certs to HAProxy)
|
||||
- Start HAProxy with a placeholder config
|
||||
|
||||
Monitor logs:
|
||||
|
||||
```bash
|
||||
docker compose logs -f certctl-server
|
||||
```
|
||||
|
||||
Wait for all services to reach healthy state:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
NAME STATUS
|
||||
certctl-postgres-... healthy
|
||||
certctl-server-... healthy
|
||||
step-ca-... healthy
|
||||
certctl-agent-... running
|
||||
certctl-haproxy-... healthy
|
||||
```
|
||||
|
||||
### 2. Access certctl Dashboard
|
||||
|
||||
Open your browser to:
|
||||
|
||||
```
|
||||
http://localhost:8443
|
||||
```
|
||||
|
||||
You should see an empty dashboard. This is expected — no certificates issued yet.
|
||||
|
||||
### 3. Create a Certificate Profile
|
||||
|
||||
This defines what certificates certctl can issue (key algorithm, max TTL, allowed names).
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8443/api/v1/profiles \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"name": "internal-web",
|
||||
"key_type": "rsa-2048",
|
||||
"max_ttl_days": 90,
|
||||
"description": "Internal web services"
|
||||
}'
|
||||
```
|
||||
|
||||
### 4. Create an HAProxy Deployment Target
|
||||
|
||||
This tells certctl where to deploy certificates on the HAProxy server.
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8443/api/v1/targets \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"name": "haproxy-01",
|
||||
"type": "haproxy",
|
||||
"enabled": true,
|
||||
"config": {
|
||||
"pem_path": "/etc/haproxy/ssl/cert.pem",
|
||||
"reload_command": "systemctl reload haproxy",
|
||||
"validate_command": "haproxy -c -f /etc/haproxy/haproxy.cfg"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
Note: In the Docker Compose environment, reload command can be `kill -HUP $(pidof haproxy)` instead of `systemctl reload haproxy`.
|
||||
|
||||
### 5. Create a Renewal Policy
|
||||
|
||||
This ties a certificate profile to a deployment target and sets renewal thresholds.
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8443/api/v1/renewal-policies \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"name": "haproxy-internal-web",
|
||||
"profile_id": "<profile_id_from_step_3>",
|
||||
"issuer_id": "iss-stepca",
|
||||
"enabled": true,
|
||||
"renewal_days_before_expiry": 30,
|
||||
"alert_thresholds_days": [30, 14, 7, 0]
|
||||
}'
|
||||
```
|
||||
|
||||
Get the issuer ID:
|
||||
|
||||
```bash
|
||||
curl http://localhost:8443/api/v1/issuers | jq '.'
|
||||
```
|
||||
|
||||
You should see `iss-stepca` in the list.
|
||||
|
||||
### 6. Issue a Certificate
|
||||
|
||||
Request a certificate via the API. The server will sign it via step-ca.
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8443/api/v1/certificates \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"common_name": "api.internal.example.com",
|
||||
"sans": ["api.internal.example.com", "api.staging.example.com"],
|
||||
"issuer_id": "iss-stepca",
|
||||
"profile_id": "<profile_id_from_step_3>"
|
||||
}'
|
||||
```
|
||||
|
||||
### 7. Deploy to HAProxy
|
||||
|
||||
Get the certificate ID and trigger deployment:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8443/api/v1/certificates/<cert_id>/deploy \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"target_id": "<target_id_from_step_4>"
|
||||
}'
|
||||
```
|
||||
|
||||
The agent will:
|
||||
1. Fetch the deployment job
|
||||
2. Generate a combined PEM (cert + chain + key) locally
|
||||
3. Write it to `/etc/haproxy/ssl/cert.pem` on HAProxy
|
||||
4. Reload HAProxy
|
||||
5. Report status back to certctl
|
||||
|
||||
### 8. Verify in Dashboard
|
||||
|
||||
Refresh http://localhost:8443 and you should see:
|
||||
- 1 certificate (status: Active, expiry in 90 days)
|
||||
- 1 deployment job (status: Completed)
|
||||
- 1 agent (heartbeat: recent)
|
||||
|
||||
## Configuration Details
|
||||
|
||||
### step-ca Integration
|
||||
|
||||
step-ca is configured with:
|
||||
|
||||
- **Root CA Name**: `certctl-demo-ca`
|
||||
- **Provisioner**: `certctl` (JWK type)
|
||||
- **Default Password**: `certctl-provisioner-demo` (override with `STEP_CA_PROVISIONER_PASSWORD`)
|
||||
|
||||
To inspect step-ca:
|
||||
|
||||
```bash
|
||||
docker compose exec step-ca step ca provisioner list
|
||||
docker compose exec step-ca step ca health --insecure
|
||||
```
|
||||
|
||||
### HAProxy Combined PEM Format
|
||||
|
||||
HAProxy requires a single file with certificate, chain, and key concatenated:
|
||||
|
||||
```
|
||||
-----BEGIN CERTIFICATE-----
|
||||
[leaf certificate]
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN CERTIFICATE-----
|
||||
[intermediate CA]
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
[private key]
|
||||
-----END RSA PRIVATE KEY-----
|
||||
```
|
||||
|
||||
The agent automatically constructs this file from the issued certificate and step-ca-provided chain.
|
||||
|
||||
**Security**: The combined PEM is written with `0600` permissions (owner-readable only) because it contains the private key.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Customize behavior with:
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
|----------|---------|---------|
|
||||
| `DB_PASSWORD` | `certctl-dev-password` | PostgreSQL password |
|
||||
| `STEP_CA_PASSWORD` | `stepca-demo-password` | step-ca root key password |
|
||||
| `STEP_CA_PROVISIONER_PASSWORD` | `certctl-provisioner-demo` | certctl JWK provisioner password |
|
||||
| `AGENT_API_KEY` | `agent-demo-key` | Agent authentication token |
|
||||
| `SERVER_PORT` | `8443` | certctl server external port |
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
STEP_CA_PASSWORD=myca-password AGENT_API_KEY=secret-key docker compose up -d
|
||||
```
|
||||
|
||||
## Integrating with an Existing step-ca Instance
|
||||
|
||||
If you already run step-ca elsewhere (not in this Compose file):
|
||||
|
||||
1. **Extract the root certificate** from your step-ca:
|
||||
|
||||
```bash
|
||||
step ca root /tmp/step-ca-root.crt --ca-url https://ca.internal:9000 --insecure
|
||||
```
|
||||
|
||||
2. **Create or retrieve the certctl JWK provisioner key**:
|
||||
|
||||
```bash
|
||||
step ca provisioner list --ca-url https://ca.internal:9000 --insecure
|
||||
step ca provisioner describe certctl --ca-url https://ca.internal:9000 --insecure
|
||||
```
|
||||
|
||||
3. **Update docker-compose.yml**:
|
||||
|
||||
```yaml
|
||||
certctl-server:
|
||||
environment:
|
||||
CERTCTL_STEPCA_URL: https://ca.internal:9000
|
||||
CERTCTL_STEPCA_ROOT_CERT_PATH: /etc/certctl/step-ca-root.crt
|
||||
CERTCTL_STEPCA_PROVISIONER_NAME: certctl
|
||||
CERTCTL_STEPCA_PROVISIONER_KEY_PATH: /etc/certctl/step-ca-provisioner.json
|
||||
CERTCTL_STEPCA_PROVISIONER_PASSWORD: <your-password>
|
||||
```
|
||||
|
||||
4. **Mount the cert and key**:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- /path/to/step-ca-root.crt:/etc/certctl/step-ca-root.crt:ro
|
||||
- /path/to/provisioner.json:/etc/certctl/step-ca-provisioner.json:ro
|
||||
```
|
||||
|
||||
## Cleanup
|
||||
|
||||
```bash
|
||||
docker compose down -v
|
||||
```
|
||||
|
||||
This removes all containers and volumes (step-ca config, certificates, database).
|
||||
|
||||
## Next Steps
|
||||
|
||||
### Production Deployment
|
||||
|
||||
- Replace image tags (`latest` → specific version)
|
||||
- Use real TLS certificates for step-ca (self-signed is fine internally, but use proper roots for verification)
|
||||
- Configure persistent storage for step-ca keys (HSM or encrypted filesystem)
|
||||
- Set `CERTCTL_AUTH_TYPE: api-key` and rotate API keys regularly
|
||||
- Enable audit trail export for compliance
|
||||
- Configure renewal alerts (Slack, email, PagerDuty)
|
||||
- Run agents on separate machines (not in Compose)
|
||||
|
||||
### Advanced Features
|
||||
|
||||
- **Multiple HAProxy instances**: Create additional targets and agents
|
||||
- **Policy-based renewal**: Set different renewal windows per environment (staging vs. production)
|
||||
- **Approval workflows**: Require manual approval before deploying to production
|
||||
- **Discovery**: Scan existing HAProxy certs and bring them under management
|
||||
- **Network scanning**: Discover TLS endpoints in your network and inventory them
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### step-ca fails to initialize
|
||||
|
||||
Check logs:
|
||||
|
||||
```bash
|
||||
docker compose logs step-ca
|
||||
```
|
||||
|
||||
Common issues:
|
||||
- Permissions on `/home/step/step-ca` volume
|
||||
- Port 9000 already in use
|
||||
|
||||
### Agent can't reach server
|
||||
|
||||
Verify network:
|
||||
|
||||
```bash
|
||||
docker compose exec certctl-agent curl http://certctl-server:8443/health
|
||||
```
|
||||
|
||||
### HAProxy config validation fails
|
||||
|
||||
Check HAProxy config syntax:
|
||||
|
||||
```bash
|
||||
docker compose exec haproxy haproxy -c -f /etc/haproxy/haproxy.cfg
|
||||
```
|
||||
|
||||
### Deployment job stays in "Running" state
|
||||
|
||||
Check agent logs:
|
||||
|
||||
```bash
|
||||
docker compose logs certctl-agent
|
||||
```
|
||||
|
||||
Likely causes:
|
||||
- Agent can't write to `/etc/haproxy/ssl/cert.pem` (permissions)
|
||||
- Reload command is misconfigured
|
||||
- HAProxy container is not accessible
|
||||
|
||||
## Documentation
|
||||
|
||||
- [certctl Architecture](../../docs/architecture.md)
|
||||
- [step-ca Connector Docs](../../docs/connectors.md#step-ca)
|
||||
- [HAProxy Target Docs](../../docs/connectors.md#haproxy)
|
||||
- [API Reference](../../api/openapi.yaml)
|
||||
|
||||
## Support
|
||||
|
||||
For issues or questions:
|
||||
|
||||
1. Check the [troubleshooting guide](../../docs/troubleshooting.md)
|
||||
2. Review service logs: `docker compose logs <service>`
|
||||
3. Open an issue on GitHub
|
||||
@@ -9,12 +9,19 @@ require (
|
||||
github.com/testcontainers/testcontainers-go v0.35.0
|
||||
)
|
||||
|
||||
require golang.org/x/crypto v0.31.0
|
||||
require (
|
||||
golang.org/x/crypto v0.31.0
|
||||
software.sslmate.com/src/go-pkcs12 v0.7.0
|
||||
)
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.0 // indirect
|
||||
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
||||
github.com/ChrisTrenkamp/goxpath v0.0.0-20210404020558-97928f7e12b6 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/bodgit/ntlmssp v0.0.0-20240506230425-31973bb52d9b // indirect
|
||||
github.com/bodgit/windows v1.0.1 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.2.1 // indirect
|
||||
github.com/containerd/containerd v1.7.18 // indirect
|
||||
github.com/containerd/log v0.1.0 // indirect
|
||||
@@ -29,12 +36,23 @@ require (
|
||||
github.com/go-logr/logr v1.4.1 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/gofrs/uuid v4.4.0+incompatible // indirect
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/google/jsonschema-go v0.4.2 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 // indirect
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
github.com/jcmturner/goidentity/v6 v6.0.1 // indirect
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
|
||||
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
|
||||
github.com/klauspost/compress v1.17.4 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/masterzen/simplexml v0.0.0-20190410153822-31eea3082786 // indirect
|
||||
github.com/masterzen/winrm v0.0.0-20250927112105-5f8e6c707321 // indirect
|
||||
github.com/moby/docker-image-spec v1.3.1 // indirect
|
||||
github.com/moby/patternmatcher v0.6.0 // indirect
|
||||
github.com/moby/sys/sequential v0.5.0 // indirect
|
||||
@@ -52,6 +70,7 @@ require (
|
||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/stretchr/testify v1.9.0 // indirect
|
||||
github.com/tidwall/transform v0.0.0-20201103190739-32f242e2dbde // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
@@ -60,7 +79,9 @@ require (
|
||||
go.opentelemetry.io/otel v1.24.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.24.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.24.0 // indirect
|
||||
golang.org/x/net v0.23.0 // indirect
|
||||
golang.org/x/oauth2 v0.34.0 // indirect
|
||||
golang.org/x/sys v0.40.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
@@ -4,8 +4,16 @@ github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 h1:bvDV9
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
||||
github.com/ChrisTrenkamp/goxpath v0.0.0-20210404020558-97928f7e12b6 h1:w0E0fgc1YafGEh5cROhlROMWXiNoZqApk2PDN0M1+Ns=
|
||||
github.com/ChrisTrenkamp/goxpath v0.0.0-20210404020558-97928f7e12b6/go.mod h1:nuWgzSkT5PnyOd+272uUmV0dnAnAn42Mk7PiQC5VzN4=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/bodgit/ntlmssp v0.0.0-20240506230425-31973bb52d9b h1:baFN6AnR0SeC194X2D292IUZcHDs4JjStpqtE70fjXE=
|
||||
github.com/bodgit/ntlmssp v0.0.0-20240506230425-31973bb52d9b/go.mod h1:Ram6ngyPDmP+0t6+4T2rymv0w0BS9N8Ch5vvUJccw5o=
|
||||
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
|
||||
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
|
||||
github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM=
|
||||
github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||
github.com/containerd/containerd v1.7.18 h1:jqjZTQNfXGoEaZdW1WwPU0RqSn1Bm2Ay/KJPUuO8nao=
|
||||
@@ -39,6 +47,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA=
|
||||
github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||
@@ -52,8 +62,27 @@ github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbc
|
||||
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0 h1:YBftPWNWd4WwGqtY2yeZL2ef8rHAxPBD8KFhJpmcqms=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0/go.mod h1:YN5jB8ie0yfIUg6VvR9Kz84aCaG7AsGZnLjhHbUqwPg=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
|
||||
github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
|
||||
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
|
||||
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo=
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM=
|
||||
github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg=
|
||||
github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo=
|
||||
github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o=
|
||||
github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg=
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8=
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
|
||||
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
|
||||
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=
|
||||
@@ -68,6 +97,10 @@ github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/masterzen/simplexml v0.0.0-20190410153822-31eea3082786 h1:2ZKn+w/BJeL43sCxI2jhPLRv73oVVOjEKZjKkflyqxg=
|
||||
github.com/masterzen/simplexml v0.0.0-20190410153822-31eea3082786/go.mod h1:kCEbxUJlNDEBNbdQMkPSp6yaKcRXVI6f4ddk8Riv4bc=
|
||||
github.com/masterzen/winrm v0.0.0-20250927112105-5f8e6c707321 h1:AKIJL2PfBX2uie0Mn5pxtG1+zut3hAVMZbRfoXecFzI=
|
||||
github.com/masterzen/winrm v0.0.0-20250927112105-5f8e6c707321/go.mod h1:JajVhkiG2bYSNYYPYuWG7WZHr42CTjMTcCjfInRNCqc=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/patternmatcher v0.6.0 h1:GmP9lR19aU5GqSSFko+5pRqHi+Ohk1O69aFiKkVGiPk=
|
||||
@@ -111,14 +144,18 @@ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSS
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/testcontainers/testcontainers-go v0.35.0 h1:uADsZpTKFAtp8SLK+hMwSaa+X+JiERHtd4sQAFmXeMo=
|
||||
github.com/testcontainers/testcontainers-go v0.35.0/go.mod h1:oEVBj5zrfJTrgjwONs1SsRbnBtH9OKl+IGl3UMcr2B4=
|
||||
github.com/tidwall/transform v0.0.0-20201103190739-32f242e2dbde h1:AMNpJRc7P+GTwVbl8DkK2I9I8BBUzNiHuH/tlxrpan0=
|
||||
github.com/tidwall/transform v0.0.0-20201103190739-32f242e2dbde/go.mod h1:MvrEmduDUz4ST5pGZ7CABCnOU5f3ZiOAZzT6b1A6nX8=
|
||||
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
|
||||
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
|
||||
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
|
||||
@@ -127,6 +164,7 @@ github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zI
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw=
|
||||
github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
|
||||
@@ -148,14 +186,22 @@ go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v8
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
|
||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
|
||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
|
||||
@@ -163,22 +209,33 @@ golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwE
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 h1:vVKdlvoWBphwdxWKrFZEuM0kGgGLxUOYcY4U/2Vjg44=
|
||||
@@ -187,6 +244,7 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
|
||||
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
@@ -205,8 +263,11 @@ google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHh
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=
|
||||
gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=
|
||||
software.sslmate.com/src/go-pkcs12 v0.7.0 h1:Db8W44cB54TWD7stUFFSWxdfpdn6fZVcDl0w3R4RVM0=
|
||||
software.sslmate.com/src/go-pkcs12 v0.7.0/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI=
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
#!/bin/bash
|
||||
# certctl Agent Install Script
|
||||
# Detects OS (Linux/macOS) and architecture, downloads binary from GitHub Releases,
|
||||
# installs to system path, configures service (systemd/launchd), and prompts for config.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Colors for output
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Configuration
|
||||
GITHUB_REPO="shankar0123/certctl"
|
||||
RELEASE_URL="https://github.com/${GITHUB_REPO}/releases/latest/download"
|
||||
INSTALL_DIR="/usr/local/bin"
|
||||
SERVICE_NAME="certctl-agent"
|
||||
|
||||
# Detect OS and architecture
|
||||
detect_platform() {
|
||||
local os="$(uname -s)"
|
||||
local arch="$(uname -m)"
|
||||
|
||||
case "$os" in
|
||||
Linux*)
|
||||
OS_TYPE="linux"
|
||||
;;
|
||||
Darwin*)
|
||||
OS_TYPE="darwin"
|
||||
;;
|
||||
*)
|
||||
echo -e "${RED}Error: Unsupported OS: $os${NC}"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
case "$arch" in
|
||||
x86_64)
|
||||
ARCH_TYPE="amd64"
|
||||
;;
|
||||
aarch64|arm64)
|
||||
ARCH_TYPE="arm64"
|
||||
;;
|
||||
*)
|
||||
echo -e "${RED}Error: Unsupported architecture: $arch${NC}"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Print usage information
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $0 [OPTIONS]
|
||||
|
||||
Install and configure the certctl agent on your system.
|
||||
|
||||
OPTIONS:
|
||||
-h, --help Show this help message
|
||||
--server-url URL Set CERTCTL_SERVER_URL (skips interactive prompt)
|
||||
--api-key KEY Set CERTCTL_API_KEY (skips interactive prompt)
|
||||
--no-start Install but don't start the service
|
||||
|
||||
EOF
|
||||
}
|
||||
|
||||
# Parse command-line arguments
|
||||
parse_args() {
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
--server-url)
|
||||
SERVER_URL="$2"
|
||||
shift 2
|
||||
;;
|
||||
--api-key)
|
||||
API_KEY="$2"
|
||||
shift 2
|
||||
;;
|
||||
--no-start)
|
||||
NO_START=true
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
echo -e "${RED}Error: Unknown option: $1${NC}"
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
# Check if running as root/sudo on Linux
|
||||
check_privileges() {
|
||||
if [[ "$OS_TYPE" == "linux" && "$EUID" -ne 0 ]]; then
|
||||
echo -e "${RED}Error: This script must be run as root on Linux. Try: sudo $0${NC}"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Download agent binary from GitHub Releases
|
||||
download_binary() {
|
||||
local binary_name="certctl-agent-${OS_TYPE}-${ARCH_TYPE}"
|
||||
local download_url="${RELEASE_URL}/${binary_name}"
|
||||
|
||||
echo -e "${YELLOW}Downloading certctl agent (${OS_TYPE}-${ARCH_TYPE})...${NC}"
|
||||
|
||||
if ! command -v curl &> /dev/null; then
|
||||
echo -e "${RED}Error: curl is required but not installed${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local temp_file=$(mktemp)
|
||||
trap "rm -f $temp_file" EXIT
|
||||
|
||||
if ! curl -sSL -f "$download_url" -o "$temp_file"; then
|
||||
echo -e "${RED}Error: Failed to download binary from $download_url${NC}"
|
||||
echo "Make sure the latest release exists on GitHub with the binary asset for ${OS_TYPE}-${ARCH_TYPE}."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
chmod +x "$temp_file"
|
||||
echo "$temp_file"
|
||||
}
|
||||
|
||||
# Install binary to system path
|
||||
install_binary() {
|
||||
local binary_path="$1"
|
||||
|
||||
echo -e "${YELLOW}Installing to $INSTALL_DIR/$SERVICE_NAME...${NC}"
|
||||
|
||||
if [[ "$OS_TYPE" == "linux" ]]; then
|
||||
cp "$binary_path" "$INSTALL_DIR/$SERVICE_NAME"
|
||||
else
|
||||
# macOS: use sudo if not already running as root
|
||||
if [[ "$EUID" -ne 0 ]]; then
|
||||
sudo cp "$binary_path" "$INSTALL_DIR/$SERVICE_NAME"
|
||||
else
|
||||
cp "$binary_path" "$INSTALL_DIR/$SERVICE_NAME"
|
||||
fi
|
||||
fi
|
||||
|
||||
chmod +x "$INSTALL_DIR/$SERVICE_NAME"
|
||||
echo -e "${GREEN}Binary installed: $INSTALL_DIR/$SERVICE_NAME${NC}"
|
||||
}
|
||||
|
||||
# Prompt for configuration (unless --server-url and --api-key provided)
|
||||
prompt_for_config() {
|
||||
if [[ -z "${SERVER_URL:-}" ]]; then
|
||||
echo ""
|
||||
echo -e "${YELLOW}Enter certctl server URL (e.g., https://certctl.example.com):${NC}"
|
||||
read -r SERVER_URL
|
||||
if [[ -z "$SERVER_URL" ]]; then
|
||||
echo -e "${RED}Error: Server URL is required${NC}"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "${API_KEY:-}" ]]; then
|
||||
echo -e "${YELLOW}Enter certctl API key:${NC}"
|
||||
read -sr API_KEY
|
||||
echo ""
|
||||
if [[ -z "$API_KEY" ]]; then
|
||||
echo -e "${RED}Error: API key is required${NC}"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "${AGENT_ID:-}" ]]; then
|
||||
local default_agent_id="$(hostname)"
|
||||
echo -e "${YELLOW}Enter agent ID (default: $default_agent_id):${NC}"
|
||||
read -r AGENT_ID
|
||||
if [[ -z "$AGENT_ID" ]]; then
|
||||
AGENT_ID="$default_agent_id"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# Create configuration directory and env file (Linux)
|
||||
setup_linux_config() {
|
||||
local config_dir="/etc/certctl"
|
||||
local config_file="$config_dir/agent.env"
|
||||
local key_dir="/var/lib/certctl/keys"
|
||||
|
||||
echo -e "${YELLOW}Creating configuration directory...${NC}"
|
||||
|
||||
# Create /etc/certctl with restrictive permissions
|
||||
mkdir -p "$config_dir"
|
||||
chmod 755 "$config_dir"
|
||||
|
||||
# Create key storage directory with 0700 permissions
|
||||
mkdir -p "$key_dir"
|
||||
chmod 700 "$key_dir"
|
||||
|
||||
# Write agent configuration (overwrite if exists)
|
||||
cat > "$config_file" <<EOF
|
||||
# certctl Agent Configuration
|
||||
# Generated by install-agent.sh on $(date)
|
||||
|
||||
# Agent ID (unique identifier in the fleet)
|
||||
CERTCTL_AGENT_ID=$AGENT_ID
|
||||
|
||||
# Control plane server URL
|
||||
CERTCTL_SERVER_URL=$SERVER_URL
|
||||
|
||||
# API authentication key
|
||||
CERTCTL_API_KEY=$API_KEY
|
||||
|
||||
# Key generation mode (agent = agent-side keygen, server = server-side for demo only)
|
||||
CERTCTL_KEYGEN_MODE=agent
|
||||
|
||||
# Key storage directory (agent-side keygen)
|
||||
CERTCTL_KEY_DIR=$key_dir
|
||||
|
||||
# Logging level (debug, info, warn, error)
|
||||
# CERTCTL_LOG_LEVEL=info
|
||||
|
||||
# Discovery directories (comma-separated paths to scan for existing certs)
|
||||
# CERTCTL_DISCOVERY_DIRS=/etc/letsencrypt/live,/etc/ssl/certs
|
||||
|
||||
# Enable deployment verification (TLS endpoint check post-deployment)
|
||||
# CERTCTL_VERIFY_DEPLOYMENT=true
|
||||
EOF
|
||||
|
||||
# Restrict permissions on env file (contains API key)
|
||||
chmod 600 "$config_file"
|
||||
echo -e "${GREEN}Configuration written to: $config_file${NC}"
|
||||
}
|
||||
|
||||
# Create configuration directory and env file (macOS)
|
||||
setup_macos_config() {
|
||||
local config_dir="$HOME/.certctl"
|
||||
local config_file="$config_dir/agent.env"
|
||||
local key_dir="$config_dir/keys"
|
||||
|
||||
echo -e "${YELLOW}Creating configuration directory...${NC}"
|
||||
|
||||
# Create ~/.certctl with restrictive permissions
|
||||
mkdir -p "$config_dir"
|
||||
chmod 700 "$config_dir"
|
||||
|
||||
# Create key storage directory
|
||||
mkdir -p "$key_dir"
|
||||
chmod 700 "$key_dir"
|
||||
|
||||
# Write agent configuration (overwrite if exists)
|
||||
cat > "$config_file" <<EOF
|
||||
# certctl Agent Configuration
|
||||
# Generated by install-agent.sh on $(date)
|
||||
|
||||
# Agent ID (unique identifier in the fleet)
|
||||
CERTCTL_AGENT_ID=$AGENT_ID
|
||||
|
||||
# Control plane server URL
|
||||
CERTCTL_SERVER_URL=$SERVER_URL
|
||||
|
||||
# API authentication key
|
||||
CERTCTL_API_KEY=$API_KEY
|
||||
|
||||
# Key generation mode (agent = agent-side keygen, server = server-side for demo only)
|
||||
CERTCTL_KEYGEN_MODE=agent
|
||||
|
||||
# Key storage directory (agent-side keygen)
|
||||
CERTCTL_KEY_DIR=$key_dir
|
||||
|
||||
# Logging level (debug, info, warn, error)
|
||||
# CERTCTL_LOG_LEVEL=info
|
||||
|
||||
# Discovery directories (comma-separated paths to scan for existing certs)
|
||||
# CERTCTL_DISCOVERY_DIRS=/etc/letsencrypt/live,/etc/ssl/certs
|
||||
|
||||
# Enable deployment verification (TLS endpoint check post-deployment)
|
||||
# CERTCTL_VERIFY_DEPLOYMENT=true
|
||||
EOF
|
||||
|
||||
# Restrict permissions on env file (contains API key)
|
||||
chmod 600 "$config_file"
|
||||
echo -e "${GREEN}Configuration written to: $config_file${NC}"
|
||||
}
|
||||
|
||||
# Create and enable systemd service (Linux only)
|
||||
setup_systemd_service() {
|
||||
local service_file="/etc/systemd/system/${SERVICE_NAME}.service"
|
||||
|
||||
echo -e "${YELLOW}Creating systemd service file...${NC}"
|
||||
|
||||
cat > "$service_file" <<'EOF'
|
||||
[Unit]
|
||||
Description=certctl Agent - Certificate Lifecycle Management
|
||||
Documentation=https://github.com/shankar0123/certctl
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Restart=on-failure
|
||||
RestartSec=10s
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
# Load environment from /etc/certctl/agent.env
|
||||
EnvironmentFile=/etc/certctl/agent.env
|
||||
|
||||
# Command to start the agent
|
||||
ExecStart=/usr/local/bin/certctl-agent
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
chmod 644 "$service_file"
|
||||
echo -e "${GREEN}Service file created: $service_file${NC}"
|
||||
|
||||
# Reload systemd daemon
|
||||
systemctl daemon-reload
|
||||
}
|
||||
|
||||
# Create and enable launchd plist (macOS only)
|
||||
setup_launchd_service() {
|
||||
local plist_file="$HOME/Library/LaunchAgents/com.certctl.agent.plist"
|
||||
local config_file="$HOME/.certctl/agent.env"
|
||||
local launcher_script="$HOME/.certctl/launcher.sh"
|
||||
local home_dir="$HOME"
|
||||
|
||||
echo -e "${YELLOW}Creating launchd service file...${NC}"
|
||||
|
||||
mkdir -p "$(dirname "$plist_file")"
|
||||
|
||||
# Create wrapper script that sources env file before executing agent
|
||||
cat > "$launcher_script" <<'LAUNCHER_SCRIPT'
|
||||
#!/bin/bash
|
||||
set -a
|
||||
source "$HOME/.certctl/agent.env"
|
||||
set +a
|
||||
exec /usr/local/bin/certctl-agent
|
||||
LAUNCHER_SCRIPT
|
||||
|
||||
chmod 755 "$launcher_script"
|
||||
|
||||
# Create plist that references the launcher script
|
||||
cat > "$plist_file" <<EOF
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>com.certctl.agent</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>$home_dir/.certctl/launcher.sh</string>
|
||||
</array>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>PATH</key>
|
||||
<string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
|
||||
<key>HOME</key>
|
||||
<string>$home_dir</string>
|
||||
</dict>
|
||||
<key>KeepAlive</key>
|
||||
<true/>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>$home_dir/.certctl/agent.log</string>
|
||||
<key>StandardOutPath</key>
|
||||
<string>$home_dir/.certctl/agent.log</string>
|
||||
</dict>
|
||||
</plist>
|
||||
EOF
|
||||
|
||||
chmod 644 "$plist_file"
|
||||
echo -e "${GREEN}Service file created: $plist_file${NC}"
|
||||
echo -e "${GREEN}Launcher script created: $launcher_script${NC}"
|
||||
}
|
||||
|
||||
# Start the agent service
|
||||
start_service() {
|
||||
if [[ "${NO_START:-false}" == "true" ]]; then
|
||||
echo -e "${YELLOW}Service not started (--no-start flag used)${NC}"
|
||||
return
|
||||
fi
|
||||
|
||||
echo -e "${YELLOW}Starting certctl agent service...${NC}"
|
||||
|
||||
if [[ "$OS_TYPE" == "linux" ]]; then
|
||||
systemctl enable "$SERVICE_NAME"
|
||||
systemctl start "$SERVICE_NAME"
|
||||
sleep 2
|
||||
if systemctl is-active --quiet "$SERVICE_NAME"; then
|
||||
echo -e "${GREEN}Service started successfully${NC}"
|
||||
else
|
||||
echo -e "${RED}Warning: Service may not have started. Check logs with: systemctl status $SERVICE_NAME${NC}"
|
||||
fi
|
||||
else
|
||||
# macOS: load launchd service for current user
|
||||
launchctl load "$HOME/Library/LaunchAgents/com.certctl.agent.plist" 2>/dev/null || true
|
||||
sleep 1
|
||||
echo -e "${GREEN}Service loaded into launchd${NC}"
|
||||
fi
|
||||
}
|
||||
|
||||
# Print success message with next steps
|
||||
print_summary() {
|
||||
echo ""
|
||||
echo -e "${GREEN}========================================${NC}"
|
||||
echo -e "${GREEN}certctl Agent Installation Complete${NC}"
|
||||
echo -e "${GREEN}========================================${NC}"
|
||||
echo ""
|
||||
echo "Configuration:"
|
||||
if [[ "$OS_TYPE" == "linux" ]]; then
|
||||
echo " Config file: /etc/certctl/agent.env"
|
||||
echo " Key storage: /var/lib/certctl/keys"
|
||||
echo " Service: /etc/systemd/system/${SERVICE_NAME}.service"
|
||||
echo " View logs: journalctl -u ${SERVICE_NAME} -f"
|
||||
else
|
||||
echo " Config file: $HOME/.certctl/agent.env"
|
||||
echo " Key storage: $HOME/.certctl/keys"
|
||||
echo " Service: $HOME/Library/LaunchAgents/com.certctl.agent.plist"
|
||||
echo " View logs: tail -f $HOME/.certctl/agent.log"
|
||||
fi
|
||||
echo ""
|
||||
echo "Next steps:"
|
||||
echo " 1. Verify the service is running"
|
||||
if [[ "$OS_TYPE" == "linux" ]]; then
|
||||
echo " systemctl status ${SERVICE_NAME}"
|
||||
else
|
||||
echo " launchctl list | grep certctl"
|
||||
fi
|
||||
echo ""
|
||||
echo " 2. Visit your certctl dashboard: $SERVER_URL"
|
||||
echo " 3. The agent should appear in the fleet overview within 30 seconds"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Main installation flow
|
||||
main() {
|
||||
parse_args "$@"
|
||||
detect_platform
|
||||
check_privileges
|
||||
|
||||
echo -e "${GREEN}certctl Agent Installer${NC}"
|
||||
echo "Detected platform: ${OS_TYPE}-${ARCH_TYPE}"
|
||||
echo ""
|
||||
|
||||
prompt_for_config
|
||||
|
||||
# Download and install binary
|
||||
local binary_path
|
||||
binary_path=$(download_binary)
|
||||
install_binary "$binary_path"
|
||||
|
||||
# Setup OS-specific configuration
|
||||
if [[ "$OS_TYPE" == "linux" ]]; then
|
||||
setup_linux_config
|
||||
setup_systemd_service
|
||||
else
|
||||
setup_macos_config
|
||||
setup_launchd_service
|
||||
fi
|
||||
|
||||
# Start the service
|
||||
start_service
|
||||
|
||||
# Print summary
|
||||
print_summary
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -0,0 +1,187 @@
|
||||
-- =============================================================================
|
||||
-- Comprehensive Referential Integrity Check for seed_demo.sql
|
||||
-- Run AFTER migrations and seed data are loaded
|
||||
-- =============================================================================
|
||||
|
||||
-- 1. Verify certificate_versions.certificate_id references valid managed_certificates.id
|
||||
SELECT 'FK VIOLATION: certificate_versions.certificate_id' AS issue, cv.id, cv.certificate_id
|
||||
FROM certificate_versions cv
|
||||
WHERE cv.certificate_id NOT IN (SELECT id FROM managed_certificates)
|
||||
ORDER BY cv.id;
|
||||
|
||||
-- 2. Verify certificate_target_mappings references valid IDs
|
||||
SELECT 'FK VIOLATION: certificate_target_mappings.certificate_id' AS issue, ctm.certificate_id
|
||||
FROM certificate_target_mappings ctm
|
||||
WHERE ctm.certificate_id NOT IN (SELECT id FROM managed_certificates)
|
||||
ORDER BY ctm.certificate_id;
|
||||
|
||||
SELECT 'FK VIOLATION: certificate_target_mappings.target_id' AS issue, ctm.target_id
|
||||
FROM certificate_target_mappings ctm
|
||||
WHERE ctm.target_id NOT IN (SELECT id FROM deployment_targets)
|
||||
ORDER BY ctm.target_id;
|
||||
|
||||
-- 3. Verify jobs references valid IDs
|
||||
SELECT 'FK VIOLATION: jobs.certificate_id' AS issue, j.id, j.certificate_id
|
||||
FROM jobs j
|
||||
WHERE j.certificate_id NOT IN (SELECT id FROM managed_certificates)
|
||||
ORDER BY j.id;
|
||||
|
||||
SELECT 'FK VIOLATION: jobs.target_id' AS issue, j.id, j.target_id
|
||||
FROM jobs j
|
||||
WHERE j.target_id IS NOT NULL AND j.target_id NOT IN (SELECT id FROM deployment_targets)
|
||||
ORDER BY j.id;
|
||||
|
||||
SELECT 'FK VIOLATION: jobs.agent_id' AS issue, j.id, j.agent_id
|
||||
FROM jobs j
|
||||
WHERE j.agent_id NOT IN (SELECT id FROM agents)
|
||||
ORDER BY j.id;
|
||||
|
||||
-- 4. Verify discovered_certificates references valid IDs
|
||||
SELECT 'FK VIOLATION: discovered_certificates.agent_id' AS issue, dc.id, dc.agent_id
|
||||
FROM discovered_certificates dc
|
||||
WHERE dc.agent_id NOT IN (SELECT id FROM agents)
|
||||
ORDER BY dc.id;
|
||||
|
||||
SELECT 'FK VIOLATION: discovered_certificates.discovery_scan_id' AS issue, dc.id, dc.discovery_scan_id
|
||||
FROM discovered_certificates dc
|
||||
WHERE dc.discovery_scan_id IS NOT NULL AND dc.discovery_scan_id NOT IN (SELECT id FROM discovery_scans)
|
||||
ORDER BY dc.id;
|
||||
|
||||
-- 5. Verify notification_events references valid certificate_id
|
||||
SELECT 'FK VIOLATION: notification_events.certificate_id' AS issue, ne.id, ne.certificate_id
|
||||
FROM notification_events ne
|
||||
WHERE ne.certificate_id IS NOT NULL AND ne.certificate_id NOT IN (SELECT id FROM managed_certificates)
|
||||
ORDER BY ne.id;
|
||||
|
||||
-- 6. Verify policy_violations references valid certificate_id
|
||||
SELECT 'FK VIOLATION: policy_violations.certificate_id' AS issue, pv.id, pv.certificate_id
|
||||
FROM policy_violations pv
|
||||
WHERE pv.certificate_id NOT IN (SELECT id FROM managed_certificates)
|
||||
ORDER BY pv.id;
|
||||
|
||||
-- 7. Verify certificate_revocations references valid IDs
|
||||
SELECT 'FK VIOLATION: certificate_revocations.certificate_id' AS issue, cr.id, cr.certificate_id
|
||||
FROM certificate_revocations cr
|
||||
WHERE cr.certificate_id NOT IN (SELECT id FROM managed_certificates)
|
||||
ORDER BY cr.id;
|
||||
|
||||
SELECT 'FK VIOLATION: certificate_revocations.issuer_id' AS issue, cr.id, cr.issuer_id
|
||||
FROM certificate_revocations cr
|
||||
WHERE cr.issuer_id NOT IN (SELECT id FROM issuers)
|
||||
ORDER BY cr.id;
|
||||
|
||||
-- 8. Verify agent_group_members references valid IDs
|
||||
SELECT 'FK VIOLATION: agent_group_members.agent_group_id' AS issue, agm.agent_group_id
|
||||
FROM agent_group_members agm
|
||||
WHERE agm.agent_group_id NOT IN (SELECT id FROM agent_groups)
|
||||
ORDER BY agm.agent_group_id;
|
||||
|
||||
SELECT 'FK VIOLATION: agent_group_members.agent_id' AS issue, agm.agent_id
|
||||
FROM agent_group_members agm
|
||||
WHERE agm.agent_id NOT IN (SELECT id FROM agents)
|
||||
ORDER BY agm.agent_id;
|
||||
|
||||
-- 9. Verify owners.team_id references valid teams.id
|
||||
SELECT 'FK VIOLATION: owners.team_id' AS issue, o.id, o.team_id
|
||||
FROM owners o
|
||||
WHERE o.team_id IS NOT NULL AND o.team_id NOT IN (SELECT id FROM teams)
|
||||
ORDER BY o.id;
|
||||
|
||||
-- 10. Verify deployment_targets.agent_id references valid agents.id
|
||||
SELECT 'FK VIOLATION: deployment_targets.agent_id' AS issue, dt.id, dt.agent_id
|
||||
FROM deployment_targets dt
|
||||
WHERE dt.agent_id NOT IN (SELECT id FROM agents)
|
||||
ORDER BY dt.id;
|
||||
|
||||
-- 11. Verify managed_certificates FK columns
|
||||
SELECT 'FK VIOLATION: managed_certificates.owner_id' AS issue, mc.id, mc.owner_id
|
||||
FROM managed_certificates mc
|
||||
WHERE mc.owner_id IS NOT NULL AND mc.owner_id NOT IN (SELECT id FROM owners)
|
||||
ORDER BY mc.id;
|
||||
|
||||
SELECT 'FK VIOLATION: managed_certificates.team_id' AS issue, mc.id, mc.team_id
|
||||
FROM managed_certificates mc
|
||||
WHERE mc.team_id IS NOT NULL AND mc.team_id NOT IN (SELECT id FROM teams)
|
||||
ORDER BY mc.id;
|
||||
|
||||
SELECT 'FK VIOLATION: managed_certificates.issuer_id' AS issue, mc.id, mc.issuer_id
|
||||
FROM managed_certificates mc
|
||||
WHERE mc.issuer_id NOT IN (SELECT id FROM issuers)
|
||||
ORDER BY mc.id;
|
||||
|
||||
SELECT 'FK VIOLATION: managed_certificates.renewal_policy_id' AS issue, mc.id, mc.renewal_policy_id
|
||||
FROM managed_certificates mc
|
||||
WHERE mc.renewal_policy_id IS NOT NULL AND mc.renewal_policy_id NOT IN (SELECT id FROM renewal_policies)
|
||||
ORDER BY mc.id;
|
||||
|
||||
-- 12. Check for duplicate primary keys
|
||||
SELECT 'DUPLICATE PK: teams' AS issue, id, COUNT(*) as count
|
||||
FROM teams GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: owners' AS issue, id, COUNT(*) as count
|
||||
FROM owners GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: agents' AS issue, id, COUNT(*) as count
|
||||
FROM agents GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: deployment_targets' AS issue, id, COUNT(*) as count
|
||||
FROM deployment_targets GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: managed_certificates' AS issue, id, COUNT(*) as count
|
||||
FROM managed_certificates GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: certificate_versions' AS issue, id, COUNT(*) as count
|
||||
FROM certificate_versions GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: issuers' AS issue, id, COUNT(*) as count
|
||||
FROM issuers GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: renewal_policies' AS issue, id, COUNT(*) as count
|
||||
FROM renewal_policies GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: jobs' AS issue, id, COUNT(*) as count
|
||||
FROM jobs GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: certificate_profiles' AS issue, id, COUNT(*) as count
|
||||
FROM certificate_profiles GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
SELECT 'DUPLICATE PK: certificate_revocations' AS issue, id, COUNT(*) as count
|
||||
FROM certificate_revocations GROUP BY id HAVING COUNT(*) > 1;
|
||||
|
||||
-- 13. Check fingerprint_sha256 uniqueness in certificate_versions
|
||||
SELECT 'DUPLICATE FINGERPRINT: certificate_versions' AS issue, fingerprint_sha256, COUNT(*) as count
|
||||
FROM certificate_versions
|
||||
WHERE fingerprint_sha256 IS NOT NULL
|
||||
GROUP BY fingerprint_sha256
|
||||
HAVING COUNT(*) > 1;
|
||||
|
||||
-- 14. Check serial number uniqueness in certificate_versions
|
||||
SELECT 'DUPLICATE SERIAL: certificate_versions' AS issue, serial_number, COUNT(*) as count
|
||||
FROM certificate_versions
|
||||
WHERE serial_number IS NOT NULL
|
||||
GROUP BY serial_number
|
||||
HAVING COUNT(*) > 1;
|
||||
|
||||
-- 15. Verify discovery_scan_id references are valid
|
||||
SELECT 'FK VIOLATION: discovered_certificates.discovery_scan_id references' AS issue,
|
||||
dc.id, dc.discovery_scan_id, ds.id
|
||||
FROM discovered_certificates dc
|
||||
LEFT JOIN discovery_scans ds ON dc.discovery_scan_id = ds.id
|
||||
WHERE dc.discovery_scan_id IS NOT NULL AND ds.id IS NULL;
|
||||
|
||||
-- Summary: Count total records
|
||||
SELECT 'SUMMARY: teams' AS table_name, COUNT(*) as count FROM teams UNION ALL
|
||||
SELECT 'SUMMARY: owners', COUNT(*) FROM owners UNION ALL
|
||||
SELECT 'SUMMARY: agents', COUNT(*) FROM agents UNION ALL
|
||||
SELECT 'SUMMARY: deployment_targets', COUNT(*) FROM deployment_targets UNION ALL
|
||||
SELECT 'SUMMARY: managed_certificates', COUNT(*) FROM managed_certificates UNION ALL
|
||||
SELECT 'SUMMARY: certificate_versions', COUNT(*) FROM certificate_versions UNION ALL
|
||||
SELECT 'SUMMARY: certificate_target_mappings', COUNT(*) FROM certificate_target_mappings UNION ALL
|
||||
SELECT 'SUMMARY: issuers', COUNT(*) FROM issuers UNION ALL
|
||||
SELECT 'SUMMARY: renewal_policies', COUNT(*) FROM renewal_policies UNION ALL
|
||||
SELECT 'SUMMARY: jobs', COUNT(*) FROM jobs UNION ALL
|
||||
SELECT 'SUMMARY: certificate_profiles', COUNT(*) FROM certificate_profiles UNION ALL
|
||||
SELECT 'SUMMARY: certificate_revocations', COUNT(*) FROM certificate_revocations UNION ALL
|
||||
SELECT 'SUMMARY: audit_events', COUNT(*) FROM audit_events UNION ALL
|
||||
SELECT 'SUMMARY: discovery_scans', COUNT(*) FROM discovery_scans UNION ALL
|
||||
SELECT 'SUMMARY: discovered_certificates', COUNT(*) FROM discovered_certificates;
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -134,6 +135,11 @@ func (h AgentHandler) RegisterAgent(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
created, err := h.svc.RegisterAgent(r.Context(), agent)
|
||||
if err != nil {
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "unique") || strings.Contains(errMsg, "duplicate") || strings.Contains(errMsg, "already exists") {
|
||||
ErrorWithRequestID(w, http.StatusConflict, "Agent with this name already exists", requestID)
|
||||
return
|
||||
}
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to register agent", requestID)
|
||||
return
|
||||
}
|
||||
@@ -184,6 +190,11 @@ func (h AgentHandler) Heartbeat(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if err := h.svc.Heartbeat(r.Context(), agentID, metadata); err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Agent not found", requestID)
|
||||
return
|
||||
}
|
||||
slog.Error("Heartbeat failed", "agent_id", agentID, "error", err.Error())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to record heartbeat", requestID)
|
||||
return
|
||||
}
|
||||
@@ -241,6 +252,7 @@ func (h AgentHandler) AgentCSRSubmit(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
slog.Error("CSR submission failed", "agent_id", agentID, "certificate_id", req.CertificateID, "error", err.Error())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to submit CSR", requestID)
|
||||
return
|
||||
}
|
||||
@@ -263,9 +275,10 @@ func (h AgentHandler) AgentCertificatePickup(w http.ResponseWriter, r *http.Requ
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// Extract agent ID and certificate ID from path /api/v1/agents/{id}/certificates/{cert_id}
|
||||
// After TrimPrefix, path is "{id}/certificates/{cert_id}" → split gives [id, "certificates", cert_id]
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/agents/")
|
||||
parts := strings.Split(path, "/")
|
||||
if len(parts) < 4 || parts[0] == "" || parts[2] == "" {
|
||||
if len(parts) < 3 || parts[0] == "" || parts[2] == "" {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Agent ID and Certificate ID are required", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -353,11 +353,12 @@ func TestCreateCertificate_Success(t *testing.T) {
|
||||
handler := NewCertificateHandler(mock)
|
||||
|
||||
certBody := domain.ManagedCertificate{
|
||||
Name: "Production Cert",
|
||||
CommonName: "example.com",
|
||||
OwnerID: "o-alice",
|
||||
TeamID: "t-platform",
|
||||
IssuerID: "iss-local",
|
||||
Name: "Production Cert",
|
||||
CommonName: "example.com",
|
||||
OwnerID: "o-alice",
|
||||
TeamID: "t-platform",
|
||||
IssuerID: "iss-local",
|
||||
RenewalPolicyID: "rp-standard",
|
||||
}
|
||||
body, _ := json.Marshal(certBody)
|
||||
|
||||
@@ -410,11 +411,12 @@ func TestCreateCertificate_ServiceError(t *testing.T) {
|
||||
handler := NewCertificateHandler(mock)
|
||||
|
||||
certBody := domain.ManagedCertificate{
|
||||
Name: "Production Cert",
|
||||
CommonName: "example.com",
|
||||
OwnerID: "o-alice",
|
||||
TeamID: "t-platform",
|
||||
IssuerID: "iss-local",
|
||||
Name: "Production Cert",
|
||||
CommonName: "example.com",
|
||||
OwnerID: "o-alice",
|
||||
TeamID: "t-platform",
|
||||
IssuerID: "iss-local",
|
||||
RenewalPolicyID: "rp-standard",
|
||||
}
|
||||
body, _ := json.Marshal(certBody)
|
||||
|
||||
@@ -534,8 +536,8 @@ func TestArchiveCertificate_NotFound(t *testing.T) {
|
||||
|
||||
handler.ArchiveCertificate(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status %d, got %d", http.StatusInternalServerError, w.Code)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected status %d, got %d", http.StatusNotFound, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -231,9 +232,18 @@ func (h CertificateHandler) CreateCertificate(w http.ResponseWriter, r *http.Req
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
|
||||
return
|
||||
}
|
||||
if err := ValidateRequired("name", cert.Name); err != nil {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
|
||||
return
|
||||
}
|
||||
if err := ValidateRequired("renewal_policy_id", cert.RenewalPolicyID); err != nil {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
|
||||
return
|
||||
}
|
||||
|
||||
created, err := h.svc.CreateCertificate(cert)
|
||||
if err != nil {
|
||||
slog.Error("failed to create certificate", "error", err, "request_id", requestID, "common_name", cert.CommonName, "name", cert.Name)
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to create certificate", requestID)
|
||||
return
|
||||
}
|
||||
@@ -287,6 +297,11 @@ func (h CertificateHandler) UpdateCertificate(w http.ResponseWriter, r *http.Req
|
||||
|
||||
updated, err := h.svc.UpdateCertificate(id, cert)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Certificate not found", requestID)
|
||||
return
|
||||
}
|
||||
slog.Error("UpdateCertificate failed", "cert_id", id, "error", err.Error())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to update certificate", requestID)
|
||||
return
|
||||
}
|
||||
@@ -311,6 +326,10 @@ func (h CertificateHandler) ArchiveCertificate(w http.ResponseWriter, r *http.Re
|
||||
}
|
||||
|
||||
if err := h.svc.ArchiveCertificate(id); err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Certificate not found", requestID)
|
||||
return
|
||||
}
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to archive certificate", requestID)
|
||||
return
|
||||
}
|
||||
@@ -353,7 +372,12 @@ func (h CertificateHandler) GetCertificateVersions(w http.ResponseWriter, r *htt
|
||||
|
||||
versions, total, err := h.svc.GetCertificateVersions(certID, page, perPage)
|
||||
if err != nil {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Certificate not found", requestID)
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Certificate not found", requestID)
|
||||
return
|
||||
}
|
||||
slog.Error("GetCertificateVersions failed", "cert_id", certID, "error", err.Error())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to get certificate versions", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -387,6 +411,19 @@ func (h CertificateHandler) TriggerRenewal(w http.ResponseWriter, r *http.Reques
|
||||
certID := parts[0]
|
||||
|
||||
if err := h.svc.TriggerRenewal(certID); err != nil {
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Certificate not found", requestID)
|
||||
return
|
||||
}
|
||||
if strings.Contains(errMsg, "cannot renew") {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, errMsg, requestID)
|
||||
return
|
||||
}
|
||||
if strings.Contains(errMsg, "already in progress") {
|
||||
ErrorWithRequestID(w, http.StatusConflict, errMsg, requestID)
|
||||
return
|
||||
}
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to trigger renewal", requestID)
|
||||
return
|
||||
}
|
||||
@@ -480,7 +517,7 @@ func (h CertificateHandler) RevokeCertificate(w http.ResponseWriter, r *http.Req
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, errMsg, requestID)
|
||||
return
|
||||
}
|
||||
if strings.Contains(errMsg, "not found") || strings.Contains(errMsg, "failed to fetch") {
|
||||
if strings.Contains(errMsg, "not found") || strings.Contains(errMsg, "failed to fetch") || strings.Contains(errMsg, "failed to get") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Certificate not found", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// DigestServicer defines the interface for digest operations used by the handler.
|
||||
type DigestServicer interface {
|
||||
PreviewDigest(ctx context.Context) (string, error)
|
||||
SendDigest(ctx context.Context) error
|
||||
}
|
||||
|
||||
// DigestHandler provides HTTP endpoints for certificate digest operations.
|
||||
type DigestHandler struct {
|
||||
service DigestServicer
|
||||
}
|
||||
|
||||
// NewDigestHandler creates a new digest handler.
|
||||
func NewDigestHandler(service DigestServicer) *DigestHandler {
|
||||
return &DigestHandler{service: service}
|
||||
}
|
||||
|
||||
// PreviewDigest renders the digest HTML without sending it.
|
||||
// GET /api/v1/digest/preview
|
||||
func (h *DigestHandler) PreviewDigest(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if h.service == nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "digest service not configured"})
|
||||
return
|
||||
}
|
||||
|
||||
html, err := h.service.PreviewDigest(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(html))
|
||||
}
|
||||
|
||||
// SendDigest triggers an immediate digest send.
|
||||
// POST /api/v1/digest/send
|
||||
func (h *DigestHandler) SendDigest(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if h.service == nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "digest service not configured"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.service.SendDigest(r.Context()); err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "sent"})
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// mockDigestService implements DigestServicer for testing.
|
||||
type mockDigestService struct {
|
||||
previewHTML string
|
||||
previewErr error
|
||||
sendErr error
|
||||
sendCalled bool
|
||||
}
|
||||
|
||||
func (m *mockDigestService) PreviewDigest(ctx context.Context) (string, error) {
|
||||
if m.previewErr != nil {
|
||||
return "", m.previewErr
|
||||
}
|
||||
return m.previewHTML, nil
|
||||
}
|
||||
|
||||
func (m *mockDigestService) SendDigest(ctx context.Context) error {
|
||||
m.sendCalled = true
|
||||
return m.sendErr
|
||||
}
|
||||
|
||||
func TestDigestHandler_PreviewDigest_Success(t *testing.T) {
|
||||
svc := &mockDigestService{
|
||||
previewHTML: "<html><body>Digest Preview</body></html>",
|
||||
}
|
||||
h := NewDigestHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/digest/preview", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.PreviewDigest(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
if w.Header().Get("Content-Type") != "text/html; charset=utf-8" {
|
||||
t.Errorf("expected Content-Type text/html, got %s", w.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
if w.Body.String() != "<html><body>Digest Preview</body></html>" {
|
||||
t.Errorf("unexpected body: %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestHandler_PreviewDigest_MethodNotAllowed(t *testing.T) {
|
||||
svc := &mockDigestService{}
|
||||
h := NewDigestHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/digest/preview", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.PreviewDigest(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected status 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestHandler_PreviewDigest_ServiceError(t *testing.T) {
|
||||
svc := &mockDigestService{
|
||||
previewErr: errors.New("stats unavailable"),
|
||||
}
|
||||
h := NewDigestHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/digest/preview", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.PreviewDigest(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestHandler_PreviewDigest_NotConfigured(t *testing.T) {
|
||||
h := NewDigestHandler(nil)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/digest/preview", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.PreviewDigest(w, req)
|
||||
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Errorf("expected status 503, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestHandler_SendDigest_Success(t *testing.T) {
|
||||
svc := &mockDigestService{}
|
||||
h := NewDigestHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/digest/send", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.SendDigest(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
if !svc.sendCalled {
|
||||
t.Error("expected SendDigest to be called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestHandler_SendDigest_MethodNotAllowed(t *testing.T) {
|
||||
svc := &mockDigestService{}
|
||||
h := NewDigestHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/digest/send", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.SendDigest(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected status 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestHandler_SendDigest_ServiceError(t *testing.T) {
|
||||
svc := &mockDigestService{
|
||||
sendErr: errors.New("SMTP connection refused"),
|
||||
}
|
||||
h := NewDigestHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/digest/send", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.SendDigest(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestHandler_SendDigest_NotConfigured(t *testing.T) {
|
||||
h := NewDigestHandler(nil)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/digest/send", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.SendDigest(w, req)
|
||||
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Errorf("expected status 503, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -610,3 +610,122 @@ func TestGetDiscoverySummary_MethodNotAllowed(t *testing.T) {
|
||||
t.Errorf("expected status %d, got %d", http.StatusMethodNotAllowed, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test DismissDiscovered - service error
|
||||
func TestDismissDiscovered_ServiceError(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
DismissDiscoveredFn: func(ctx context.Context, id string) error {
|
||||
return fmt.Errorf("database error")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/discovered-certificates/dcert-1/dismiss", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "dcert-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.DismissDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status %d, got %d", http.StatusInternalServerError, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ClaimDiscovered - invalid body (malformed JSON)
|
||||
func TestClaimDiscovered_InvalidJSON(t *testing.T) {
|
||||
mock := &MockDiscoveryService{}
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/discovered-certificates/dcert-1/claim", bytes.NewReader([]byte("invalid json")))
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "dcert-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ClaimDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status %d, got %d", http.StatusBadRequest, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ClaimDiscovered - method not allowed
|
||||
func TestClaimDiscovered_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockDiscoveryService{}
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovered-certificates/dcert-1/claim", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "dcert-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ClaimDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected status %d, got %d", http.StatusMethodNotAllowed, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ListDiscovered - service error
|
||||
func TestListDiscovered_ServiceError(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
ListDiscoveredFn: func(ctx context.Context, agentID, status string, page, perPage int) ([]*domain.DiscoveredCertificate, int, error) {
|
||||
return nil, 0, fmt.Errorf("database error")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovered-certificates", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status %d, got %d", http.StatusInternalServerError, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ListScans - service error
|
||||
func TestListScans_ServiceError(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
ListScansFn: func(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error) {
|
||||
return nil, 0, fmt.Errorf("database error")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovery-scans", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListScans(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status %d, got %d", http.StatusInternalServerError, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetDiscoverySummary - service error
|
||||
func TestGetDiscoverySummary_ServiceError(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
GetDiscoverySummaryFn: func(ctx context.Context) (map[string]int, error) {
|
||||
return nil, fmt.Errorf("database error")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovery-summary", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetDiscoverySummary(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status %d, got %d", http.StatusInternalServerError, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,3 +396,49 @@ func TestASN1EncodeLength(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTCSRAttrs_ServiceError(t *testing.T) {
|
||||
svc := &mockESTService{
|
||||
CSRAttrsErr: errors.New("service error"),
|
||||
}
|
||||
h := NewESTHandler(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/csrattrs", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.CSRAttrs(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTSimpleReEnroll_ServiceError(t *testing.T) {
|
||||
csrPEM := generateTestCSRPEM(t)
|
||||
svc := &mockESTService{
|
||||
EnrollErr: errors.New("renewal failed"),
|
||||
}
|
||||
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.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestESTCACerts_UnableToGetCerts(t *testing.T) {
|
||||
svc := &mockESTService{
|
||||
CACertErr: errors.New("CA 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
"github.com/shankar0123/certctl/internal/service"
|
||||
)
|
||||
|
||||
// ExportService defines the service interface for certificate export operations.
|
||||
type ExportService interface {
|
||||
ExportPEM(ctx context.Context, certID string) (*service.ExportPEMResult, error)
|
||||
ExportPKCS12(ctx context.Context, certID string, password string) ([]byte, error)
|
||||
}
|
||||
|
||||
// ExportHandler handles HTTP requests for certificate export operations.
|
||||
type ExportHandler struct {
|
||||
svc ExportService
|
||||
}
|
||||
|
||||
// NewExportHandler creates a new ExportHandler with a service dependency.
|
||||
func NewExportHandler(svc ExportService) ExportHandler {
|
||||
return ExportHandler{svc: svc}
|
||||
}
|
||||
|
||||
// ExportPEM exports a certificate and its chain in PEM format.
|
||||
// GET /api/v1/certificates/{id}/export/pem
|
||||
func (h ExportHandler) ExportPEM(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// Extract certificate ID from path: /api/v1/certificates/{id}/export/pem
|
||||
id := extractCertIDFromExportPath(r.URL.Path)
|
||||
if id == "" {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Certificate ID is required", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.svc.ExportPEM(r.Context(), id)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Certificate not found", requestID)
|
||||
return
|
||||
}
|
||||
slog.Error("ExportPEM failed", "cert_id", id, "error", err.Error())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to export certificate", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if client wants file download via Accept header or ?download=true query param
|
||||
if r.URL.Query().Get("download") == "true" {
|
||||
w.Header().Set("Content-Type", "application/x-pem-file")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\"certificate.pem\"")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(result.FullPEM))
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// ExportPKCS12 exports a certificate and chain in PKCS#12 format.
|
||||
// POST /api/v1/certificates/{id}/export/pkcs12
|
||||
// Body: { "password": "optional-password" }
|
||||
func (h ExportHandler) ExportPKCS12(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// Extract certificate ID from path: /api/v1/certificates/{id}/export/pkcs12
|
||||
id := extractCertIDFromExportPath(r.URL.Path)
|
||||
if id == "" {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Certificate ID is required", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse optional password from request body (may be empty)
|
||||
var req struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
// Body is optional — empty body means empty password
|
||||
_ = parseJSONBody(r, &req)
|
||||
|
||||
pfxData, err := h.svc.ExportPKCS12(r.Context(), id, req.Password)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Certificate not found", requestID)
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "cannot be parsed") || strings.Contains(err.Error(), "no certificates found") {
|
||||
ErrorWithRequestID(w, http.StatusUnprocessableEntity, "Certificate data cannot be parsed as X.509", requestID)
|
||||
return
|
||||
}
|
||||
slog.Error("ExportPKCS12 failed", "cert_id", id, "error", err.Error())
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to export PKCS#12", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/x-pkcs12")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\"certificate.p12\"")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(pfxData)
|
||||
}
|
||||
|
||||
// extractCertIDFromExportPath extracts the certificate ID from an export path.
|
||||
// Path format: /api/v1/certificates/{id}/export/pem or /api/v1/certificates/{id}/export/pkcs12
|
||||
func extractCertIDFromExportPath(path string) string {
|
||||
prefix := "/api/v1/certificates/"
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
return ""
|
||||
}
|
||||
rest := strings.TrimPrefix(path, prefix)
|
||||
// rest should be "{id}/export/pem" or "{id}/export/pkcs12"
|
||||
parts := strings.Split(rest, "/")
|
||||
if len(parts) < 3 || parts[1] != "export" {
|
||||
return ""
|
||||
}
|
||||
return parts[0]
|
||||
}
|
||||
|
||||
// parseJSONBody is a helper that decodes JSON from the request body.
|
||||
// Returns an error if the body is malformed, nil if body is empty.
|
||||
func parseJSONBody(r *http.Request, v interface{}) error {
|
||||
if r.Body == nil {
|
||||
return nil
|
||||
}
|
||||
return json.NewDecoder(r.Body).Decode(v)
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/service"
|
||||
)
|
||||
|
||||
// Add context import was already there — verify import is present above
|
||||
|
||||
// MockExportService is a mock implementation of ExportService interface.
|
||||
type MockExportService struct {
|
||||
ExportPEMFn func(ctx context.Context, certID string) (*service.ExportPEMResult, error)
|
||||
ExportPKCS12Fn func(ctx context.Context, certID string, password string) ([]byte, error)
|
||||
}
|
||||
|
||||
func (m *MockExportService) ExportPEM(ctx context.Context, certID string) (*service.ExportPEMResult, error) {
|
||||
if m.ExportPEMFn != nil {
|
||||
return m.ExportPEMFn(ctx, certID)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockExportService) ExportPKCS12(ctx context.Context, certID string, password string) ([]byte, error) {
|
||||
if m.ExportPKCS12Fn != nil {
|
||||
return m.ExportPKCS12Fn(ctx, certID, password)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestExportPEM_Success(t *testing.T) {
|
||||
mockSvc := &MockExportService{
|
||||
ExportPEMFn: func(_ context.Context, certID string) (*service.ExportPEMResult, error) {
|
||||
if certID != "mc-test-1" {
|
||||
t.Errorf("expected certID mc-test-1, got %s", certID)
|
||||
}
|
||||
return &service.ExportPEMResult{
|
||||
CertPEM: "-----BEGIN CERTIFICATE-----\nAAA\n-----END CERTIFICATE-----\n",
|
||||
ChainPEM: "-----BEGIN CERTIFICATE-----\nBBB\n-----END CERTIFICATE-----\n",
|
||||
FullPEM: "-----BEGIN CERTIFICATE-----\nAAA\n-----END CERTIFICATE-----\n-----BEGIN CERTIFICATE-----\nBBB\n-----END CERTIFICATE-----\n",
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
h := NewExportHandler(mockSvc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/certificates/mc-test-1/export/pem", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPEM(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); ct != "application/json" {
|
||||
t.Errorf("expected application/json content type, got %s", ct)
|
||||
}
|
||||
|
||||
var result service.ExportPEMResult
|
||||
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
if result.CertPEM == "" {
|
||||
t.Error("expected non-empty CertPEM")
|
||||
}
|
||||
if result.ChainPEM == "" {
|
||||
t.Error("expected non-empty ChainPEM")
|
||||
}
|
||||
if result.FullPEM == "" {
|
||||
t.Error("expected non-empty FullPEM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPEM_Download(t *testing.T) {
|
||||
mockSvc := &MockExportService{
|
||||
ExportPEMFn: func(_ context.Context, _ string) (*service.ExportPEMResult, error) {
|
||||
return &service.ExportPEMResult{
|
||||
CertPEM: "cert",
|
||||
ChainPEM: "chain",
|
||||
FullPEM: "full-pem-content",
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
h := NewExportHandler(mockSvc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/certificates/mc-test-1/export/pem?download=true", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPEM(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); ct != "application/x-pem-file" {
|
||||
t.Errorf("expected application/x-pem-file, got %s", ct)
|
||||
}
|
||||
if cd := w.Header().Get("Content-Disposition"); cd != `attachment; filename="certificate.pem"` {
|
||||
t.Errorf("expected Content-Disposition attachment, got %s", cd)
|
||||
}
|
||||
if w.Body.String() != "full-pem-content" {
|
||||
t.Errorf("expected full-pem-content body, got %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPEM_NotFound(t *testing.T) {
|
||||
mockSvc := &MockExportService{
|
||||
ExportPEMFn: func(_ context.Context, _ string) (*service.ExportPEMResult, error) {
|
||||
return nil, fmt.Errorf("certificate not found")
|
||||
},
|
||||
}
|
||||
h := NewExportHandler(mockSvc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/certificates/nonexistent/export/pem", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPEM(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPEM_ServiceError(t *testing.T) {
|
||||
mockSvc := &MockExportService{
|
||||
ExportPEMFn: func(_ context.Context, _ string) (*service.ExportPEMResult, error) {
|
||||
return nil, fmt.Errorf("internal error")
|
||||
},
|
||||
}
|
||||
h := NewExportHandler(mockSvc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/certificates/mc-test-1/export/pem", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPEM(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPEM_MethodNotAllowed(t *testing.T) {
|
||||
h := NewExportHandler(&MockExportService{})
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/mc-test-1/export/pem", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPEM(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPKCS12_Success(t *testing.T) {
|
||||
pfxData := []byte{0x30, 0x82, 0x01, 0x00} // mock PKCS#12 data
|
||||
mockSvc := &MockExportService{
|
||||
ExportPKCS12Fn: func(_ context.Context, certID string, password string) ([]byte, error) {
|
||||
if certID != "mc-test-1" {
|
||||
t.Errorf("expected certID mc-test-1, got %s", certID)
|
||||
}
|
||||
if password != "mysecret" {
|
||||
t.Errorf("expected password mysecret, got %s", password)
|
||||
}
|
||||
return pfxData, nil
|
||||
},
|
||||
}
|
||||
h := NewExportHandler(mockSvc)
|
||||
|
||||
body := strings.NewReader(`{"password":"mysecret"}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/mc-test-1/export/pkcs12", body)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPKCS12(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); ct != "application/x-pkcs12" {
|
||||
t.Errorf("expected application/x-pkcs12, got %s", ct)
|
||||
}
|
||||
if cd := w.Header().Get("Content-Disposition"); cd != `attachment; filename="certificate.p12"` {
|
||||
t.Errorf("expected Content-Disposition attachment, got %s", cd)
|
||||
}
|
||||
if len(w.Body.Bytes()) != len(pfxData) {
|
||||
t.Errorf("expected %d bytes, got %d", len(pfxData), len(w.Body.Bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPKCS12_EmptyPassword(t *testing.T) {
|
||||
mockSvc := &MockExportService{
|
||||
ExportPKCS12Fn: func(_ context.Context, _ string, password string) ([]byte, error) {
|
||||
if password != "" {
|
||||
t.Errorf("expected empty password, got %s", password)
|
||||
}
|
||||
return []byte{0x30}, nil
|
||||
},
|
||||
}
|
||||
h := NewExportHandler(mockSvc)
|
||||
|
||||
// Empty body — password defaults to ""
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/mc-test-1/export/pkcs12", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPKCS12(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPKCS12_NotFound(t *testing.T) {
|
||||
mockSvc := &MockExportService{
|
||||
ExportPKCS12Fn: func(_ context.Context, _ string, _ string) ([]byte, error) {
|
||||
return nil, fmt.Errorf("certificate not found")
|
||||
},
|
||||
}
|
||||
h := NewExportHandler(mockSvc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/nonexistent/export/pkcs12", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPKCS12(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPKCS12_ServiceError(t *testing.T) {
|
||||
mockSvc := &MockExportService{
|
||||
ExportPKCS12Fn: func(_ context.Context, _ string, _ string) ([]byte, error) {
|
||||
return nil, fmt.Errorf("encoding error")
|
||||
},
|
||||
}
|
||||
h := NewExportHandler(mockSvc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/mc-test-1/export/pkcs12", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPKCS12(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPKCS12_MethodNotAllowed(t *testing.T) {
|
||||
h := NewExportHandler(&MockExportService{})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/certificates/mc-test-1/export/pkcs12", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPKCS12(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractCertIDFromExportPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
path string
|
||||
expected string
|
||||
}{
|
||||
{"/api/v1/certificates/mc-test-1/export/pem", "mc-test-1"},
|
||||
{"/api/v1/certificates/mc-api-prod/export/pkcs12", "mc-api-prod"},
|
||||
{"/api/v1/certificates//export/pem", ""},
|
||||
{"/api/v1/other/mc-test-1/export/pem", ""},
|
||||
{"/api/v1/certificates/mc-test-1", ""},
|
||||
{"", ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := extractCertIDFromExportPath(tt.path)
|
||||
if got != tt.expected {
|
||||
t.Errorf("extractCertIDFromExportPath(%q) = %q, want %q", tt.path, got, tt.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPKCS12_InvalidJSON(t *testing.T) {
|
||||
mockSvc := &MockExportService{
|
||||
ExportPKCS12Fn: func(_ context.Context, _ string, password string) ([]byte, error) {
|
||||
// Invalid JSON is silently ignored, defaults to empty password
|
||||
if password != "" {
|
||||
t.Errorf("expected empty password (invalid JSON ignored), got %s", password)
|
||||
}
|
||||
return []byte{0x30}, nil
|
||||
},
|
||||
}
|
||||
h := NewExportHandler(mockSvc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/mc-test-1/export/pkcs12", strings.NewReader(`{"invalid json`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPKCS12(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200 (invalid JSON ignored), got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportPEM_MethodNotAllowedDelete(t *testing.T) {
|
||||
h := NewExportHandler(&MockExportService{})
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/certificates/mc-test-1/export/pem", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ExportPEM(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -316,3 +316,115 @@ func TestGetPrometheusMetrics_ZeroValues(t *testing.T) {
|
||||
func containsLine(text, substr string) bool {
|
||||
return strings.Contains(text, substr)
|
||||
}
|
||||
|
||||
// Test GetCertificatesByStatus - method not allowed
|
||||
func TestGetCertificatesByStatus_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockStatsService{}
|
||||
h := NewStatsHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/stats/certificates-by-status", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.GetCertificatesByStatus(w, req)
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetCertificatesByStatus - service error
|
||||
func TestGetCertificatesByStatus_ServiceError(t *testing.T) {
|
||||
mock := &MockStatsService{
|
||||
GetCertificatesByStatusFn: func(ctx context.Context) (interface{}, error) {
|
||||
return nil, fmt.Errorf("db error")
|
||||
},
|
||||
}
|
||||
h := NewStatsHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/stats/certificates-by-status", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.GetCertificatesByStatus(w, req)
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetExpirationTimeline - method not allowed
|
||||
func TestGetExpirationTimeline_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockStatsService{}
|
||||
h := NewStatsHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/stats/expiration-timeline", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.GetExpirationTimeline(w, req)
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetExpirationTimeline - service error
|
||||
func TestGetExpirationTimeline_ServiceError(t *testing.T) {
|
||||
mock := &MockStatsService{
|
||||
GetExpirationTimelineFn: func(ctx context.Context, days int) (interface{}, error) {
|
||||
return nil, fmt.Errorf("db error")
|
||||
},
|
||||
}
|
||||
h := NewStatsHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/stats/expiration-timeline?days=30", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.GetExpirationTimeline(w, req)
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetJobTrends - method not allowed
|
||||
func TestGetJobTrends_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockStatsService{}
|
||||
h := NewStatsHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/stats/job-trends", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.GetJobTrends(w, req)
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetJobTrends - service error
|
||||
func TestGetJobTrends_ServiceError(t *testing.T) {
|
||||
mock := &MockStatsService{
|
||||
GetJobStatsFn: func(ctx context.Context, days int) (interface{}, error) {
|
||||
return nil, fmt.Errorf("db error")
|
||||
},
|
||||
}
|
||||
h := NewStatsHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/stats/job-trends?days=14", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.GetJobTrends(w, req)
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetIssuanceRate - method not allowed
|
||||
func TestGetIssuanceRate_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockStatsService{}
|
||||
h := NewStatsHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/stats/issuance-rate", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.GetIssuanceRate(w, req)
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetIssuanceRate - service error
|
||||
func TestGetIssuanceRate_ServiceError(t *testing.T) {
|
||||
mock := &MockStatsService{
|
||||
GetIssuanceRateFn: func(ctx context.Context, days int) (interface{}, error) {
|
||||
return nil, fmt.Errorf("db error")
|
||||
},
|
||||
}
|
||||
h := NewStatsHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/stats/issuance-rate?days=7", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.GetIssuanceRate(w, req)
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,11 +13,12 @@ import (
|
||||
|
||||
// MockTargetService is a mock implementation of TargetService interface.
|
||||
type MockTargetService struct {
|
||||
ListTargetsFn func(page, perPage int) ([]domain.DeploymentTarget, int64, error)
|
||||
GetTargetFn func(id string) (*domain.DeploymentTarget, error)
|
||||
CreateTargetFn func(target domain.DeploymentTarget) (*domain.DeploymentTarget, error)
|
||||
UpdateTargetFn func(id string, target domain.DeploymentTarget) (*domain.DeploymentTarget, error)
|
||||
DeleteTargetFn func(id string) error
|
||||
ListTargetsFn func(page, perPage int) ([]domain.DeploymentTarget, int64, error)
|
||||
GetTargetFn func(id string) (*domain.DeploymentTarget, error)
|
||||
CreateTargetFn func(target domain.DeploymentTarget) (*domain.DeploymentTarget, error)
|
||||
UpdateTargetFn func(id string, target domain.DeploymentTarget) (*domain.DeploymentTarget, error)
|
||||
DeleteTargetFn func(id string) error
|
||||
TestTargetConnectionFn func(id string) error
|
||||
}
|
||||
|
||||
func (m *MockTargetService) ListTargets(page, perPage int) ([]domain.DeploymentTarget, int64, error) {
|
||||
@@ -55,6 +56,13 @@ func (m *MockTargetService) DeleteTarget(id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockTargetService) TestTargetConnection(id string) error {
|
||||
if m.TestTargetConnectionFn != nil {
|
||||
return m.TestTargetConnectionFn(id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestListTargets_Success(t *testing.T) {
|
||||
now := time.Now()
|
||||
t1 := domain.DeploymentTarget{
|
||||
@@ -419,3 +427,69 @@ func TestDeleteTarget_EmptyID(t *testing.T) {
|
||||
t.Fatalf("expected status 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestTargetConnection_Success(t *testing.T) {
|
||||
mock := &MockTargetService{
|
||||
TestTargetConnectionFn: func(id string) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewTargetHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/targets/t-nginx-01/test", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.TestTargetConnection(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
if resp["status"] != "success" {
|
||||
t.Errorf("expected status 'success', got %v", resp["status"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestTargetConnection_Failed(t *testing.T) {
|
||||
mock := &MockTargetService{
|
||||
TestTargetConnectionFn: func(id string) error {
|
||||
return ErrMockServiceFailed
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewTargetHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/targets/t-nginx-01/test", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.TestTargetConnection(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
if resp["status"] != "failed" {
|
||||
t.Errorf("expected status 'failed', got %v", resp["status"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestTargetConnection_MethodNotAllowed(t *testing.T) {
|
||||
handler := NewTargetHandler(&MockTargetService{})
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/targets/t-nginx-01/test", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.TestTargetConnection(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("expected status 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ type TargetService interface {
|
||||
CreateTarget(target domain.DeploymentTarget) (*domain.DeploymentTarget, error)
|
||||
UpdateTarget(id string, target domain.DeploymentTarget) (*domain.DeploymentTarget, error)
|
||||
DeleteTarget(id string) error
|
||||
TestTargetConnection(id string) error
|
||||
}
|
||||
|
||||
// TargetHandler handles HTTP requests for deployment target operations.
|
||||
@@ -189,3 +190,36 @@ func (h TargetHandler) DeleteTarget(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// TestTargetConnection tests target connectivity by checking the assigned agent's heartbeat.
|
||||
// POST /api/v1/targets/{id}/test
|
||||
func (h TargetHandler) TestTargetConnection(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// Extract target ID from path: /api/v1/targets/{id}/test
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/targets/")
|
||||
parts := strings.Split(path, "/")
|
||||
if len(parts) < 2 || parts[0] == "" {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Target ID is required", requestID)
|
||||
return
|
||||
}
|
||||
id := parts[0]
|
||||
|
||||
if err := h.svc.TestTargetConnection(id); err != nil {
|
||||
JSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": "failed",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": "Agent is online and reachable",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/mail"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -13,6 +14,7 @@ type ValidationError struct {
|
||||
}
|
||||
|
||||
// ValidateCommonName validates a certificate common name.
|
||||
// Accepts hostnames (TLS), IP addresses, and email addresses (S/MIME).
|
||||
func ValidateCommonName(cn string) error {
|
||||
if cn == "" {
|
||||
return ValidationError{Field: "common_name", Message: "common_name is required"}
|
||||
@@ -20,6 +22,13 @@ func ValidateCommonName(cn string) error {
|
||||
if len(cn) > 253 {
|
||||
return ValidationError{Field: "common_name", Message: "common_name must be 253 characters or fewer"}
|
||||
}
|
||||
// If CN contains @, validate as email address (S/MIME certificates)
|
||||
if strings.Contains(cn, "@") {
|
||||
if _, err := mail.ParseAddress(cn); err != nil {
|
||||
return ValidationError{Field: "common_name", Message: fmt.Sprintf("invalid email format for S/MIME common name: %v", err)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Basic hostname validation: allow alphanumeric, dots, hyphens
|
||||
if err := isValidHostname(cn); err != nil {
|
||||
return ValidationError{Field: "common_name", Message: fmt.Sprintf("invalid hostname format: %v", err)}
|
||||
|
||||
@@ -249,6 +249,58 @@ func TestVerifyDeployment_ServiceError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyDeployment_EmptyBody(t *testing.T) {
|
||||
mockSvc := &mockVerificationService{}
|
||||
handler := NewVerificationHandler(mockSvc)
|
||||
|
||||
httpReq := httptest.NewRequest("POST", "/api/v1/jobs/j-test10/verify", bytes.NewBufferString(""))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.VerifyDeployment(w, httpReq)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetVerificationStatus_ServiceError(t *testing.T) {
|
||||
mockSvc := &mockVerificationService{
|
||||
getErr: ErrServiceUnavailable,
|
||||
}
|
||||
handler := NewVerificationHandler(mockSvc)
|
||||
|
||||
httpReq := httptest.NewRequest("GET", "/api/v1/jobs/j-test11/verification", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetVerificationStatus(w, httpReq)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetVerificationStatus_NotFound(t *testing.T) {
|
||||
mockSvc := &mockVerificationService{
|
||||
results: make(map[string]*domain.VerificationResult),
|
||||
}
|
||||
handler := NewVerificationHandler(mockSvc)
|
||||
|
||||
httpReq := httptest.NewRequest("GET", "/api/v1/jobs/j-nonexistent/verification", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetVerificationStatus(w, httpReq)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var result *domain.VerificationResult
|
||||
json.NewDecoder(w.Body).Decode(&result)
|
||||
if result != nil {
|
||||
t.Error("expected nil result for nonexistent job")
|
||||
}
|
||||
}
|
||||
|
||||
var ErrServiceUnavailable = NewServiceError("service unavailable")
|
||||
|
||||
func NewServiceError(msg string) error {
|
||||
|
||||
@@ -63,6 +63,8 @@ type HandlerRegistry struct {
|
||||
Discovery handler.DiscoveryHandler
|
||||
NetworkScan handler.NetworkScanHandler
|
||||
Verification handler.VerificationHandler
|
||||
Export handler.ExportHandler
|
||||
Digest handler.DigestHandler
|
||||
}
|
||||
|
||||
// RegisterHandlers sets up all API routes with their handlers.
|
||||
@@ -99,6 +101,10 @@ func (r *Router) RegisterHandlers(reg HandlerRegistry) {
|
||||
r.Register("POST /api/v1/certificates/{id}/deploy", http.HandlerFunc(reg.Certificates.TriggerDeployment))
|
||||
r.Register("POST /api/v1/certificates/{id}/revoke", http.HandlerFunc(reg.Certificates.RevokeCertificate))
|
||||
|
||||
// Export endpoints: /api/v1/certificates/{id}/export/{format}
|
||||
r.Register("GET /api/v1/certificates/{id}/export/pem", http.HandlerFunc(reg.Export.ExportPEM))
|
||||
r.Register("POST /api/v1/certificates/{id}/export/pkcs12", http.HandlerFunc(reg.Export.ExportPKCS12))
|
||||
|
||||
// CRL endpoints: /api/v1/crl (JSON) and /api/v1/crl/{issuer_id} (DER)
|
||||
r.Register("GET /api/v1/crl", http.HandlerFunc(reg.Certificates.GetCRL))
|
||||
r.Register("GET /api/v1/crl/{issuer_id}", http.HandlerFunc(reg.Certificates.GetDERCRL))
|
||||
@@ -120,6 +126,7 @@ func (r *Router) RegisterHandlers(reg HandlerRegistry) {
|
||||
r.Register("GET /api/v1/targets/{id}", http.HandlerFunc(reg.Targets.GetTarget))
|
||||
r.Register("PUT /api/v1/targets/{id}", http.HandlerFunc(reg.Targets.UpdateTarget))
|
||||
r.Register("DELETE /api/v1/targets/{id}", http.HandlerFunc(reg.Targets.DeleteTarget))
|
||||
r.Register("POST /api/v1/targets/{id}/test", http.HandlerFunc(reg.Targets.TestTargetConnection))
|
||||
|
||||
// Agents routes: /api/v1/agents
|
||||
r.Register("GET /api/v1/agents", http.HandlerFunc(reg.Agents.ListAgents))
|
||||
@@ -215,6 +222,10 @@ func (r *Router) RegisterHandlers(reg HandlerRegistry) {
|
||||
// Verification routes: /api/v1/jobs/{id}/verify and /api/v1/jobs/{id}/verification
|
||||
r.Register("POST /api/v1/jobs/{id}/verify", http.HandlerFunc(reg.Verification.VerifyDeployment))
|
||||
r.Register("GET /api/v1/jobs/{id}/verification", http.HandlerFunc(reg.Verification.GetVerificationStatus))
|
||||
|
||||
// Digest routes: /api/v1/digest
|
||||
r.Register("GET /api/v1/digest/preview", http.HandlerFunc(reg.Digest.PreviewDigest))
|
||||
r.Register("POST /api/v1/digest/send", http.HandlerFunc(reg.Digest.SendDigest))
|
||||
}
|
||||
|
||||
// RegisterESTHandlers sets up EST (RFC 7030) routes under /.well-known/est/.
|
||||
|
||||
+247
-2
@@ -24,6 +24,20 @@ type Config struct {
|
||||
NetworkScan NetworkScanConfig
|
||||
EST ESTConfig
|
||||
Verification VerificationConfig
|
||||
ACME ACMEConfig
|
||||
Vault VaultConfig
|
||||
DigiCert DigiCertConfig
|
||||
Sectigo SectigoConfig
|
||||
GoogleCAS GoogleCASConfig
|
||||
Digest DigestConfig
|
||||
Encryption EncryptionConfig
|
||||
}
|
||||
|
||||
// EncryptionConfig contains configuration for encrypting sensitive data at rest.
|
||||
type EncryptionConfig struct {
|
||||
// ConfigEncryptionKey is the passphrase used to derive AES-256-GCM keys for encrypting
|
||||
// issuer config secrets in the database. If empty, configs are stored in plaintext (development only).
|
||||
ConfigEncryptionKey string
|
||||
}
|
||||
|
||||
// NotifierConfig contains configuration for notification connectors.
|
||||
@@ -64,6 +78,34 @@ type NotifierConfig struct {
|
||||
// OpsGeniePriority sets the default priority for OpsGenie alerts.
|
||||
// Valid values: "P1", "P2", "P3", "P4", "P5". Default: "P3".
|
||||
OpsGeniePriority string
|
||||
|
||||
// SMTPHost is the SMTP server hostname for sending email notifications.
|
||||
// Example: "smtp.gmail.com", "smtp.sendgrid.net". Required for email notifications.
|
||||
// Setting: CERTCTL_SMTP_HOST environment variable.
|
||||
SMTPHost string
|
||||
|
||||
// SMTPPort is the SMTP server port. Default: 587 (STARTTLS).
|
||||
// Common values: 25 (plain), 465 (implicit TLS), 587 (STARTTLS).
|
||||
// Setting: CERTCTL_SMTP_PORT environment variable.
|
||||
SMTPPort int
|
||||
|
||||
// SMTPUsername is the SMTP authentication username.
|
||||
// Setting: CERTCTL_SMTP_USERNAME environment variable.
|
||||
SMTPUsername string
|
||||
|
||||
// SMTPPassword is the SMTP authentication password or app-specific password.
|
||||
// Setting: CERTCTL_SMTP_PASSWORD environment variable.
|
||||
SMTPPassword string
|
||||
|
||||
// SMTPFromAddress is the sender email address for outbound notifications.
|
||||
// Example: "certctl@example.com", "noreply@company.com".
|
||||
// Setting: CERTCTL_SMTP_FROM_ADDRESS environment variable.
|
||||
SMTPFromAddress string
|
||||
|
||||
// SMTPUseTLS enables TLS for the SMTP connection.
|
||||
// Default: true. Set to false for plain SMTP (not recommended).
|
||||
// Setting: CERTCTL_SMTP_USE_TLS environment variable.
|
||||
SMTPUseTLS bool
|
||||
}
|
||||
|
||||
// KeygenConfig controls where private keys are generated.
|
||||
@@ -111,6 +153,140 @@ type StepCAConfig struct {
|
||||
ProvisionerPassword string
|
||||
}
|
||||
|
||||
// VaultConfig contains HashiCorp Vault PKI issuer connector configuration.
|
||||
type VaultConfig struct {
|
||||
// Addr is the Vault server address (e.g., "https://vault.example.com:8200").
|
||||
// Required for Vault PKI integration.
|
||||
// Setting: CERTCTL_VAULT_ADDR environment variable.
|
||||
Addr string
|
||||
|
||||
// Token is the Vault token for authentication.
|
||||
// Required for Vault PKI integration.
|
||||
// Setting: CERTCTL_VAULT_TOKEN environment variable.
|
||||
Token string
|
||||
|
||||
// Mount is the PKI secrets engine mount path.
|
||||
// Default: "pki".
|
||||
// Setting: CERTCTL_VAULT_MOUNT environment variable.
|
||||
Mount string
|
||||
|
||||
// Role is the PKI role name used for signing certificates.
|
||||
// Required for Vault PKI integration.
|
||||
// Setting: CERTCTL_VAULT_ROLE environment variable.
|
||||
Role string
|
||||
|
||||
// TTL is the requested certificate time-to-live.
|
||||
// Default: "8760h" (1 year).
|
||||
// Setting: CERTCTL_VAULT_TTL environment variable.
|
||||
TTL string
|
||||
}
|
||||
|
||||
// DigiCertConfig contains DigiCert CertCentral issuer connector configuration.
|
||||
type DigiCertConfig struct {
|
||||
// APIKey is the CertCentral API key for authentication.
|
||||
// Required for DigiCert integration.
|
||||
// Setting: CERTCTL_DIGICERT_API_KEY environment variable.
|
||||
APIKey string
|
||||
|
||||
// OrgID is the DigiCert organization ID for certificate orders.
|
||||
// Required for DigiCert integration.
|
||||
// Setting: CERTCTL_DIGICERT_ORG_ID environment variable.
|
||||
OrgID string
|
||||
|
||||
// ProductType is the DigiCert product type for certificate orders.
|
||||
// Default: "ssl_basic". Common values: "ssl_basic", "ssl_wildcard", "ssl_ev_basic".
|
||||
// Setting: CERTCTL_DIGICERT_PRODUCT_TYPE environment variable.
|
||||
ProductType string
|
||||
|
||||
// BaseURL is the DigiCert CertCentral API base URL.
|
||||
// Default: "https://www.digicert.com/services/v2".
|
||||
// Setting: CERTCTL_DIGICERT_BASE_URL environment variable.
|
||||
BaseURL string
|
||||
}
|
||||
|
||||
// SectigoConfig contains Sectigo Certificate Manager issuer connector configuration.
|
||||
type SectigoConfig struct {
|
||||
// CustomerURI is the Sectigo customer URI (organization identifier).
|
||||
// Required for Sectigo integration.
|
||||
// Setting: CERTCTL_SECTIGO_CUSTOMER_URI environment variable.
|
||||
CustomerURI string
|
||||
|
||||
// Login is the Sectigo API account login.
|
||||
// Required for Sectigo integration.
|
||||
// Setting: CERTCTL_SECTIGO_LOGIN environment variable.
|
||||
Login string
|
||||
|
||||
// Password is the Sectigo API account password or API key.
|
||||
// Required for Sectigo integration.
|
||||
// Setting: CERTCTL_SECTIGO_PASSWORD environment variable.
|
||||
Password string
|
||||
|
||||
// OrgID is the Sectigo organization ID for certificate enrollments.
|
||||
// Required for Sectigo integration.
|
||||
// Setting: CERTCTL_SECTIGO_ORG_ID environment variable.
|
||||
OrgID int
|
||||
|
||||
// CertType is the Sectigo certificate type ID (from GET /ssl/v1/types).
|
||||
// Required for enrollment. Set via CERTCTL_SECTIGO_CERT_TYPE environment variable.
|
||||
CertType int
|
||||
|
||||
// Term is the certificate validity in days (e.g., 365, 730).
|
||||
// Default: 365.
|
||||
// Setting: CERTCTL_SECTIGO_TERM environment variable.
|
||||
Term int
|
||||
|
||||
// BaseURL is the Sectigo SCM API base URL.
|
||||
// Default: "https://cert-manager.com/api".
|
||||
// Setting: CERTCTL_SECTIGO_BASE_URL environment variable.
|
||||
BaseURL string
|
||||
}
|
||||
|
||||
// GoogleCASConfig contains Google Cloud Certificate Authority Service configuration.
|
||||
type GoogleCASConfig struct {
|
||||
// Project is the GCP project ID.
|
||||
// Required for Google CAS integration.
|
||||
// Setting: CERTCTL_GOOGLE_CAS_PROJECT environment variable.
|
||||
Project string
|
||||
|
||||
// Location is the GCP region (e.g., "us-central1").
|
||||
// Required for Google CAS integration.
|
||||
// Setting: CERTCTL_GOOGLE_CAS_LOCATION environment variable.
|
||||
Location string
|
||||
|
||||
// CAPool is the Certificate Authority pool name.
|
||||
// Required for Google CAS integration.
|
||||
// Setting: CERTCTL_GOOGLE_CAS_CA_POOL environment variable.
|
||||
CAPool string
|
||||
|
||||
// Credentials is the path to the service account JSON credentials file.
|
||||
// Required for Google CAS integration.
|
||||
// Setting: CERTCTL_GOOGLE_CAS_CREDENTIALS environment variable.
|
||||
Credentials string
|
||||
|
||||
// TTL is the default certificate time-to-live.
|
||||
// Default: "8760h" (1 year).
|
||||
// Setting: CERTCTL_GOOGLE_CAS_TTL environment variable.
|
||||
TTL string
|
||||
}
|
||||
|
||||
// DigestConfig controls the scheduled certificate digest email feature.
|
||||
type DigestConfig struct {
|
||||
// Enabled controls whether periodic digest emails are generated and sent.
|
||||
// Default: false. When enabled, requires SMTP to be configured.
|
||||
// Setting: CERTCTL_DIGEST_ENABLED environment variable.
|
||||
Enabled bool
|
||||
|
||||
// Interval is how often digest emails are generated and sent.
|
||||
// Default: 24 hours. Minimum: 1 hour.
|
||||
// Setting: CERTCTL_DIGEST_INTERVAL environment variable.
|
||||
Interval time.Duration
|
||||
|
||||
// Recipients is a comma-separated list of email addresses to receive digest emails.
|
||||
// If empty, digests are sent to all certificate owners.
|
||||
// Setting: CERTCTL_DIGEST_RECIPIENTS environment variable.
|
||||
Recipients []string
|
||||
}
|
||||
|
||||
// ACMEConfig contains ACME issuer connector configuration.
|
||||
type ACMEConfig struct {
|
||||
// DirectoryURL is the ACME directory URL for certificate issuance.
|
||||
@@ -130,13 +306,17 @@ type ACMEConfig struct {
|
||||
|
||||
// DNSPresentScript is the path to a shell script that creates DNS TXT records.
|
||||
// Required for dns-01 and dns-persist-01 challenge types.
|
||||
// Script receives: DOMAIN_NAME, VALIDATION_TOKEN, RECORD_NAME as env vars.
|
||||
// Script receives these environment variables:
|
||||
// - CERTCTL_DNS_DOMAIN: domain being validated (e.g., "example.com")
|
||||
// - CERTCTL_DNS_FQDN: full record name (e.g., "_acme-challenge.example.com" or "_validation-persist.example.com")
|
||||
// - CERTCTL_DNS_VALUE: TXT record value (key authorization digest for dns-01, or issuer domain info for dns-persist-01)
|
||||
// - CERTCTL_DNS_TOKEN: ACME challenge token
|
||||
// Example: /opt/dns-scripts/add-record.sh
|
||||
DNSPresentScript string
|
||||
|
||||
// DNSCleanUpScript is the path to a shell script that removes DNS TXT records.
|
||||
// Used only for dns-01 challenges to clean up temporary validation records.
|
||||
// Script receives: DOMAIN_NAME, RECORD_NAME as env vars.
|
||||
// Script receives the same environment variables as DNSPresentScript.
|
||||
// Leave empty if cleanup is not needed (e.g., dns-persist-01).
|
||||
DNSCleanUpScript string
|
||||
|
||||
@@ -144,6 +324,18 @@ type ACMEConfig struct {
|
||||
// Example: "letsencrypt.org" or "zerossl.com". Only used if ChallengeType is "dns-persist-01".
|
||||
// The record value becomes: "<issuer_domain>; accounturi=<acme_account_uri>"
|
||||
DNSPersistIssuerDomain string
|
||||
|
||||
// ARIEnabled enables ACME Renewal Information (RFC 9702) support.
|
||||
// When enabled, the renewal scheduler queries the CA for suggested renewal windows
|
||||
// instead of relying solely on static expiration thresholds.
|
||||
// Default: false. Requires a CA that supports ARI (e.g., Let's Encrypt).
|
||||
// Setting: CERTCTL_ACME_ARI_ENABLED environment variable.
|
||||
ARIEnabled bool
|
||||
|
||||
// Insecure skips TLS certificate verification when connecting to the ACME directory.
|
||||
// Only use for testing with self-signed ACME servers like Pebble. Never in production.
|
||||
// Setting: CERTCTL_ACME_INSECURE environment variable.
|
||||
Insecure bool
|
||||
}
|
||||
|
||||
// OpenSSLConfig contains OpenSSL/Custom CA issuer connector configuration.
|
||||
@@ -349,6 +541,12 @@ func Load() (*Config, error) {
|
||||
PagerDutySeverity: getEnv("CERTCTL_PAGERDUTY_SEVERITY", "warning"),
|
||||
OpsGenieAPIKey: getEnv("CERTCTL_OPSGENIE_API_KEY", ""),
|
||||
OpsGeniePriority: getEnv("CERTCTL_OPSGENIE_PRIORITY", "P3"),
|
||||
SMTPHost: getEnv("CERTCTL_SMTP_HOST", ""),
|
||||
SMTPPort: getEnvInt("CERTCTL_SMTP_PORT", 587),
|
||||
SMTPUsername: getEnv("CERTCTL_SMTP_USERNAME", ""),
|
||||
SMTPPassword: getEnv("CERTCTL_SMTP_PASSWORD", ""),
|
||||
SMTPFromAddress: getEnv("CERTCTL_SMTP_FROM_ADDRESS", ""),
|
||||
SMTPUseTLS: getEnvBool("CERTCTL_SMTP_USE_TLS", true),
|
||||
},
|
||||
NetworkScan: NetworkScanConfig{
|
||||
Enabled: getEnvBool("CERTCTL_NETWORK_SCAN_ENABLED", false),
|
||||
@@ -364,6 +562,53 @@ func Load() (*Config, error) {
|
||||
Timeout: getEnvDuration("CERTCTL_VERIFY_TIMEOUT", 10*time.Second),
|
||||
Delay: getEnvDuration("CERTCTL_VERIFY_DELAY", 2*time.Second),
|
||||
},
|
||||
Vault: VaultConfig{
|
||||
Addr: getEnv("CERTCTL_VAULT_ADDR", ""),
|
||||
Token: getEnv("CERTCTL_VAULT_TOKEN", ""),
|
||||
Mount: getEnv("CERTCTL_VAULT_MOUNT", "pki"),
|
||||
Role: getEnv("CERTCTL_VAULT_ROLE", ""),
|
||||
TTL: getEnv("CERTCTL_VAULT_TTL", "8760h"),
|
||||
},
|
||||
DigiCert: DigiCertConfig{
|
||||
APIKey: getEnv("CERTCTL_DIGICERT_API_KEY", ""),
|
||||
OrgID: getEnv("CERTCTL_DIGICERT_ORG_ID", ""),
|
||||
ProductType: getEnv("CERTCTL_DIGICERT_PRODUCT_TYPE", "ssl_basic"),
|
||||
BaseURL: getEnv("CERTCTL_DIGICERT_BASE_URL", "https://www.digicert.com/services/v2"),
|
||||
},
|
||||
Sectigo: SectigoConfig{
|
||||
CustomerURI: getEnv("CERTCTL_SECTIGO_CUSTOMER_URI", ""),
|
||||
Login: getEnv("CERTCTL_SECTIGO_LOGIN", ""),
|
||||
Password: getEnv("CERTCTL_SECTIGO_PASSWORD", ""),
|
||||
OrgID: getEnvInt("CERTCTL_SECTIGO_ORG_ID", 0),
|
||||
CertType: getEnvInt("CERTCTL_SECTIGO_CERT_TYPE", 0),
|
||||
Term: getEnvInt("CERTCTL_SECTIGO_TERM", 365),
|
||||
BaseURL: getEnv("CERTCTL_SECTIGO_BASE_URL", "https://cert-manager.com/api"),
|
||||
},
|
||||
GoogleCAS: GoogleCASConfig{
|
||||
Project: getEnv("CERTCTL_GOOGLE_CAS_PROJECT", ""),
|
||||
Location: getEnv("CERTCTL_GOOGLE_CAS_LOCATION", ""),
|
||||
CAPool: getEnv("CERTCTL_GOOGLE_CAS_CA_POOL", ""),
|
||||
Credentials: getEnv("CERTCTL_GOOGLE_CAS_CREDENTIALS", ""),
|
||||
TTL: getEnv("CERTCTL_GOOGLE_CAS_TTL", "8760h"),
|
||||
},
|
||||
ACME: ACMEConfig{
|
||||
DirectoryURL: getEnv("CERTCTL_ACME_DIRECTORY_URL", ""),
|
||||
Email: getEnv("CERTCTL_ACME_EMAIL", ""),
|
||||
ChallengeType: getEnv("CERTCTL_ACME_CHALLENGE_TYPE", "http-01"),
|
||||
DNSPresentScript: getEnv("CERTCTL_ACME_DNS_PRESENT_SCRIPT", ""),
|
||||
DNSCleanUpScript: getEnv("CERTCTL_ACME_DNS_CLEANUP_SCRIPT", ""),
|
||||
DNSPersistIssuerDomain: getEnv("CERTCTL_ACME_DNS_PERSIST_ISSUER_DOMAIN", ""),
|
||||
ARIEnabled: getEnvBool("CERTCTL_ACME_ARI_ENABLED", false),
|
||||
Insecure: getEnvBool("CERTCTL_ACME_INSECURE", false),
|
||||
},
|
||||
Digest: DigestConfig{
|
||||
Enabled: getEnvBool("CERTCTL_DIGEST_ENABLED", false),
|
||||
Interval: getEnvDuration("CERTCTL_DIGEST_INTERVAL", 24*time.Hour),
|
||||
Recipients: getEnvList("CERTCTL_DIGEST_RECIPIENTS", nil),
|
||||
},
|
||||
Encryption: EncryptionConfig{
|
||||
ConfigEncryptionKey: getEnv("CERTCTL_CONFIG_ENCRYPTION_KEY", ""),
|
||||
},
|
||||
}
|
||||
|
||||
if err := cfg.Validate(); err != nil {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
@@ -54,6 +55,14 @@ type Config struct {
|
||||
// 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"`
|
||||
|
||||
// ARIEnabled enables ACME Renewal Information (RFC 9702) support per CERTCTL_ACME_ARI_ENABLED.
|
||||
// When enabled, the connector queries the CA's ARI endpoint to get CA-directed renewal timing.
|
||||
ARIEnabled bool `json:"ari_enabled,omitempty"`
|
||||
|
||||
// Insecure skips TLS certificate verification when connecting to the ACME directory.
|
||||
// Only use for testing with self-signed ACME servers like Pebble.
|
||||
Insecure bool `json:"insecure,omitempty"`
|
||||
}
|
||||
|
||||
// Connector implements the issuer.Connector interface for ACME-compatible CAs
|
||||
@@ -110,6 +119,18 @@ func New(config *Config, logger *slog.Logger) *Connector {
|
||||
return c
|
||||
}
|
||||
|
||||
// httpClient returns an HTTP client configured for the ACME connector.
|
||||
// When Insecure is true (e.g., for Pebble test servers), TLS verification is skipped.
|
||||
func (c *Connector) httpClient() *http.Client {
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
if c.config != nil && c.config.Insecure {
|
||||
client.Transport = &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // Intentional for test ACME servers (Pebble)
|
||||
}
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
// ValidateConfig checks that the ACME directory URL is reachable and valid.
|
||||
func (c *Connector) ValidateConfig(ctx context.Context, rawConfig json.RawMessage) error {
|
||||
var cfg Config
|
||||
@@ -125,10 +146,16 @@ func (c *Connector) ValidateConfig(ctx context.Context, rawConfig json.RawMessag
|
||||
return fmt.Errorf("ACME email is required")
|
||||
}
|
||||
|
||||
c.logger.Info("validating ACME configuration", "directory_url", cfg.DirectoryURL)
|
||||
c.logger.Info("validating ACME configuration", "directory_url", cfg.DirectoryURL, "insecure", cfg.Insecure)
|
||||
|
||||
// Apply config so httpClient() can use it for the directory probe.
|
||||
// This persists across the function — if validation fails early, the config
|
||||
// will still be set, but that's fine since a failed ValidateConfig means
|
||||
// the connector won't be used.
|
||||
c.config = &cfg
|
||||
|
||||
// Verify that the directory URL is reachable
|
||||
httpClient := &http.Client{Timeout: 10 * time.Second}
|
||||
httpClient := c.httpClient()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, cfg.DirectoryURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
@@ -199,6 +226,7 @@ func (c *Connector) ensureClient(ctx context.Context) error {
|
||||
c.client = &acme.Client{
|
||||
Key: key,
|
||||
DirectoryURL: c.config.DirectoryURL,
|
||||
HTTPClient: c.httpClient(),
|
||||
}
|
||||
|
||||
// Register or retrieve the ACME account
|
||||
@@ -334,6 +362,12 @@ func (c *Connector) IssueCertificate(ctx context.Context, request issuer.Issuanc
|
||||
}
|
||||
c.logger.Info("ACME order created", "order_url", order.URI, "status", order.Status)
|
||||
|
||||
// Save FinalizeURL and URI before WaitOrder — WaitOrder returns a new Order
|
||||
// object that may have empty FinalizeURL and URI fields (Go's crypto/acme
|
||||
// WaitOrder doesn't populate Order.URI on the returned struct).
|
||||
finalizeURL := order.FinalizeURL
|
||||
orderURI := order.URI
|
||||
|
||||
// Step 2: Solve authorizations (HTTP-01 challenges)
|
||||
if order.Status == acme.StatusPending {
|
||||
if err := c.solveAuthorizations(ctx, order.AuthzURLs); err != nil {
|
||||
@@ -341,10 +375,18 @@ func (c *Connector) IssueCertificate(ctx context.Context, request issuer.Issuanc
|
||||
}
|
||||
|
||||
// Wait for the order to be ready
|
||||
order, err = c.client.WaitOrder(ctx, order.URI)
|
||||
order, err = c.client.WaitOrder(ctx, orderURI)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("order failed after challenge: %w", err)
|
||||
}
|
||||
// Update finalizeURL from the waited order if it has one
|
||||
if order.FinalizeURL != "" {
|
||||
finalizeURL = order.FinalizeURL
|
||||
}
|
||||
// Preserve orderURI — WaitOrder doesn't populate Order.URI
|
||||
if order.URI != "" {
|
||||
orderURI = order.URI
|
||||
}
|
||||
}
|
||||
|
||||
if order.Status != acme.StatusReady {
|
||||
@@ -357,9 +399,39 @@ func (c *Connector) IssueCertificate(ctx context.Context, request issuer.Issuanc
|
||||
return nil, fmt.Errorf("failed to parse CSR: %w", err)
|
||||
}
|
||||
|
||||
derChain, _, err := c.client.CreateOrderCert(ctx, order.FinalizeURL, csrDER, true)
|
||||
if finalizeURL == "" {
|
||||
return nil, fmt.Errorf("ACME order has no finalize URL (order URI: %s, status: %s)", order.URI, order.Status)
|
||||
}
|
||||
|
||||
// Step 3b: Finalize the order and fetch the certificate.
|
||||
// CreateOrderCert POSTs the CSR to the finalize URL and attempts to retrieve
|
||||
// the certificate. Some ACME servers (notably Pebble) return the order object
|
||||
// per RFC 8555 rather than redirecting to the cert, which can cause
|
||||
// CreateOrderCert's internal cert URL resolution to fail. In that case, we
|
||||
// fall back to WaitOrder (to get the CertURL) + FetchCert.
|
||||
derChain, _, err := c.client.CreateOrderCert(ctx, finalizeURL, csrDER, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to finalize order: %w", err)
|
||||
c.logger.Warn("CreateOrderCert failed, attempting manual certificate fetch",
|
||||
"error", err, "order_uri", orderURI)
|
||||
|
||||
// The finalize POST likely succeeded (the CA issued the cert) but cert
|
||||
// retrieval failed. WaitOrder returns the order in "valid" state with
|
||||
// CertURL populated.
|
||||
validOrder, waitErr := c.client.WaitOrder(ctx, orderURI)
|
||||
if waitErr != nil {
|
||||
return nil, fmt.Errorf("failed to finalize order: %w (wait fallback: %v)", err, waitErr)
|
||||
}
|
||||
|
||||
if validOrder.CertURL == "" {
|
||||
return nil, fmt.Errorf("order finalized but no certificate URL returned (original error: %w)", err)
|
||||
}
|
||||
|
||||
c.logger.Info("fetching certificate via fallback", "cert_url", validOrder.CertURL)
|
||||
fetchedChain, fetchErr := c.client.FetchCert(ctx, validOrder.CertURL, true)
|
||||
if fetchErr != nil {
|
||||
return nil, fmt.Errorf("failed to fetch certificate: %w (original finalize error: %v)", fetchErr, err)
|
||||
}
|
||||
derChain = fetchedChain
|
||||
}
|
||||
|
||||
if len(derChain) == 0 {
|
||||
@@ -383,7 +455,7 @@ func (c *Connector) IssueCertificate(ctx context.Context, request issuer.Issuanc
|
||||
Serial: serial,
|
||||
NotBefore: notBefore,
|
||||
NotAfter: notAfter,
|
||||
OrderID: order.URI,
|
||||
OrderID: orderURI,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/connector/issuer"
|
||||
)
|
||||
|
||||
// GetRenewalInfo retrieves ACME Renewal Information (ARI) per RFC 9702 for a certificate.
|
||||
// certPEM is the PEM-encoded certificate. Returns nil, nil if the CA does not support ARI.
|
||||
func (c *Connector) GetRenewalInfo(ctx context.Context, certPEM string) (*issuer.RenewalInfoResult, error) {
|
||||
if !c.config.ARIEnabled {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if err := c.ensureClient(ctx); err != nil {
|
||||
return nil, fmt.Errorf("ACME client init: %w", err)
|
||||
}
|
||||
|
||||
// Parse the certificate to compute the ARI certificate ID
|
||||
certID, err := computeARICertID(certPEM)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to compute ARI cert ID: %w", err)
|
||||
}
|
||||
|
||||
c.logger.Debug("retrieving ARI for certificate",
|
||||
"cert_id", certID)
|
||||
|
||||
// Fetch the ACME directory to find the renewalInfo endpoint
|
||||
renewalInfoURL, err := c.getARIEndpoint(ctx, certID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to construct ARI endpoint: %w", err)
|
||||
}
|
||||
|
||||
c.logger.Debug("querying ARI endpoint", "url", renewalInfoURL)
|
||||
|
||||
// Make GET request to the ARI endpoint
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, renewalInfoURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create ARI request: %w", err)
|
||||
}
|
||||
|
||||
httpClient := &http.Client{Timeout: 15 * time.Second}
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ARI request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read ARI response: %w", err)
|
||||
}
|
||||
|
||||
// 404 means the CA doesn't support ARI or the cert doesn't exist
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
c.logger.Debug("ARI not supported by CA or cert not found")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Other non-2xx errors
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("ARI endpoint returned status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Parse the ARI response
|
||||
var ariResp struct {
|
||||
SuggestedWindow struct {
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
} `json:"suggestedWindow"`
|
||||
RetryAfter time.Time `json:"retryAfter,omitempty"`
|
||||
ExplanationURL string `json:"explanationURL,omitempty"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &ariResp); err != nil {
|
||||
return nil, fmt.Errorf("parse ARI response: %w", err)
|
||||
}
|
||||
|
||||
if ariResp.SuggestedWindow.Start.IsZero() || ariResp.SuggestedWindow.End.IsZero() {
|
||||
return nil, fmt.Errorf("invalid ARI response: missing or empty suggestedWindow")
|
||||
}
|
||||
|
||||
c.logger.Info("retrieved ARI",
|
||||
"window_start", ariResp.SuggestedWindow.Start,
|
||||
"window_end", ariResp.SuggestedWindow.End)
|
||||
|
||||
return &issuer.RenewalInfoResult{
|
||||
SuggestedWindowStart: ariResp.SuggestedWindow.Start,
|
||||
SuggestedWindowEnd: ariResp.SuggestedWindow.End,
|
||||
RetryAfter: ariResp.RetryAfter,
|
||||
ExplanationURL: ariResp.ExplanationURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// computeARICertID computes the ARI certificate ID as defined in RFC 9702.
|
||||
// The cert ID is base64url(SHA256(DER encoding of the certificate)).
|
||||
func computeARICertID(certPEM string) (string, error) {
|
||||
block, _ := pem.Decode([]byte(certPEM))
|
||||
if block == nil {
|
||||
return "", fmt.Errorf("invalid PEM: no certificate block found")
|
||||
}
|
||||
|
||||
hash := sha256.Sum256(block.Bytes)
|
||||
certID := base64.RawURLEncoding.EncodeToString(hash[:])
|
||||
return certID, nil
|
||||
}
|
||||
|
||||
// getARIEndpoint constructs the ARI endpoint URL from the ACME directory.
|
||||
// It fetches the directory JSON and extracts the "renewalInfo" field if available.
|
||||
// Falls back to a standard URL pattern if the directory doesn't advertise renewalInfo.
|
||||
func (c *Connector) getARIEndpoint(ctx context.Context, certID string) (string, error) {
|
||||
// Try to fetch and parse the directory
|
||||
httpClient := &http.Client{Timeout: 15 * time.Second}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.config.DirectoryURL, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create directory request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
// If we can't fetch the directory, try the standard Let's Encrypt pattern
|
||||
return constructARIURLFallback(c.config.DirectoryURL, certID), nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return constructARIURLFallback(c.config.DirectoryURL, certID), nil
|
||||
}
|
||||
|
||||
var dir struct {
|
||||
RenewalInfo string `json:"renewalInfo,omitempty"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &dir); err != nil {
|
||||
// Malformed directory; use fallback
|
||||
return constructARIURLFallback(c.config.DirectoryURL, certID), nil
|
||||
}
|
||||
|
||||
if dir.RenewalInfo != "" {
|
||||
// Directory advertises renewalInfo endpoint
|
||||
return dir.RenewalInfo + "/" + certID, nil
|
||||
}
|
||||
|
||||
// No renewalInfo in directory; use standard fallback
|
||||
return constructARIURLFallback(c.config.DirectoryURL, certID), nil
|
||||
}
|
||||
|
||||
// constructARIURLFallback builds an ARI endpoint URL using a standard pattern.
|
||||
// It replaces "/directory" with "/renewalInfo" in the URL.
|
||||
func constructARIURLFallback(directoryURL, certID string) string {
|
||||
// Replace "/directory" with "/renewalInfo/{certID}"
|
||||
// For Let's Encrypt: https://acme-v02.api.letsencrypt.org/directory
|
||||
// becomes: https://acme-v02.api.letsencrypt.org/renewalInfo/{certID}
|
||||
baseURL := strings.TrimSuffix(directoryURL, "/directory")
|
||||
return baseURL + "/renewalInfo/" + certID
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestComputeARICertID_InvalidPEM_Input tests the ARI certificate ID computation with invalid PEM.
|
||||
func TestComputeARICertID_InvalidPEM_Input(t *testing.T) {
|
||||
// Test with invalid PEM data
|
||||
_, err := computeARICertID("not a valid pem")
|
||||
if err == nil {
|
||||
t.Error("expected error for invalid PEM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConstructARIURLFallback_LetsEncrypt(t *testing.T) {
|
||||
directoryURL := "https://acme-v02.api.letsencrypt.org/directory"
|
||||
certID := "abc123"
|
||||
|
||||
url := constructARIURLFallback(directoryURL, certID)
|
||||
|
||||
expected := "https://acme-v02.api.letsencrypt.org/renewalInfo/abc123"
|
||||
if url != expected {
|
||||
t.Errorf("constructARIURLFallback: expected %s, got %s", expected, url)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConstructARIURLFallback_NoDirectory(t *testing.T) {
|
||||
directoryURL := "https://example.com/acme"
|
||||
certID := "xyz789"
|
||||
|
||||
url := constructARIURLFallback(directoryURL, certID)
|
||||
|
||||
expected := "https://example.com/acme/renewalInfo/xyz789"
|
||||
if url != expected {
|
||||
t.Errorf("constructARIURLFallback: expected %s, got %s", expected, url)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetRenewalInfo_Disabled tests that ARI returns nil when disabled.
|
||||
func TestGetRenewalInfo_Disabled(t *testing.T) {
|
||||
config := &Config{
|
||||
DirectoryURL: "https://acme.invalid/directory",
|
||||
Email: "test@example.com",
|
||||
ChallengeType: "http-01",
|
||||
ARIEnabled: false,
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
connector := New(config, logger)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
result, err := connector.GetRenewalInfo(ctx, "any-cert-pem")
|
||||
if err != nil {
|
||||
t.Fatalf("GetRenewalInfo failed: %v", err)
|
||||
}
|
||||
|
||||
if result != nil {
|
||||
t.Error("GetRenewalInfo should return nil when ARI is disabled")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetRenewalInfo_NotFound tests handling of 404 response (CA doesn't support ARI).
|
||||
func TestGetRenewalInfo_NotFound(t *testing.T) {
|
||||
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Mock directory endpoint
|
||||
if r.URL.Path == "/directory" && r.Method == http.MethodGet {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"newOrder": "/acme/new-order",
|
||||
"newAccount": "/acme/new-account",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// All other endpoints return 404
|
||||
http.Error(w, "not found", http.StatusNotFound)
|
||||
}))
|
||||
defer mockServer.Close()
|
||||
|
||||
config := &Config{
|
||||
DirectoryURL: mockServer.URL + "/directory",
|
||||
Email: "test@example.com",
|
||||
ChallengeType: "http-01",
|
||||
ARIEnabled: true,
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
connector := New(config, logger)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// GetRenewalInfo will fail when parsing the cert PEM, which is expected
|
||||
result, err := connector.GetRenewalInfo(ctx, "invalid-cert-pem")
|
||||
if err == nil {
|
||||
// If it doesn't fail on cert parsing, that's also okay
|
||||
// The 404 handling happens after cert ID computation
|
||||
if result != nil {
|
||||
t.Error("GetRenewalInfo should return nil for 404 response")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetRenewalInfo_ServerError tests handling of server errors.
|
||||
func TestGetRenewalInfo_ServerError(t *testing.T) {
|
||||
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Mock directory endpoint
|
||||
if r.URL.Path == "/directory" && r.Method == http.MethodGet {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"newOrder": "/acme/new-order",
|
||||
"newAccount": "/acme/new-account",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// All other endpoints return 500
|
||||
http.Error(w, "internal server error", http.StatusInternalServerError)
|
||||
}))
|
||||
defer mockServer.Close()
|
||||
|
||||
config := &Config{
|
||||
DirectoryURL: mockServer.URL + "/directory",
|
||||
Email: "test@example.com",
|
||||
ChallengeType: "http-01",
|
||||
ARIEnabled: true,
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
connector := New(config, logger)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := connector.GetRenewalInfo(ctx, "invalid-cert-pem")
|
||||
// Error is expected because cert parsing fails first
|
||||
if err == nil {
|
||||
// If we get here, the server error handling should catch it
|
||||
t.Error("expected error for invalid cert or 500 response")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetRenewalInfo_InvalidPEM tests handling of invalid PEM input.
|
||||
func TestGetRenewalInfo_InvalidPEM(t *testing.T) {
|
||||
config := &Config{
|
||||
DirectoryURL: "https://acme.invalid/directory",
|
||||
Email: "test@example.com",
|
||||
ChallengeType: "http-01",
|
||||
ARIEnabled: true,
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
connector := New(config, logger)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := connector.GetRenewalInfo(ctx, "invalid pem data")
|
||||
if err == nil {
|
||||
t.Error("GetRenewalInfo should return error for invalid PEM")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetRenewalInfo_MalformedResponse tests handling of malformed JSON response.
|
||||
func TestGetRenewalInfo_MalformedResponse(t *testing.T) {
|
||||
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Mock directory endpoint
|
||||
if r.URL.Path == "/directory" && r.Method == http.MethodGet {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"renewalInfo": "/acme/renewalInfo",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Mock renewalInfo with malformed JSON
|
||||
if r.URL.Path != "/directory" && r.Method == http.MethodGet {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"suggestedWindow": invalid json}`))
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, "not found", http.StatusNotFound)
|
||||
}))
|
||||
defer mockServer.Close()
|
||||
|
||||
config := &Config{
|
||||
DirectoryURL: mockServer.URL + "/directory",
|
||||
Email: "test@example.com",
|
||||
ChallengeType: "http-01",
|
||||
ARIEnabled: true,
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
connector := New(config, logger)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := connector.GetRenewalInfo(ctx, "invalid-cert-pem")
|
||||
// Error is expected
|
||||
if err == nil {
|
||||
t.Error("GetRenewalInfo should return error for malformed response or invalid cert")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetRenewalInfo_MissingWindow tests handling of missing suggestedWindow.
|
||||
func TestGetRenewalInfo_MissingWindow(t *testing.T) {
|
||||
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Mock directory endpoint
|
||||
if r.URL.Path == "/directory" && r.Method == http.MethodGet {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"renewalInfo": "/acme/renewalInfo",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Mock renewalInfo without suggestedWindow
|
||||
if r.URL.Path != "/directory" && r.Method == http.MethodGet {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{})
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, "not found", http.StatusNotFound)
|
||||
}))
|
||||
defer mockServer.Close()
|
||||
|
||||
config := &Config{
|
||||
DirectoryURL: mockServer.URL + "/directory",
|
||||
Email: "test@example.com",
|
||||
ChallengeType: "http-01",
|
||||
ARIEnabled: true,
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
connector := New(config, logger)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := connector.GetRenewalInfo(ctx, "invalid-cert-pem")
|
||||
// Error is expected due to invalid cert PEM
|
||||
if err == nil {
|
||||
t.Error("expected error for invalid cert or missing window")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
// Package digicert implements the issuer.Connector interface for DigiCert CertCentral.
|
||||
//
|
||||
// DigiCert CertCentral is an enterprise certificate authority offering DV, OV, and EV
|
||||
// certificates. Unlike synchronous issuers (Vault, step-ca), DigiCert uses an
|
||||
// asynchronous order model: submit an order, receive an order ID, then poll for
|
||||
// completion. OV/EV certificates require organization validation which may take hours
|
||||
// or days; DV certificates may be issued immediately.
|
||||
//
|
||||
// This connector maps to certctl's existing job state machine:
|
||||
// - IssueCertificate submits the order; if status is "issued", returns cert immediately.
|
||||
// If status is "pending", returns OrderID with empty CertPEM — the job system polls
|
||||
// via GetOrderStatus.
|
||||
// - GetOrderStatus polls the order; when status becomes "issued", downloads and
|
||||
// parses the PEM bundle.
|
||||
//
|
||||
// Authentication: API key via X-DC-DEVKEY header.
|
||||
//
|
||||
// DigiCert CertCentral API used:
|
||||
//
|
||||
// POST /order/certificate/{product_type} - Submit certificate order
|
||||
// GET /order/certificate/{order_id} - Check order status
|
||||
// GET /certificate/{certificate_id}/download/format/pem_all - Download cert bundle
|
||||
// PUT /certificate/{certificate_id}/revoke - Revoke certificate
|
||||
// GET /user/me - Validate API credentials
|
||||
package digicert
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/connector/issuer"
|
||||
)
|
||||
|
||||
// Config represents the DigiCert CertCentral issuer connector configuration.
|
||||
type Config struct {
|
||||
// APIKey is the CertCentral API key for authentication.
|
||||
// Required. Set via CERTCTL_DIGICERT_API_KEY environment variable.
|
||||
APIKey string `json:"api_key"`
|
||||
|
||||
// OrgID is the DigiCert organization ID for certificate orders.
|
||||
// Required. Set via CERTCTL_DIGICERT_ORG_ID environment variable.
|
||||
OrgID string `json:"org_id"`
|
||||
|
||||
// ProductType is the DigiCert product type for certificate orders.
|
||||
// Default: "ssl_basic". Set via CERTCTL_DIGICERT_PRODUCT_TYPE environment variable.
|
||||
// Common values: "ssl_basic", "ssl_wildcard", "ssl_ev_basic", "ssl_plus", "ssl_multi_domain".
|
||||
ProductType string `json:"product_type"`
|
||||
|
||||
// BaseURL is the DigiCert CertCentral API base URL.
|
||||
// Default: "https://www.digicert.com/services/v2".
|
||||
// Set via CERTCTL_DIGICERT_BASE_URL environment variable.
|
||||
BaseURL string `json:"base_url"`
|
||||
}
|
||||
|
||||
// Connector implements the issuer.Connector interface for DigiCert CertCentral.
|
||||
type Connector struct {
|
||||
config *Config
|
||||
logger *slog.Logger
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
// New creates a new DigiCert CertCentral connector with the given configuration and logger.
|
||||
func New(config *Config, logger *slog.Logger) *Connector {
|
||||
if config != nil {
|
||||
if config.ProductType == "" {
|
||||
config.ProductType = "ssl_basic"
|
||||
}
|
||||
if config.BaseURL == "" {
|
||||
config.BaseURL = "https://www.digicert.com/services/v2"
|
||||
}
|
||||
}
|
||||
|
||||
return &Connector{
|
||||
config: config,
|
||||
logger: logger,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// orderRequest is the JSON body for DigiCert certificate order submission.
|
||||
type orderRequest struct {
|
||||
Certificate orderCert `json:"certificate"`
|
||||
Organization orderOrg `json:"organization"`
|
||||
ValidityYears int `json:"validity_years"`
|
||||
}
|
||||
|
||||
type orderCert struct {
|
||||
CommonName string `json:"common_name"`
|
||||
CSR string `json:"csr"`
|
||||
DNSNames []string `json:"dns_names,omitempty"`
|
||||
}
|
||||
|
||||
type orderOrg struct {
|
||||
ID json.Number `json:"id"`
|
||||
}
|
||||
|
||||
// orderResponse is the JSON response from a certificate order submission.
|
||||
type orderResponse struct {
|
||||
ID int `json:"id"`
|
||||
Status string `json:"status"`
|
||||
CertificateID int `json:"certificate_id,omitempty"`
|
||||
}
|
||||
|
||||
// orderStatusResponse is the JSON response from an order status check.
|
||||
type orderStatusResponse struct {
|
||||
ID int `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Certificate struct {
|
||||
ID int `json:"id"`
|
||||
CommonName string `json:"common_name"`
|
||||
} `json:"certificate"`
|
||||
}
|
||||
|
||||
// ValidateConfig checks that the DigiCert configuration is valid and API access works.
|
||||
func (c *Connector) ValidateConfig(ctx context.Context, rawConfig json.RawMessage) error {
|
||||
var cfg Config
|
||||
if err := json.Unmarshal(rawConfig, &cfg); err != nil {
|
||||
return fmt.Errorf("invalid DigiCert config: %w", err)
|
||||
}
|
||||
|
||||
if cfg.APIKey == "" {
|
||||
return fmt.Errorf("DigiCert api_key is required")
|
||||
}
|
||||
|
||||
if cfg.OrgID == "" {
|
||||
return fmt.Errorf("DigiCert org_id is required")
|
||||
}
|
||||
|
||||
if cfg.ProductType == "" {
|
||||
cfg.ProductType = "ssl_basic"
|
||||
}
|
||||
if cfg.BaseURL == "" {
|
||||
cfg.BaseURL = "https://www.digicert.com/services/v2"
|
||||
}
|
||||
|
||||
// Test API access via /user/me
|
||||
meURL := cfg.BaseURL + "/user/me"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, meURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create API test request: %w", err)
|
||||
}
|
||||
req.Header.Set("X-DC-DEVKEY", cfg.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("DigiCert API not reachable at %s: %w", cfg.BaseURL, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnauthorized {
|
||||
return fmt.Errorf("DigiCert API key is invalid (status %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("DigiCert API returned status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
c.config = &cfg
|
||||
c.logger.Info("DigiCert CertCentral configuration validated",
|
||||
"base_url", cfg.BaseURL,
|
||||
"product_type", cfg.ProductType)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// IssueCertificate submits a certificate order to DigiCert CertCentral.
|
||||
// If the certificate is issued immediately (DV certs), returns the cert.
|
||||
// If pending (OV/EV certs), returns OrderID with empty CertPEM for polling.
|
||||
func (c *Connector) IssueCertificate(ctx context.Context, request issuer.IssuanceRequest) (*issuer.IssuanceResult, error) {
|
||||
c.logger.Info("processing DigiCert issuance request",
|
||||
"common_name", request.CommonName,
|
||||
"san_count", len(request.SANs),
|
||||
"product_type", c.config.ProductType)
|
||||
|
||||
orderReq := orderRequest{
|
||||
Certificate: orderCert{
|
||||
CommonName: request.CommonName,
|
||||
CSR: request.CSRPEM,
|
||||
DNSNames: request.SANs,
|
||||
},
|
||||
Organization: orderOrg{
|
||||
ID: json.Number(c.config.OrgID),
|
||||
},
|
||||
ValidityYears: 1,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(orderReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal order request: %w", err)
|
||||
}
|
||||
|
||||
orderURL := fmt.Sprintf("%s/order/certificate/%s", c.config.BaseURL, c.config.ProductType)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, orderURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create order request: %w", err)
|
||||
}
|
||||
req.Header.Set("X-DC-DEVKEY", c.config.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("DigiCert order request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read order response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||
return nil, fmt.Errorf("DigiCert order returned status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var orderResp orderResponse
|
||||
if err := json.Unmarshal(respBody, &orderResp); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse order response: %w", err)
|
||||
}
|
||||
|
||||
orderID := fmt.Sprintf("%d", orderResp.ID)
|
||||
|
||||
c.logger.Info("DigiCert order submitted",
|
||||
"order_id", orderID,
|
||||
"status", orderResp.Status)
|
||||
|
||||
// If issued immediately (DV certs), download the certificate
|
||||
if orderResp.Status == "issued" && orderResp.CertificateID > 0 {
|
||||
certPEM, chainPEM, serial, notBefore, notAfter, err := c.downloadCertificate(ctx, orderResp.CertificateID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to download certificate: %w", err)
|
||||
}
|
||||
|
||||
c.logger.Info("DigiCert certificate issued immediately",
|
||||
"order_id", orderID,
|
||||
"serial", serial)
|
||||
|
||||
return &issuer.IssuanceResult{
|
||||
CertPEM: certPEM,
|
||||
ChainPEM: chainPEM,
|
||||
Serial: serial,
|
||||
NotBefore: notBefore,
|
||||
NotAfter: notAfter,
|
||||
OrderID: orderID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Pending — return OrderID for polling via GetOrderStatus
|
||||
c.logger.Info("DigiCert order pending validation",
|
||||
"order_id", orderID,
|
||||
"status", orderResp.Status)
|
||||
|
||||
return &issuer.IssuanceResult{
|
||||
OrderID: orderID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RenewCertificate renews a certificate by submitting a new order.
|
||||
// DigiCert uses reissue for renewal, but for simplicity we submit a new order
|
||||
// (reissue requires the original order ID which may not be available).
|
||||
func (c *Connector) RenewCertificate(ctx context.Context, request issuer.RenewalRequest) (*issuer.IssuanceResult, error) {
|
||||
c.logger.Info("processing DigiCert renewal request",
|
||||
"common_name", request.CommonName,
|
||||
"san_count", len(request.SANs))
|
||||
|
||||
return c.IssueCertificate(ctx, issuer.IssuanceRequest{
|
||||
CommonName: request.CommonName,
|
||||
SANs: request.SANs,
|
||||
CSRPEM: request.CSRPEM,
|
||||
EKUs: request.EKUs,
|
||||
})
|
||||
}
|
||||
|
||||
// RevokeCertificate revokes a certificate at DigiCert CertCentral.
|
||||
// DigiCert revocation uses certificate_id, so we extract it from the serial
|
||||
// by looking up the order. For simplicity, we use the serial as the cert ID
|
||||
// (the caller should provide the DigiCert certificate ID).
|
||||
func (c *Connector) RevokeCertificate(ctx context.Context, request issuer.RevocationRequest) error {
|
||||
c.logger.Info("processing DigiCert revocation request", "serial", request.Serial)
|
||||
|
||||
reason := "unspecified"
|
||||
if request.Reason != nil {
|
||||
reason = *request.Reason
|
||||
}
|
||||
|
||||
revokeBody := map[string]interface{}{
|
||||
"reason": reason,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(revokeBody)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal revoke request: %w", err)
|
||||
}
|
||||
|
||||
// DigiCert uses certificate_id in the URL path for revocation
|
||||
revokeURL := fmt.Sprintf("%s/certificate/%s/revoke", c.config.BaseURL, request.Serial)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, revokeURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create revoke request: %w", err)
|
||||
}
|
||||
req.Header.Set("X-DC-DEVKEY", c.config.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("DigiCert revoke request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// DigiCert returns 204 No Content on successful revocation
|
||||
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK {
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("DigiCert revoke returned status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
c.logger.Info("DigiCert certificate revoked", "serial", request.Serial, "reason", reason)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetOrderStatus checks the status of a DigiCert certificate order.
|
||||
// If the order is "issued", downloads the certificate and returns it.
|
||||
// If still "pending", returns pending status for continued polling.
|
||||
func (c *Connector) GetOrderStatus(ctx context.Context, orderID string) (*issuer.OrderStatus, error) {
|
||||
c.logger.Debug("checking DigiCert order status", "order_id", orderID)
|
||||
|
||||
statusURL := fmt.Sprintf("%s/order/certificate/%s", c.config.BaseURL, orderID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, statusURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create status request: %w", err)
|
||||
}
|
||||
req.Header.Set("X-DC-DEVKEY", c.config.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("DigiCert status request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read status response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("DigiCert order status returned %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var statusResp orderStatusResponse
|
||||
if err := json.Unmarshal(respBody, &statusResp); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse status response: %w", err)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
|
||||
switch statusResp.Status {
|
||||
case "issued":
|
||||
if statusResp.Certificate.ID == 0 {
|
||||
return nil, fmt.Errorf("order is issued but certificate_id is missing")
|
||||
}
|
||||
|
||||
certPEM, chainPEM, serial, notBefore, notAfter, err := c.downloadCertificate(ctx, statusResp.Certificate.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to download certificate: %w", err)
|
||||
}
|
||||
|
||||
c.logger.Info("DigiCert order completed",
|
||||
"order_id", orderID,
|
||||
"serial", serial)
|
||||
|
||||
return &issuer.OrderStatus{
|
||||
OrderID: orderID,
|
||||
Status: "completed",
|
||||
CertPEM: &certPEM,
|
||||
ChainPEM: &chainPEM,
|
||||
Serial: &serial,
|
||||
NotBefore: ¬Before,
|
||||
NotAfter: ¬After,
|
||||
UpdatedAt: now,
|
||||
}, nil
|
||||
|
||||
case "pending", "processing":
|
||||
msg := fmt.Sprintf("order %s is %s", orderID, statusResp.Status)
|
||||
return &issuer.OrderStatus{
|
||||
OrderID: orderID,
|
||||
Status: "pending",
|
||||
Message: &msg,
|
||||
UpdatedAt: now,
|
||||
}, nil
|
||||
|
||||
case "rejected", "denied":
|
||||
msg := fmt.Sprintf("order %s was %s", orderID, statusResp.Status)
|
||||
return &issuer.OrderStatus{
|
||||
OrderID: orderID,
|
||||
Status: "failed",
|
||||
Message: &msg,
|
||||
UpdatedAt: now,
|
||||
}, nil
|
||||
|
||||
default:
|
||||
msg := fmt.Sprintf("unknown order status: %s", statusResp.Status)
|
||||
return &issuer.OrderStatus{
|
||||
OrderID: orderID,
|
||||
Status: "pending",
|
||||
Message: &msg,
|
||||
UpdatedAt: now,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// downloadCertificate downloads the PEM bundle for a DigiCert certificate.
|
||||
func (c *Connector) downloadCertificate(ctx context.Context, certificateID int) (certPEM string, chainPEM string, serial string, notBefore time.Time, notAfter time.Time, err error) {
|
||||
downloadURL := fmt.Sprintf("%s/certificate/%d/download/format/pem_all", c.config.BaseURL, certificateID)
|
||||
req, reqErr := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil)
|
||||
if reqErr != nil {
|
||||
err = fmt.Errorf("failed to create download request: %w", reqErr)
|
||||
return
|
||||
}
|
||||
req.Header.Set("X-DC-DEVKEY", c.config.APIKey)
|
||||
|
||||
resp, doErr := c.httpClient.Do(req)
|
||||
if doErr != nil {
|
||||
err = fmt.Errorf("DigiCert download request failed: %w", doErr)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
err = fmt.Errorf("DigiCert download returned status %d: %s", resp.StatusCode, string(body))
|
||||
return
|
||||
}
|
||||
|
||||
body, readErr := io.ReadAll(resp.Body)
|
||||
if readErr != nil {
|
||||
err = fmt.Errorf("failed to read download response: %w", readErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse the PEM bundle: first cert is the leaf, rest are intermediates
|
||||
certPEM, chainPEM, serial, notBefore, notAfter, err = parsePEMBundle(string(body))
|
||||
return
|
||||
}
|
||||
|
||||
// parsePEMBundle splits a PEM bundle into leaf cert and chain, extracting metadata.
|
||||
func parsePEMBundle(bundle string) (certPEM string, chainPEM string, serial string, notBefore time.Time, notAfter time.Time, err error) {
|
||||
var certs []string
|
||||
remaining := bundle
|
||||
|
||||
for {
|
||||
var block *pem.Block
|
||||
block, rest := pem.Decode([]byte(remaining))
|
||||
if block == nil {
|
||||
break
|
||||
}
|
||||
if block.Type == "CERTIFICATE" {
|
||||
certs = append(certs, string(pem.EncodeToMemory(block)))
|
||||
}
|
||||
remaining = string(rest)
|
||||
}
|
||||
|
||||
if len(certs) == 0 {
|
||||
err = fmt.Errorf("no certificates found in PEM bundle")
|
||||
return
|
||||
}
|
||||
|
||||
certPEM = certs[0]
|
||||
if len(certs) > 1 {
|
||||
chainPEM = strings.Join(certs[1:], "")
|
||||
}
|
||||
|
||||
// Parse leaf cert for metadata
|
||||
block, _ := pem.Decode([]byte(certPEM))
|
||||
if block == nil {
|
||||
err = fmt.Errorf("failed to decode leaf certificate PEM")
|
||||
return
|
||||
}
|
||||
|
||||
cert, parseErr := x509.ParseCertificate(block.Bytes)
|
||||
if parseErr != nil {
|
||||
err = fmt.Errorf("failed to parse leaf certificate: %w", parseErr)
|
||||
return
|
||||
}
|
||||
|
||||
serial = cert.SerialNumber.String()
|
||||
notBefore = cert.NotBefore
|
||||
notAfter = cert.NotAfter
|
||||
return
|
||||
}
|
||||
|
||||
// GenerateCRL is not supported because DigiCert manages CRL distribution.
|
||||
func (c *Connector) GenerateCRL(ctx context.Context, revokedCerts []issuer.RevokedCertEntry) ([]byte, error) {
|
||||
return nil, fmt.Errorf("DigiCert manages CRL distribution; use DigiCert's CRL endpoints")
|
||||
}
|
||||
|
||||
// SignOCSPResponse is not supported because DigiCert manages OCSP.
|
||||
func (c *Connector) SignOCSPResponse(ctx context.Context, req issuer.OCSPSignRequest) ([]byte, error) {
|
||||
return nil, fmt.Errorf("DigiCert manages OCSP; use DigiCert's OCSP responder")
|
||||
}
|
||||
|
||||
// GetCACertPEM is not directly supported. DigiCert intermediate certificates
|
||||
// come with each certificate issuance as part of the PEM bundle.
|
||||
func (c *Connector) GetCACertPEM(ctx context.Context) (string, error) {
|
||||
return "", fmt.Errorf("DigiCert intermediate certificates are included with each issued certificate")
|
||||
}
|
||||
|
||||
// GetRenewalInfo returns nil, nil as DigiCert does not support ACME Renewal Information (ARI).
|
||||
func (c *Connector) GetRenewalInfo(ctx context.Context, certPEM string) (*issuer.RenewalInfoResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Ensure Connector implements the issuer.Connector interface.
|
||||
var _ issuer.Connector = (*Connector)(nil)
|
||||
@@ -0,0 +1,591 @@
|
||||
package digicert_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/connector/issuer"
|
||||
"github.com/shankar0123/certctl/internal/connector/issuer/digicert"
|
||||
)
|
||||
|
||||
func TestDigiCertConnector(t *testing.T) {
|
||||
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("ValidateConfig_Success", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/user/me" {
|
||||
if r.Header.Get("X-DC-DEVKEY") == "dc-test-api-key" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"id":12345,"first_name":"Test","last_name":"User"}`))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte(`{"errors":[{"code":"invalid_api_key"}]}`))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := digicert.Config{
|
||||
APIKey: "dc-test-api-key",
|
||||
OrgID: "12345",
|
||||
ProductType: "ssl_basic",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
|
||||
connector := digicert.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateConfig failed: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ValidateConfig_MissingAPIKey", func(t *testing.T) {
|
||||
config := digicert.Config{
|
||||
OrgID: "12345",
|
||||
}
|
||||
|
||||
connector := digicert.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for missing api_key")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "api_key is required") {
|
||||
t.Errorf("Expected api_key required error, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ValidateConfig_MissingOrgID", func(t *testing.T) {
|
||||
config := digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
}
|
||||
|
||||
connector := digicert.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for missing org_id")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "org_id is required") {
|
||||
t.Errorf("Expected org_id required error, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ValidateConfig_InvalidKey", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/user/me" {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte(`{"errors":[{"code":"invalid_api_key"}]}`))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := digicert.Config{
|
||||
APIKey: "dc-bad-key",
|
||||
OrgID: "12345",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
|
||||
connector := digicert.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for invalid API key")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "invalid") {
|
||||
t.Logf("Got error: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("IssueCertificate_ImmediateSuccess", func(t *testing.T) {
|
||||
testCertPEM, _ := generateTestCert(t)
|
||||
testChainPEM, _ := generateTestCert(t)
|
||||
pemBundle := testCertPEM + testChainPEM
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasPrefix(r.URL.Path, "/order/certificate/ssl_basic"):
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
w.Write([]byte(`{"id":99001,"status":"issued","certificate_id":88001}`))
|
||||
case r.URL.Path == "/certificate/88001/download/format/pem_all":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(pemBundle))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
ProductType: "ssl_basic",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
_, csrPEM := generateTestCSR(t, "app.example.com")
|
||||
req := issuer.IssuanceRequest{
|
||||
CommonName: "app.example.com",
|
||||
SANs: []string{"app.example.com"},
|
||||
CSRPEM: csrPEM,
|
||||
}
|
||||
|
||||
result, err := connector.IssueCertificate(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueCertificate failed: %v", err)
|
||||
}
|
||||
|
||||
if result.CertPEM == "" {
|
||||
t.Error("CertPEM should not be empty for immediate issuance")
|
||||
}
|
||||
if result.Serial == "" {
|
||||
t.Error("Serial should not be empty for immediate issuance")
|
||||
}
|
||||
if result.OrderID != "99001" {
|
||||
t.Errorf("Expected OrderID '99001', got '%s'", result.OrderID)
|
||||
}
|
||||
t.Logf("DigiCert issued cert: serial=%s, orderID=%s", result.Serial, result.OrderID)
|
||||
})
|
||||
|
||||
t.Run("IssueCertificate_Pending", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasPrefix(r.URL.Path, "/order/certificate/ssl_ev_basic"):
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
w.Write([]byte(`{"id":99002,"status":"pending"}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
ProductType: "ssl_ev_basic",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
_, csrPEM := generateTestCSR(t, "secure.example.com")
|
||||
req := issuer.IssuanceRequest{
|
||||
CommonName: "secure.example.com",
|
||||
CSRPEM: csrPEM,
|
||||
}
|
||||
|
||||
result, err := connector.IssueCertificate(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueCertificate failed: %v", err)
|
||||
}
|
||||
|
||||
if result.OrderID != "99002" {
|
||||
t.Errorf("Expected OrderID '99002', got '%s'", result.OrderID)
|
||||
}
|
||||
if result.CertPEM != "" {
|
||||
t.Error("CertPEM should be empty for pending order")
|
||||
}
|
||||
if result.Serial != "" {
|
||||
t.Error("Serial should be empty for pending order")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("IssueCertificate_ServerError", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(`{"errors":[{"code":"invalid_csr","message":"CSR is malformed"}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
ProductType: "ssl_basic",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
req := issuer.IssuanceRequest{
|
||||
CommonName: "test.example.com",
|
||||
CSRPEM: "invalid-csr",
|
||||
}
|
||||
|
||||
_, err := connector.IssueCertificate(ctx, req)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for server error response")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetOrderStatus_Issued", func(t *testing.T) {
|
||||
testCertPEM, _ := generateTestCert(t)
|
||||
testChainPEM, _ := generateTestCert(t)
|
||||
pemBundle := testCertPEM + testChainPEM
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/order/certificate/99001":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"id":99001,"status":"issued","certificate":{"id":88001,"common_name":"app.example.com"}}`))
|
||||
case "/certificate/88001/download/format/pem_all":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(pemBundle))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
status, err := connector.GetOrderStatus(ctx, "99001")
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrderStatus failed: %v", err)
|
||||
}
|
||||
|
||||
if status.Status != "completed" {
|
||||
t.Errorf("Expected status 'completed', got '%s'", status.Status)
|
||||
}
|
||||
if status.CertPEM == nil || *status.CertPEM == "" {
|
||||
t.Error("CertPEM should not be empty for issued order")
|
||||
}
|
||||
if status.Serial == nil || *status.Serial == "" {
|
||||
t.Error("Serial should not be empty for issued order")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetOrderStatus_Pending", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/order/certificate/99002" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"id":99002,"status":"pending","certificate":{"id":0}}`))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
status, err := connector.GetOrderStatus(ctx, "99002")
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrderStatus failed: %v", err)
|
||||
}
|
||||
|
||||
if status.Status != "pending" {
|
||||
t.Errorf("Expected status 'pending', got '%s'", status.Status)
|
||||
}
|
||||
if status.CertPEM != nil {
|
||||
t.Error("CertPEM should be nil for pending order")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetOrderStatus_Rejected", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/order/certificate/99003" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"id":99003,"status":"rejected","certificate":{"id":0}}`))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
status, err := connector.GetOrderStatus(ctx, "99003")
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrderStatus failed: %v", err)
|
||||
}
|
||||
|
||||
if status.Status != "failed" {
|
||||
t.Errorf("Expected status 'failed', got '%s'", status.Status)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RenewCertificate_NewOrder", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasPrefix(r.URL.Path, "/order/certificate/"):
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
w.Write([]byte(`{"id":99010,"status":"pending"}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
ProductType: "ssl_basic",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
_, csrPEM := generateTestCSR(t, "renew.example.com")
|
||||
renewReq := issuer.RenewalRequest{
|
||||
CommonName: "renew.example.com",
|
||||
CSRPEM: csrPEM,
|
||||
}
|
||||
|
||||
result, err := connector.RenewCertificate(ctx, renewReq)
|
||||
if err != nil {
|
||||
t.Fatalf("RenewCertificate failed: %v", err)
|
||||
}
|
||||
|
||||
if result.OrderID == "" {
|
||||
t.Error("OrderID should not be empty")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RevokeCertificate_Success", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.Path, "/revoke") && r.Method == http.MethodPut {
|
||||
if r.Header.Get("X-DC-DEVKEY") == "" {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
reason := "keyCompromise"
|
||||
revokeReq := issuer.RevocationRequest{
|
||||
Serial: "88001",
|
||||
Reason: &reason,
|
||||
}
|
||||
|
||||
err := connector.RevokeCertificate(ctx, revokeReq)
|
||||
if err != nil {
|
||||
t.Fatalf("RevokeCertificate failed: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RevokeCertificate_Error", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(`{"errors":[{"code":"certificate_not_found"}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
revokeReq := issuer.RevocationRequest{
|
||||
Serial: "00000",
|
||||
}
|
||||
|
||||
err := connector.RevokeCertificate(ctx, revokeReq)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for revocation of nonexistent cert")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetOrderStatus_DownloadError", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/order/certificate/99004":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"id":99004,"status":"issued","certificate":{"id":88004}}`))
|
||||
case "/certificate/88004/download/format/pem_all":
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(`{"errors":["internal server error"]}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
BaseURL: srv.URL,
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
_, err := connector.GetOrderStatus(ctx, "99004")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error when download fails")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "download") {
|
||||
t.Logf("Got error: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetRenewalInfo_ReturnsNil", func(t *testing.T) {
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
BaseURL: "https://api.digicert.com",
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
result, err := connector.GetRenewalInfo(ctx, "-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
|
||||
if err != nil {
|
||||
t.Fatalf("GetRenewalInfo should not return error, got: %v", err)
|
||||
}
|
||||
if result != nil {
|
||||
t.Fatal("GetRenewalInfo should return nil for DigiCert")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("DefaultProductType", func(t *testing.T) {
|
||||
config := &digicert.Config{
|
||||
APIKey: "dc-test-key",
|
||||
OrgID: "12345",
|
||||
// ProductType intentionally left empty
|
||||
}
|
||||
connector := digicert.New(config, logger)
|
||||
|
||||
// Verify the connector was created (the default is set in New())
|
||||
if connector == nil {
|
||||
t.Fatal("Connector should not be nil")
|
||||
}
|
||||
|
||||
// Verify via a request that uses the product type
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Verify the path includes the default product type
|
||||
if strings.Contains(r.URL.Path, "ssl_basic") {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
w.Write([]byte(`{"id":99099,"status":"pending"}`))
|
||||
return
|
||||
}
|
||||
t.Errorf("Expected path to contain 'ssl_basic', got: %s", r.URL.Path)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// Reconfigure with test server URL
|
||||
config.BaseURL = srv.URL
|
||||
connector = digicert.New(config, logger)
|
||||
|
||||
_, csrPEM := generateTestCSR(t, "test.example.com")
|
||||
req := issuer.IssuanceRequest{
|
||||
CommonName: "test.example.com",
|
||||
CSRPEM: csrPEM,
|
||||
}
|
||||
|
||||
result, err := connector.IssueCertificate(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueCertificate with default product type failed: %v", err)
|
||||
}
|
||||
if result.OrderID == "" {
|
||||
t.Error("OrderID should not be empty")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// generateTestCert creates a self-signed test certificate and returns the PEM strings.
|
||||
func generateTestCert(t *testing.T) (certPEM string, keyPEM string) {
|
||||
t.Helper()
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate key: %v", err)
|
||||
}
|
||||
|
||||
serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{
|
||||
CommonName: fmt.Sprintf("Test Certificate %s", serial.String()[:8]),
|
||||
},
|
||||
DNSNames: []string{"test.example.com"},
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
}
|
||||
|
||||
certBytes, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create certificate: %v", err)
|
||||
}
|
||||
|
||||
certPEM = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes}))
|
||||
keyPEM = string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}))
|
||||
|
||||
return certPEM, keyPEM
|
||||
}
|
||||
|
||||
// generateTestCSR creates a test CSR for the given common name.
|
||||
func generateTestCSR(t *testing.T, commonName string) (*x509.CertificateRequest, string) {
|
||||
t.Helper()
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate key: %v", err)
|
||||
}
|
||||
|
||||
csrTemplate := x509.CertificateRequest{
|
||||
Subject: pkix.Name{
|
||||
CommonName: commonName,
|
||||
},
|
||||
DNSNames: []string{commonName},
|
||||
SignatureAlgorithm: x509.SHA256WithRSA,
|
||||
}
|
||||
|
||||
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, key)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create CSR: %v", err)
|
||||
}
|
||||
|
||||
csrPEM := string(pem.EncodeToMemory(&pem.Block{
|
||||
Type: "CERTIFICATE REQUEST",
|
||||
Bytes: csrBytes,
|
||||
}))
|
||||
|
||||
csr, err := x509.ParseCertificateRequest(csrBytes)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse CSR: %v", err)
|
||||
}
|
||||
|
||||
return csr, csrPEM
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package issuer
|
||||
|
||||
// Factory has been moved to internal/connector/issuerfactory to avoid import cycles.
|
||||
// See issuerfactory.NewFromConfig().
|
||||
@@ -0,0 +1,3 @@
|
||||
package issuer
|
||||
|
||||
// Factory tests have been moved to internal/connector/issuerfactory.
|
||||
@@ -0,0 +1,619 @@
|
||||
// Package googlecas implements the issuer.Connector interface for
|
||||
// Google Cloud Certificate Authority Service (CAS).
|
||||
//
|
||||
// Google CAS is a managed private CA service on GCP. This connector
|
||||
// uses the CAS REST API (privateca.googleapis.com/v1) with OAuth2
|
||||
// service account authentication. Certificates are issued synchronously.
|
||||
//
|
||||
// Authentication: OAuth2 service account via JWT → access token exchange.
|
||||
// No Google SDK dependency — uses stdlib crypto/rsa + net/http.
|
||||
//
|
||||
// API endpoints used:
|
||||
//
|
||||
// POST /v1/{parent}/certificates - Issue certificate
|
||||
// POST /v1/{name}:revoke - Revoke certificate
|
||||
// POST /v1/{caPool}:fetchCaCerts - Get CA certificate chain
|
||||
package googlecas
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/connector/issuer"
|
||||
)
|
||||
|
||||
// Config represents the Google CAS issuer connector configuration.
|
||||
type Config struct {
|
||||
// Project is the GCP project ID.
|
||||
// Required. Set via CERTCTL_GOOGLE_CAS_PROJECT environment variable.
|
||||
Project string `json:"project"`
|
||||
|
||||
// Location is the GCP region (e.g., "us-central1").
|
||||
// Required. Set via CERTCTL_GOOGLE_CAS_LOCATION environment variable.
|
||||
Location string `json:"location"`
|
||||
|
||||
// CAPool is the Certificate Authority pool name.
|
||||
// Required. Set via CERTCTL_GOOGLE_CAS_CA_POOL environment variable.
|
||||
CAPool string `json:"ca_pool"`
|
||||
|
||||
// Credentials is the path to the service account JSON credentials file.
|
||||
// Required. Set via CERTCTL_GOOGLE_CAS_CREDENTIALS environment variable.
|
||||
Credentials string `json:"credentials"`
|
||||
|
||||
// TTL is the requested certificate TTL (e.g., "8760h" for 1 year).
|
||||
// Default: "8760h". Set via CERTCTL_GOOGLE_CAS_TTL environment variable.
|
||||
TTL string `json:"ttl"`
|
||||
|
||||
// BaseURL overrides the Google CAS API base URL (for testing).
|
||||
// Default: "https://privateca.googleapis.com/v1".
|
||||
BaseURL string `json:"base_url,omitempty"`
|
||||
|
||||
// TokenURL overrides the OAuth2 token endpoint (for testing).
|
||||
// Default: "https://oauth2.googleapis.com/token".
|
||||
TokenURL string `json:"token_url,omitempty"`
|
||||
}
|
||||
|
||||
// serviceAccountKey represents the relevant fields from a Google service account JSON file.
|
||||
type serviceAccountKey struct {
|
||||
Type string `json:"type"`
|
||||
ProjectID string `json:"project_id"`
|
||||
PrivateKey string `json:"private_key"`
|
||||
ClientEmail string `json:"client_email"`
|
||||
TokenURI string `json:"token_uri"`
|
||||
}
|
||||
|
||||
// cachedToken holds an OAuth2 access token and its expiry.
|
||||
type cachedToken struct {
|
||||
token string
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
// Connector implements the issuer.Connector interface for Google CAS.
|
||||
type Connector struct {
|
||||
config *Config
|
||||
logger *slog.Logger
|
||||
httpClient *http.Client
|
||||
|
||||
// OAuth2 token caching
|
||||
mu sync.Mutex
|
||||
tokenCache *cachedToken
|
||||
saKey *serviceAccountKey
|
||||
rsaKey *rsa.PrivateKey
|
||||
}
|
||||
|
||||
// New creates a new Google CAS connector with the given configuration and logger.
|
||||
func New(config *Config, logger *slog.Logger) *Connector {
|
||||
if config != nil {
|
||||
if config.TTL == "" {
|
||||
config.TTL = "8760h"
|
||||
}
|
||||
if config.BaseURL == "" {
|
||||
config.BaseURL = "https://privateca.googleapis.com/v1"
|
||||
}
|
||||
if config.TokenURL == "" {
|
||||
config.TokenURL = "https://oauth2.googleapis.com/token"
|
||||
}
|
||||
}
|
||||
|
||||
return &Connector{
|
||||
config: config,
|
||||
logger: logger,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// parentPath returns the CAS resource parent path.
|
||||
func (c *Connector) parentPath() string {
|
||||
return fmt.Sprintf("projects/%s/locations/%s/caPools/%s",
|
||||
c.config.Project, c.config.Location, c.config.CAPool)
|
||||
}
|
||||
|
||||
// certificateCreateResponse represents the Google CAS create certificate response.
|
||||
type certificateCreateResponse struct {
|
||||
Name string `json:"name"`
|
||||
PEMCertificate string `json:"pemCertificate"`
|
||||
PEMCertificateChain []string `json:"pemCertificateChain"`
|
||||
}
|
||||
|
||||
// fetchCACertsResponse represents the Google CAS fetchCaCerts response.
|
||||
type fetchCACertsResponse struct {
|
||||
CACerts []caCertChain `json:"caCerts"`
|
||||
}
|
||||
|
||||
type caCertChain struct {
|
||||
Certificates []string `json:"certificates"`
|
||||
}
|
||||
|
||||
// googleAPIError represents a Google API error response.
|
||||
type googleAPIError struct {
|
||||
Error struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Status string `json:"status"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
// ValidateConfig checks that the Google CAS configuration is valid.
|
||||
// Verifies required fields and that the credentials file is parseable.
|
||||
func (c *Connector) ValidateConfig(ctx context.Context, rawConfig json.RawMessage) error {
|
||||
var cfg Config
|
||||
if err := json.Unmarshal(rawConfig, &cfg); err != nil {
|
||||
return fmt.Errorf("invalid Google CAS config: %w", err)
|
||||
}
|
||||
|
||||
if cfg.Project == "" {
|
||||
return fmt.Errorf("Google CAS project is required")
|
||||
}
|
||||
if cfg.Location == "" {
|
||||
return fmt.Errorf("Google CAS location is required")
|
||||
}
|
||||
if cfg.CAPool == "" {
|
||||
return fmt.Errorf("Google CAS CA pool is required")
|
||||
}
|
||||
if cfg.Credentials == "" {
|
||||
return fmt.Errorf("Google CAS credentials path is required")
|
||||
}
|
||||
|
||||
// Verify credentials file exists and is valid
|
||||
saKey, _, err := loadServiceAccountKey(cfg.Credentials)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Google CAS credentials invalid: %w", err)
|
||||
}
|
||||
|
||||
if saKey.ClientEmail == "" {
|
||||
return fmt.Errorf("Google CAS credentials missing client_email")
|
||||
}
|
||||
if saKey.PrivateKey == "" {
|
||||
return fmt.Errorf("Google CAS credentials missing private_key")
|
||||
}
|
||||
|
||||
if cfg.TTL == "" {
|
||||
cfg.TTL = "8760h"
|
||||
}
|
||||
if cfg.BaseURL == "" {
|
||||
cfg.BaseURL = "https://privateca.googleapis.com/v1"
|
||||
}
|
||||
if cfg.TokenURL == "" {
|
||||
cfg.TokenURL = "https://oauth2.googleapis.com/token"
|
||||
}
|
||||
|
||||
c.config = &cfg
|
||||
c.logger.Info("Google CAS configuration validated",
|
||||
"project", cfg.Project,
|
||||
"location", cfg.Location,
|
||||
"ca_pool", cfg.CAPool)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadServiceAccountKey reads and parses a service account JSON file.
|
||||
func loadServiceAccountKey(path string) (*serviceAccountKey, *rsa.PrivateKey, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("cannot read credentials file: %w", err)
|
||||
}
|
||||
|
||||
var saKey serviceAccountKey
|
||||
if err := json.Unmarshal(data, &saKey); err != nil {
|
||||
return nil, nil, fmt.Errorf("cannot parse credentials JSON: %w", err)
|
||||
}
|
||||
|
||||
if saKey.PrivateKey == "" {
|
||||
return &saKey, nil, nil
|
||||
}
|
||||
|
||||
// Parse the RSA private key
|
||||
block, _ := pem.Decode([]byte(saKey.PrivateKey))
|
||||
if block == nil {
|
||||
return nil, nil, fmt.Errorf("cannot decode private key PEM")
|
||||
}
|
||||
|
||||
// Try PKCS#8 first, then PKCS#1
|
||||
var rsaKey *rsa.PrivateKey
|
||||
if key, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
|
||||
var ok bool
|
||||
rsaKey, ok = key.(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, nil, fmt.Errorf("private key is not RSA")
|
||||
}
|
||||
} else if key, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
|
||||
rsaKey = key
|
||||
} else {
|
||||
return nil, nil, fmt.Errorf("cannot parse private key: not PKCS#8 or PKCS#1")
|
||||
}
|
||||
|
||||
return &saKey, rsaKey, nil
|
||||
}
|
||||
|
||||
// getAccessToken returns a valid OAuth2 access token, refreshing if needed.
|
||||
func (c *Connector) getAccessToken(ctx context.Context) (string, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
// Return cached token if still valid (5 min buffer)
|
||||
if c.tokenCache != nil && time.Now().Add(5*time.Minute).Before(c.tokenCache.expiresAt) {
|
||||
return c.tokenCache.token, nil
|
||||
}
|
||||
|
||||
// Load credentials if not cached
|
||||
if c.saKey == nil || c.rsaKey == nil {
|
||||
saKey, rsaKey, err := loadServiceAccountKey(c.config.Credentials)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to load credentials: %w", err)
|
||||
}
|
||||
c.saKey = saKey
|
||||
c.rsaKey = rsaKey
|
||||
}
|
||||
|
||||
// Build JWT
|
||||
now := time.Now()
|
||||
header := base64URLEncode([]byte(`{"alg":"RS256","typ":"JWT"}`))
|
||||
|
||||
claims, err := json.Marshal(map[string]interface{}{
|
||||
"iss": c.saKey.ClientEmail,
|
||||
"scope": "https://www.googleapis.com/auth/cloud-platform",
|
||||
"aud": c.config.TokenURL,
|
||||
"iat": now.Unix(),
|
||||
"exp": now.Add(time.Hour).Unix(),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to marshal JWT claims: %w", err)
|
||||
}
|
||||
payload := base64URLEncode(claims)
|
||||
|
||||
// Sign
|
||||
signingInput := header + "." + payload
|
||||
hash := sha256.Sum256([]byte(signingInput))
|
||||
sig, err := rsa.SignPKCS1v15(rand.Reader, c.rsaKey, crypto.SHA256, hash[:])
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to sign JWT: %w", err)
|
||||
}
|
||||
|
||||
jwt := signingInput + "." + base64URLEncode(sig)
|
||||
|
||||
// Exchange JWT for access token
|
||||
form := url.Values{
|
||||
"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"},
|
||||
"assertion": {jwt},
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.config.TokenURL,
|
||||
strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create token request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("token exchange failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read token response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("token exchange returned status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var tokenResp struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &tokenResp); err != nil {
|
||||
return "", fmt.Errorf("failed to parse token response: %w", err)
|
||||
}
|
||||
|
||||
if tokenResp.AccessToken == "" {
|
||||
return "", fmt.Errorf("empty access token in response")
|
||||
}
|
||||
|
||||
// Cache token
|
||||
c.tokenCache = &cachedToken{
|
||||
token: tokenResp.AccessToken,
|
||||
expiresAt: now.Add(time.Duration(tokenResp.ExpiresIn) * time.Second),
|
||||
}
|
||||
|
||||
return tokenResp.AccessToken, nil
|
||||
}
|
||||
|
||||
// doAuthenticatedRequest performs an HTTP request with OAuth2 bearer token.
|
||||
func (c *Connector) doAuthenticatedRequest(ctx context.Context, method, urlStr string, body interface{}) ([]byte, int, error) {
|
||||
token, err := c.getAccessToken(ctx)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to get access token: %w", err)
|
||||
}
|
||||
|
||||
var bodyReader io.Reader
|
||||
if body != nil {
|
||||
bodyBytes, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to marshal request body: %w", err)
|
||||
}
|
||||
bodyReader = bytes.NewReader(bodyBytes)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, urlStr, bodyReader)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, resp.StatusCode, fmt.Errorf("failed to read response: %w", err)
|
||||
}
|
||||
|
||||
return respBody, resp.StatusCode, nil
|
||||
}
|
||||
|
||||
// extractAPIError extracts an error message from a Google API error response.
|
||||
func extractAPIError(body []byte) string {
|
||||
var apiErr googleAPIError
|
||||
if err := json.Unmarshal(body, &apiErr); err == nil && apiErr.Error.Message != "" {
|
||||
return fmt.Sprintf("%s (%s)", apiErr.Error.Message, apiErr.Error.Status)
|
||||
}
|
||||
return string(body)
|
||||
}
|
||||
|
||||
// IssueCertificate issues a new certificate via Google CAS.
|
||||
func (c *Connector) IssueCertificate(ctx context.Context, request issuer.IssuanceRequest) (*issuer.IssuanceResult, error) {
|
||||
c.logger.Info("processing Google CAS issuance request",
|
||||
"common_name", request.CommonName,
|
||||
"san_count", len(request.SANs))
|
||||
|
||||
// Convert TTL to seconds string
|
||||
ttlDuration, err := time.ParseDuration(c.config.TTL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid TTL %q: %w", c.config.TTL, err)
|
||||
}
|
||||
lifetimeSeconds := fmt.Sprintf("%ds", int(ttlDuration.Seconds()))
|
||||
|
||||
// Generate unique certificate ID
|
||||
certID := fmt.Sprintf("certctl-%d-%s", time.Now().Unix(), randomHex(4))
|
||||
|
||||
// Build request
|
||||
createURL := fmt.Sprintf("%s/%s/certificates?certificateId=%s",
|
||||
c.config.BaseURL, c.parentPath(), certID)
|
||||
|
||||
createBody := map[string]interface{}{
|
||||
"lifetime": lifetimeSeconds,
|
||||
"pemCsr": request.CSRPEM,
|
||||
}
|
||||
|
||||
respBody, statusCode, err := c.doAuthenticatedRequest(ctx, http.MethodPost, createURL, createBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Google CAS create certificate failed: %w", err)
|
||||
}
|
||||
|
||||
if statusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("Google CAS create certificate returned status %d: %s",
|
||||
statusCode, extractAPIError(respBody))
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var certResp certificateCreateResponse
|
||||
if err := json.Unmarshal(respBody, &certResp); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse Google CAS response: %w", err)
|
||||
}
|
||||
|
||||
if certResp.PEMCertificate == "" {
|
||||
return nil, fmt.Errorf("no certificate in Google CAS response")
|
||||
}
|
||||
|
||||
// Parse leaf cert to extract metadata
|
||||
block, _ := pem.Decode([]byte(certResp.PEMCertificate))
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("failed to decode certificate PEM from Google CAS")
|
||||
}
|
||||
|
||||
cert, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse certificate: %w", err)
|
||||
}
|
||||
|
||||
// Build chain PEM
|
||||
chainPEM := strings.Join(certResp.PEMCertificateChain, "\n")
|
||||
|
||||
serial := formatSerial(cert.SerialNumber)
|
||||
|
||||
// Store full resource name as OrderID for revocation lookup
|
||||
orderID := certResp.Name
|
||||
|
||||
c.logger.Info("Google CAS certificate issued",
|
||||
"common_name", request.CommonName,
|
||||
"serial", serial,
|
||||
"name", certResp.Name,
|
||||
"not_after", cert.NotAfter)
|
||||
|
||||
return &issuer.IssuanceResult{
|
||||
CertPEM: certResp.PEMCertificate,
|
||||
ChainPEM: chainPEM,
|
||||
Serial: serial,
|
||||
NotBefore: cert.NotBefore,
|
||||
NotAfter: cert.NotAfter,
|
||||
OrderID: orderID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RenewCertificate renews a certificate by creating a new one.
|
||||
// For Google CAS, renewal is functionally identical to issuance.
|
||||
func (c *Connector) RenewCertificate(ctx context.Context, request issuer.RenewalRequest) (*issuer.IssuanceResult, error) {
|
||||
c.logger.Info("processing Google CAS renewal request",
|
||||
"common_name", request.CommonName,
|
||||
"san_count", len(request.SANs))
|
||||
|
||||
return c.IssueCertificate(ctx, issuer.IssuanceRequest{
|
||||
CommonName: request.CommonName,
|
||||
SANs: request.SANs,
|
||||
CSRPEM: request.CSRPEM,
|
||||
EKUs: request.EKUs,
|
||||
})
|
||||
}
|
||||
|
||||
// RevokeCertificate revokes a certificate at Google CAS.
|
||||
// The serial field should contain the full certificate resource name (set as OrderID at issuance).
|
||||
func (c *Connector) RevokeCertificate(ctx context.Context, request issuer.RevocationRequest) error {
|
||||
c.logger.Info("processing Google CAS revocation request", "serial", request.Serial)
|
||||
|
||||
// Determine the certificate resource name.
|
||||
// If serial starts with "projects/", it's a full resource name (from OrderID).
|
||||
// Otherwise, construct a best-effort path.
|
||||
var certName string
|
||||
if strings.HasPrefix(request.Serial, "projects/") {
|
||||
certName = request.Serial
|
||||
} else {
|
||||
certName = fmt.Sprintf("%s/certificates/%s", c.parentPath(), request.Serial)
|
||||
}
|
||||
|
||||
reason := mapRevocationReason(request.Reason)
|
||||
|
||||
revokeURL := fmt.Sprintf("%s/%s:revoke", c.config.BaseURL, certName)
|
||||
revokeBody := map[string]interface{}{
|
||||
"reason": reason,
|
||||
}
|
||||
|
||||
respBody, statusCode, err := c.doAuthenticatedRequest(ctx, http.MethodPost, revokeURL, revokeBody)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Google CAS revoke failed: %w", err)
|
||||
}
|
||||
|
||||
if statusCode != http.StatusOK {
|
||||
return fmt.Errorf("Google CAS revoke returned status %d: %s",
|
||||
statusCode, extractAPIError(respBody))
|
||||
}
|
||||
|
||||
c.logger.Info("Google CAS certificate revoked", "name", certName, "reason", reason)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetOrderStatus returns the status of a Google CAS order.
|
||||
// Google CAS signs synchronously, so orders are always "completed" immediately.
|
||||
func (c *Connector) GetOrderStatus(ctx context.Context, orderID string) (*issuer.OrderStatus, error) {
|
||||
return &issuer.OrderStatus{
|
||||
OrderID: orderID,
|
||||
Status: "completed",
|
||||
UpdatedAt: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GenerateCRL is not supported because Google CAS manages CRL directly.
|
||||
func (c *Connector) GenerateCRL(ctx context.Context, revokedCerts []issuer.RevokedCertEntry) ([]byte, error) {
|
||||
return nil, fmt.Errorf("Google CAS manages CRL directly; not supported via certctl")
|
||||
}
|
||||
|
||||
// SignOCSPResponse is not supported because Google CAS manages OCSP directly.
|
||||
func (c *Connector) SignOCSPResponse(ctx context.Context, req issuer.OCSPSignRequest) ([]byte, error) {
|
||||
return nil, fmt.Errorf("Google CAS manages OCSP directly; not supported via certctl")
|
||||
}
|
||||
|
||||
// GetCACertPEM retrieves the CA certificate chain from Google CAS.
|
||||
func (c *Connector) GetCACertPEM(ctx context.Context) (string, error) {
|
||||
fetchURL := fmt.Sprintf("%s/%s:fetchCaCerts", c.config.BaseURL, c.parentPath())
|
||||
|
||||
respBody, statusCode, err := c.doAuthenticatedRequest(ctx, http.MethodPost, fetchURL, map[string]interface{}{})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Google CAS fetchCaCerts failed: %w", err)
|
||||
}
|
||||
|
||||
if statusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("Google CAS fetchCaCerts returned status %d: %s",
|
||||
statusCode, extractAPIError(respBody))
|
||||
}
|
||||
|
||||
var resp fetchCACertsResponse
|
||||
if err := json.Unmarshal(respBody, &resp); err != nil {
|
||||
return "", fmt.Errorf("failed to parse fetchCaCerts response: %w", err)
|
||||
}
|
||||
|
||||
if len(resp.CACerts) == 0 || len(resp.CACerts[0].Certificates) == 0 {
|
||||
return "", fmt.Errorf("no CA certificates in response")
|
||||
}
|
||||
|
||||
// Join all certificates from the first CA cert chain
|
||||
return strings.Join(resp.CACerts[0].Certificates, "\n"), nil
|
||||
}
|
||||
|
||||
// GetRenewalInfo returns nil, nil as Google CAS does not support ACME Renewal Information (ARI).
|
||||
func (c *Connector) GetRenewalInfo(ctx context.Context, certPEM string) (*issuer.RenewalInfoResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// mapRevocationReason maps certctl RFC 5280 reason strings to Google CAS enum values.
|
||||
func mapRevocationReason(reason *string) string {
|
||||
if reason == nil {
|
||||
return "REVOCATION_REASON_UNSPECIFIED"
|
||||
}
|
||||
|
||||
switch strings.ToLower(*reason) {
|
||||
case "keycompromise":
|
||||
return "KEY_COMPROMISE"
|
||||
case "cacompromise":
|
||||
return "CERTIFICATE_AUTHORITY_COMPROMISE"
|
||||
case "affiliationchanged":
|
||||
return "AFFILIATION_CHANGED"
|
||||
case "superseded":
|
||||
return "SUPERSEDED"
|
||||
case "cessationofoperation":
|
||||
return "CESSATION_OF_OPERATION"
|
||||
case "certificatehold":
|
||||
return "CERTIFICATE_HOLD"
|
||||
case "privilegewithdrawn":
|
||||
return "PRIVILEGE_WITHDRAWN"
|
||||
default:
|
||||
return "REVOCATION_REASON_UNSPECIFIED"
|
||||
}
|
||||
}
|
||||
|
||||
// formatSerial converts a *big.Int serial number to a hex string.
|
||||
func formatSerial(serial *big.Int) string {
|
||||
return serial.Text(16)
|
||||
}
|
||||
|
||||
// randomHex generates n random bytes and returns them as a hex string.
|
||||
func randomHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
_, _ = rand.Read(b)
|
||||
return fmt.Sprintf("%x", b)
|
||||
}
|
||||
|
||||
// base64URLEncode encodes data using base64url without padding.
|
||||
func base64URLEncode(data []byte) string {
|
||||
return base64.RawURLEncoding.EncodeToString(data)
|
||||
}
|
||||
|
||||
// Ensure Connector implements the issuer.Connector interface.
|
||||
var _ issuer.Connector = (*Connector)(nil)
|
||||
@@ -0,0 +1,826 @@
|
||||
package googlecas_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/connector/issuer"
|
||||
"github.com/shankar0123/certctl/internal/connector/issuer/googlecas"
|
||||
)
|
||||
|
||||
func TestGoogleCASConnector(t *testing.T) {
|
||||
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("ValidateConfig_Success", func(t *testing.T) {
|
||||
credPath := createTestCredentialsFile(t)
|
||||
|
||||
config := googlecas.Config{
|
||||
Project: "my-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "my-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
}
|
||||
|
||||
connector := googlecas.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateConfig failed: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ValidateConfig_MissingProject", func(t *testing.T) {
|
||||
config := googlecas.Config{
|
||||
Location: "us-central1",
|
||||
CAPool: "my-pool",
|
||||
Credentials: "/tmp/creds.json",
|
||||
}
|
||||
|
||||
connector := googlecas.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for missing project")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "project is required") {
|
||||
t.Errorf("Expected project required error, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ValidateConfig_MissingLocation", func(t *testing.T) {
|
||||
config := googlecas.Config{
|
||||
Project: "my-project",
|
||||
CAPool: "my-pool",
|
||||
Credentials: "/tmp/creds.json",
|
||||
}
|
||||
|
||||
connector := googlecas.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for missing location")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "location is required") {
|
||||
t.Errorf("Expected location required error, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ValidateConfig_MissingCAPool", func(t *testing.T) {
|
||||
config := googlecas.Config{
|
||||
Project: "my-project",
|
||||
Location: "us-central1",
|
||||
Credentials: "/tmp/creds.json",
|
||||
}
|
||||
|
||||
connector := googlecas.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for missing CA pool")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "CA pool is required") {
|
||||
t.Errorf("Expected CA pool required error, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ValidateConfig_MissingCredentials", func(t *testing.T) {
|
||||
config := googlecas.Config{
|
||||
Project: "my-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "my-pool",
|
||||
}
|
||||
|
||||
connector := googlecas.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for missing credentials")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "credentials path is required") {
|
||||
t.Errorf("Expected credentials required error, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ValidateConfig_InvalidCredentialsFile", func(t *testing.T) {
|
||||
config := googlecas.Config{
|
||||
Project: "my-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "my-pool",
|
||||
Credentials: "/nonexistent/path/credentials.json",
|
||||
}
|
||||
|
||||
connector := googlecas.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for invalid credentials file")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "credentials invalid") {
|
||||
t.Errorf("Expected credentials invalid error, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ValidateConfig_MalformedCredentialsJSON", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
badFile := filepath.Join(tmpDir, "bad-creds.json")
|
||||
if err := os.WriteFile(badFile, []byte("not json"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
config := googlecas.Config{
|
||||
Project: "my-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "my-pool",
|
||||
Credentials: badFile,
|
||||
}
|
||||
|
||||
connector := googlecas.New(nil, logger)
|
||||
rawConfig, _ := json.Marshal(config)
|
||||
err := connector.ValidateConfig(ctx, rawConfig)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for malformed credentials JSON")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "credentials invalid") {
|
||||
t.Errorf("Expected credentials invalid error, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("IssueCertificate_Success", func(t *testing.T) {
|
||||
testCertPEM, _ := generateTestCert(t)
|
||||
credPath := createTestCredentialsFile(t)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"test-token-12345","expires_in":3600,"token_type":"Bearer"}`))
|
||||
|
||||
case strings.Contains(r.URL.Path, "/certificates") && r.Method == http.MethodPost &&
|
||||
!strings.Contains(r.URL.Path, ":revoke") && !strings.Contains(r.URL.Path, ":fetchCaCerts"):
|
||||
// Verify auth header
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth != "Bearer test-token-12345" {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte(`{"error":{"code":403,"message":"Permission denied","status":"PERMISSION_DENIED"}}`))
|
||||
return
|
||||
}
|
||||
// Verify certificateId query param
|
||||
certID := r.URL.Query().Get("certificateId")
|
||||
if certID == "" {
|
||||
t.Error("Missing certificateId query parameter")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
chainCert, _ := generateTestCert(t)
|
||||
resp := fmt.Sprintf(`{
|
||||
"name": "projects/test-project/locations/us-central1/caPools/test-pool/certificates/%s",
|
||||
"pemCertificate": %q,
|
||||
"pemCertificateChain": [%q]
|
||||
}`, certID, testCertPEM, chainCert)
|
||||
w.Write([]byte(resp))
|
||||
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
_, csrPEM := generateTestCSR(t, "app.example.com")
|
||||
|
||||
req := issuer.IssuanceRequest{
|
||||
CommonName: "app.example.com",
|
||||
SANs: []string{"app.example.com", "www.example.com"},
|
||||
CSRPEM: csrPEM,
|
||||
}
|
||||
|
||||
result, err := connector.IssueCertificate(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueCertificate failed: %v", err)
|
||||
}
|
||||
|
||||
if result.CertPEM == "" {
|
||||
t.Error("CertPEM is empty")
|
||||
}
|
||||
if result.Serial == "" {
|
||||
t.Error("Serial is empty")
|
||||
}
|
||||
if result.OrderID == "" {
|
||||
t.Error("OrderID is empty")
|
||||
}
|
||||
if !strings.HasPrefix(result.OrderID, "projects/") {
|
||||
t.Errorf("Expected OrderID to be full resource name, got '%s'", result.OrderID)
|
||||
}
|
||||
if result.ChainPEM == "" {
|
||||
t.Error("ChainPEM is empty")
|
||||
}
|
||||
if result.NotBefore.IsZero() {
|
||||
t.Error("NotBefore is zero")
|
||||
}
|
||||
if result.NotAfter.IsZero() {
|
||||
t.Error("NotAfter is zero")
|
||||
}
|
||||
t.Logf("Google CAS issued cert: serial=%s, orderID=%s", result.Serial, result.OrderID)
|
||||
})
|
||||
|
||||
t.Run("IssueCertificate_ServerError", func(t *testing.T) {
|
||||
credPath := createTestCredentialsFile(t)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"test-token","expires_in":3600,"token_type":"Bearer"}`))
|
||||
case strings.Contains(r.URL.Path, "/certificates"):
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(`{"error":{"code":400,"message":"Invalid CSR","status":"INVALID_ARGUMENT"}}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
_, csrPEM := generateTestCSR(t, "test.example.com")
|
||||
req := issuer.IssuanceRequest{
|
||||
CommonName: "test.example.com",
|
||||
CSRPEM: csrPEM,
|
||||
}
|
||||
|
||||
_, err := connector.IssueCertificate(ctx, req)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for server error response")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "Invalid CSR") {
|
||||
t.Logf("Got error: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("IssueCertificate_InvalidResponse", func(t *testing.T) {
|
||||
credPath := createTestCredentialsFile(t)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"test-token","expires_in":3600,"token_type":"Bearer"}`))
|
||||
case strings.Contains(r.URL.Path, "/certificates"):
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`not-json`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
_, csrPEM := generateTestCSR(t, "test.example.com")
|
||||
req := issuer.IssuanceRequest{
|
||||
CommonName: "test.example.com",
|
||||
CSRPEM: csrPEM,
|
||||
}
|
||||
|
||||
_, err := connector.IssueCertificate(ctx, req)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for invalid response")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "parse") {
|
||||
t.Logf("Got error: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetOrderStatus_AlwaysCompleted", func(t *testing.T) {
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
TTL: "8760h",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
status, err := connector.GetOrderStatus(ctx, "projects/p/locations/l/caPools/cp/certificates/cert-123")
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrderStatus failed: %v", err)
|
||||
}
|
||||
|
||||
if status.Status != "completed" {
|
||||
t.Errorf("Expected status 'completed', got '%s'", status.Status)
|
||||
}
|
||||
if status.OrderID != "projects/p/locations/l/caPools/cp/certificates/cert-123" {
|
||||
t.Errorf("Expected OrderID preserved, got '%s'", status.OrderID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RenewCertificate_NewCert", func(t *testing.T) {
|
||||
testCertPEM, _ := generateTestCert(t)
|
||||
credPath := createTestCredentialsFile(t)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"test-token","expires_in":3600,"token_type":"Bearer"}`))
|
||||
case strings.Contains(r.URL.Path, "/certificates") && r.Method == http.MethodPost &&
|
||||
!strings.Contains(r.URL.Path, ":revoke"):
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
resp := fmt.Sprintf(`{
|
||||
"name": "projects/test-project/locations/us-central1/caPools/test-pool/certificates/certctl-renew",
|
||||
"pemCertificate": %q,
|
||||
"pemCertificateChain": []
|
||||
}`, testCertPEM)
|
||||
w.Write([]byte(resp))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
_, csrPEM := generateTestCSR(t, "renew.example.com")
|
||||
renewReq := issuer.RenewalRequest{
|
||||
CommonName: "renew.example.com",
|
||||
CSRPEM: csrPEM,
|
||||
}
|
||||
|
||||
result, err := connector.RenewCertificate(ctx, renewReq)
|
||||
if err != nil {
|
||||
t.Fatalf("RenewCertificate failed: %v", err)
|
||||
}
|
||||
|
||||
if result.Serial == "" {
|
||||
t.Error("Serial is empty")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RevokeCertificate_Success", func(t *testing.T) {
|
||||
credPath := createTestCredentialsFile(t)
|
||||
|
||||
var receivedReason string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"test-token","expires_in":3600,"token_type":"Bearer"}`))
|
||||
case strings.Contains(r.URL.Path, ":revoke"):
|
||||
var body map[string]interface{}
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
receivedReason = body["reason"].(string)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"name":"projects/p/locations/l/caPools/cp/certificates/cert-123"}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
reason := "keyCompromise"
|
||||
revokeReq := issuer.RevocationRequest{
|
||||
Serial: "projects/test-project/locations/us-central1/caPools/test-pool/certificates/cert-123",
|
||||
Reason: &reason,
|
||||
}
|
||||
|
||||
err := connector.RevokeCertificate(ctx, revokeReq)
|
||||
if err != nil {
|
||||
t.Fatalf("RevokeCertificate failed: %v", err)
|
||||
}
|
||||
|
||||
if receivedReason != "KEY_COMPROMISE" {
|
||||
t.Errorf("Expected reason 'KEY_COMPROMISE', got '%s'", receivedReason)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RevokeCertificate_Error", func(t *testing.T) {
|
||||
credPath := createTestCredentialsFile(t)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"test-token","expires_in":3600,"token_type":"Bearer"}`))
|
||||
case strings.Contains(r.URL.Path, ":revoke"):
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte(`{"error":{"code":404,"message":"Certificate not found","status":"NOT_FOUND"}}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
revokeReq := issuer.RevocationRequest{
|
||||
Serial: "projects/test-project/locations/us-central1/caPools/test-pool/certificates/nonexistent",
|
||||
}
|
||||
|
||||
err := connector.RevokeCertificate(ctx, revokeReq)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for revoke of nonexistent certificate")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "Certificate not found") {
|
||||
t.Logf("Got error: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RevocationReasonMapping", func(t *testing.T) {
|
||||
credPath := createTestCredentialsFile(t)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
reason string
|
||||
expected string
|
||||
}{
|
||||
{"keyCompromise", "keyCompromise", "KEY_COMPROMISE"},
|
||||
{"caCompromise", "caCompromise", "CERTIFICATE_AUTHORITY_COMPROMISE"},
|
||||
{"affiliationChanged", "affiliationChanged", "AFFILIATION_CHANGED"},
|
||||
{"superseded", "superseded", "SUPERSEDED"},
|
||||
{"cessationOfOperation", "cessationOfOperation", "CESSATION_OF_OPERATION"},
|
||||
{"certificateHold", "certificateHold", "CERTIFICATE_HOLD"},
|
||||
{"privilegeWithdrawn", "privilegeWithdrawn", "PRIVILEGE_WITHDRAWN"},
|
||||
{"unspecified", "unspecified", "REVOCATION_REASON_UNSPECIFIED"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var receivedReason string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"test-token","expires_in":3600,"token_type":"Bearer"}`))
|
||||
case strings.Contains(r.URL.Path, ":revoke"):
|
||||
var body map[string]interface{}
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
receivedReason = body["reason"].(string)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
reason := tc.reason
|
||||
err := connector.RevokeCertificate(ctx, issuer.RevocationRequest{
|
||||
Serial: "projects/p/locations/l/caPools/cp/certificates/cert-1",
|
||||
Reason: &reason,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RevokeCertificate failed: %v", err)
|
||||
}
|
||||
|
||||
if receivedReason != tc.expected {
|
||||
t.Errorf("Expected reason '%s', got '%s'", tc.expected, receivedReason)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetCACertPEM_Success", func(t *testing.T) {
|
||||
credPath := createTestCredentialsFile(t)
|
||||
caCertPEM, _ := generateTestCert(t)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"test-token","expires_in":3600,"token_type":"Bearer"}`))
|
||||
case strings.Contains(r.URL.Path, ":fetchCaCerts"):
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
resp := fmt.Sprintf(`{"caCerts":[{"certificates":[%q]}]}`, caCertPEM)
|
||||
w.Write([]byte(resp))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
caPEM, err := connector.GetCACertPEM(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("GetCACertPEM failed: %v", err)
|
||||
}
|
||||
|
||||
if !strings.Contains(caPEM, "BEGIN CERTIFICATE") {
|
||||
t.Errorf("Expected CA PEM to contain certificate, got: %s", caPEM[:50])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetCACertPEM_Error", func(t *testing.T) {
|
||||
credPath := createTestCredentialsFile(t)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"test-token","expires_in":3600,"token_type":"Bearer"}`))
|
||||
case strings.Contains(r.URL.Path, ":fetchCaCerts"):
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte(`{"error":{"code":403,"message":"Permission denied","status":"PERMISSION_DENIED"}}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
_, err := connector.GetCACertPEM(ctx)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for permission denied")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GetRenewalInfo_ReturnsNil", func(t *testing.T) {
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
result, err := connector.GetRenewalInfo(ctx, "-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
|
||||
if err != nil {
|
||||
t.Fatalf("GetRenewalInfo should not return error, got: %v", err)
|
||||
}
|
||||
if result != nil {
|
||||
t.Fatal("GetRenewalInfo should return nil for Google CAS")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("AuthHeader_BearerToken", func(t *testing.T) {
|
||||
testCertPEM, _ := generateTestCert(t)
|
||||
credPath := createTestCredentialsFile(t)
|
||||
var authHeader string
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"access_token":"verified-token-abc","expires_in":3600,"token_type":"Bearer"}`))
|
||||
case strings.Contains(r.URL.Path, "/certificates") && r.Method == http.MethodPost:
|
||||
authHeader = r.Header.Get("Authorization")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
resp := fmt.Sprintf(`{
|
||||
"name": "projects/p/locations/l/caPools/cp/certificates/c1",
|
||||
"pemCertificate": %q,
|
||||
"pemCertificateChain": []
|
||||
}`, testCertPEM)
|
||||
w.Write([]byte(resp))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
config := &googlecas.Config{
|
||||
Project: "test-project",
|
||||
Location: "us-central1",
|
||||
CAPool: "test-pool",
|
||||
Credentials: credPath,
|
||||
TTL: "8760h",
|
||||
BaseURL: srv.URL,
|
||||
TokenURL: srv.URL + "/token",
|
||||
}
|
||||
connector := googlecas.New(config, logger)
|
||||
|
||||
_, csrPEM := generateTestCSR(t, "auth-test.example.com")
|
||||
_, err := connector.IssueCertificate(ctx, issuer.IssuanceRequest{
|
||||
CommonName: "auth-test.example.com",
|
||||
CSRPEM: csrPEM,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("IssueCertificate failed: %v", err)
|
||||
}
|
||||
|
||||
if authHeader != "Bearer verified-token-abc" {
|
||||
t.Errorf("Expected 'Bearer verified-token-abc', got '%s'", authHeader)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// createTestCredentialsFile generates a temporary service account JSON file with a test RSA key.
|
||||
func createTestCredentialsFile(t *testing.T) string {
|
||||
t.Helper()
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate RSA key: %v", err)
|
||||
}
|
||||
|
||||
keyPEM := pem.EncodeToMemory(&pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: x509.MarshalPKCS1PrivateKey(key),
|
||||
})
|
||||
|
||||
creds := map[string]interface{}{
|
||||
"type": "service_account",
|
||||
"project_id": "test-project",
|
||||
"private_key_id": "key-123",
|
||||
"private_key": string(keyPEM),
|
||||
"client_email": "certctl@test-project.iam.gserviceaccount.com",
|
||||
"token_uri": "https://oauth2.googleapis.com/token",
|
||||
}
|
||||
|
||||
data, err := json.Marshal(creds)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal credentials: %v", err)
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
credPath := filepath.Join(tmpDir, "credentials.json")
|
||||
if err := os.WriteFile(credPath, data, 0600); err != nil {
|
||||
t.Fatalf("Failed to write credentials file: %v", err)
|
||||
}
|
||||
|
||||
return credPath
|
||||
}
|
||||
|
||||
// generateTestCert creates a self-signed test certificate and returns the PEM strings.
|
||||
func generateTestCert(t *testing.T) (certPEM string, keyPEM string) {
|
||||
t.Helper()
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate key: %v", err)
|
||||
}
|
||||
|
||||
serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{
|
||||
CommonName: "Test Certificate",
|
||||
},
|
||||
NotBefore: time.Now().Add(-1 * time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
DNSNames: []string{"test.example.com"},
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
}
|
||||
|
||||
certBytes, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create certificate: %v", err)
|
||||
}
|
||||
|
||||
certPEM = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes}))
|
||||
keyPEM = string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}))
|
||||
|
||||
return certPEM, keyPEM
|
||||
}
|
||||
|
||||
// generateTestCSR creates a test CSR for the given common name.
|
||||
func generateTestCSR(t *testing.T, commonName string) (*x509.CertificateRequest, string) {
|
||||
t.Helper()
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate key: %v", err)
|
||||
}
|
||||
|
||||
csrTemplate := x509.CertificateRequest{
|
||||
Subject: pkix.Name{
|
||||
CommonName: commonName,
|
||||
},
|
||||
DNSNames: []string{commonName},
|
||||
SignatureAlgorithm: x509.SHA256WithRSA,
|
||||
}
|
||||
|
||||
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, key)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create CSR: %v", err)
|
||||
}
|
||||
|
||||
csrPEM := string(pem.EncodeToMemory(&pem.Block{
|
||||
Type: "CERTIFICATE REQUEST",
|
||||
Bytes: csrBytes,
|
||||
}))
|
||||
|
||||
csr, err := x509.ParseCertificateRequest(csrBytes)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse CSR: %v", err)
|
||||
}
|
||||
|
||||
return csr, csrPEM
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user