This commit is contained in:
Meghdad committed 2026-07-12 23:06:00 +03:30
commit eb115daf3b
76 files changed
+22739

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
test:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.26.x'
cache: true
- run: go test ./...
- run: go test -race ./...
- run: go vet ./...
- run: go build -trimpath ./cmd/domainops
release-config:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: '~> v2'
args: check
cross-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.26.x'
cache: true
- name: Build supported targets
shell: bash
run: |
for os in linux darwin; do
for arch in amd64 arm64; do
CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" go build -trimpath -o "build/domainops-$os-$arch" ./cmd/domainops
done
done
+43
View File
@@ -0,0 +1,43 @@
name: Release
on:
push:
tags:
- 'v*'
permissions:
contents: read
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.26.x'
cache: true
- run: go test ./...
- run: go vet ./...
- run: go build -trimpath ./cmd/domainops
release:
needs: verify
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-go@v5
with:
go-version: '1.26.x'
cache: true
- uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: '~> v2'
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+12
View File
@@ -0,0 +1,12 @@
/.domainops/
/bin/
/build/
/coverage/
/dist/
*.log
*.out
.DS_Store
.idea/
.env
.env.*
!.env.example
+31
View File
@@ -0,0 +1,31 @@
version: 2
project_name: domainops
builds:
- id: domainops
main: ./cmd/domainops
binary: domainops
env:
- CGO_ENABLED=0
goos:
- darwin
- linux
goarch:
- amd64
- arm64
ldflags:
- -s -w
- -X github.com/MeghdadFadaee/domainops/internal/buildinfo.Version={{.Version}}
- -X github.com/MeghdadFadaee/domainops/internal/buildinfo.Commit={{.Commit}}
- -X github.com/MeghdadFadaee/domainops/internal/buildinfo.Date={{.Date}}
archives:
- formats: [tar.gz]
name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
checksum:
name_template: checksums.txt
changelog:
sort: asc
+21
View File
@@ -0,0 +1,21 @@
# Changelog
## Unreleased
- Initial DomainOps implementation.
- Multi-account Cloudflare inventory and DNS management.
- Cloudflare core TLS controls and edge certificate inventory.
- Let’s Encrypt DNS-01 wildcard issuance, renewal, revocation primitives, import, and export.
- Isolated staging/production certificate lineages, transactional version activation, and durable revocation-intent recovery.
- Encrypted local vault, durable SQLite jobs, crash-safe challenge cleanup, and audit history.
- Background public TLS observations and actionable dashboard findings.
- Bubble Tea v2 TUI plus essential JSON CLI commands.
- Safe DNS batch preview/apply, stable overlapping-token routing, and remote-change conflict detection.
- Streaming per-certificate persistence for large batches, CAA/routing preflight, ARI scheduling, and durable revocation state.
- Intent-first DNS-01 recovery tied to the exact Cloudflare credential.
- Power-loss-durable certificate commit journals, deterministic orphan cleanup, and fail-closed recovery health guards.
- Reconciled single-record DNS outcomes and field-masked Cloudflare TLS updates with remote-conflict detection.
- Self-contained headless data directories, stable JSON envelopes, and documented automation exit statuses.
- Crash-durable ACME account-key commits, idempotent explicit exports, and stricter private-path validation.
- Per-zone DNS authority invalidation, nested endpoint ownership, and a forward migration for legacy endpoint duplicates.
- Zone-bound TLS drafts, blocked-recovery retry, undersized-terminal input safety, and ambiguity-safe certificate forms.
+35
View File
@@ -0,0 +1,35 @@
.PHONY: build test race lint fmt check snapshot clean
APP := domainops
VERSION ?= dev
COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
DATE ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
LDFLAGS := -s -w \
-X github.com/MeghdadFadaee/domainops/internal/buildinfo.Version=$(VERSION) \
-X github.com/MeghdadFadaee/domainops/internal/buildinfo.Commit=$(COMMIT) \
-X github.com/MeghdadFadaee/domainops/internal/buildinfo.Date=$(DATE)
build:
go build -trimpath -ldflags "$(LDFLAGS)" -o bin/$(APP) ./cmd/domainops
test:
go test ./...
race:
go test -race ./...
fmt:
gofmt -w $$(find cmd internal -name '*.go' -type f)
lint:
go vet ./...
check:
$(MAKE) lint
go test ./...
snapshot:
goreleaser release --snapshot --clean
clean:
rm -rf bin build coverage dist
+221
View File
@@ -0,0 +1,221 @@
# DomainOps
DomainOps is a local-first terminal console for managing domains, DNS, Cloudflare TLS, and locally owned ACME certificates. It is designed for operators with many zones across multiple accounts and remains usable over SSH on a minimal Linux server.
The default command opens a full-screen Bubble Tea v2 interface. The same engine also exposes stable JSON commands for scripts.
## Current capabilities
- Multiple Cloudflare user-owned or account-owned API tokens.
- Background account, zone, and DNS synchronization with a durable SQLite cache.
- Read visibility for every Cloudflare DNS record type.
- Structured create/edit support for A, AAAA, CNAME, TXT, MX, CAA, NS, and SRV records.
- Re-fetch-before-write conflict detection, managed-record protection, confirmation dialogs, and best-effort local audit history.
- Zone-scoped DNS batch preview/apply with fresh validation and full cache reconciliation.
- Cloudflare SSL mode, Always Use HTTPS, minimum TLS, TLS 1.3, proxied-DNS status, and edge certificate inventory support.
- Separate Let’s Encrypt staging and production accounts.
- Separate staging and production lineages and `current` links, so a staging test can never replace a production artifact.
- Apex-plus-wildcard certificates, nested wildcard pairs, EC P-256 or RSA 2048 keys, and batches capped at three concurrent ACME orders.
- Crash-safe DNS-01 journaling that removes only TXT records created by the exact job.
- ARI renewal windows and `replaces` identifiers for qualifying renewals.
- Active-zone, explicit credential routing, per-zone read-probed DNS access, and advisory cached CAA preflight before every ACME order.
- Versioned, integrity-checked PEM storage and export: `cert.pem`, `chain.pem`, `fullchain.pem`, `privkey.pem`, and `metadata.json`; pending or revoked certificates are never re-exported as deployable material.
- Metadata-only PEM import without private keys.
- Background public DNS/TLS observations that compare the served certificate with the locally managed fingerprint.
- An encrypted XChaCha20-Poly1305 vault with Argon2id password wrapping and optional OS-keyring auto-unlock.
- macOS and Linux support without requiring containers, a database service, or a desktop keyring.
## Build and start
Go 1.26 or newer is required when building from source.
```bash
make build
./bin/domainops
```
The first run creates a local vault. On macOS or a desktop Linux session, DomainOps can use the OS keyring as an unlock convenience. On Debian, Ubuntu Server, Arch, or another headless installation, the same binary uses the password-backed vault directly:
```bash
./bin/domainops --no-keyring
```
No root privileges are required.
## Cloudflare token setup
Use a scoped API token, never a Global API Key. Recommended permissions are:
- Zone / Zone / Read
- Zone / DNS / Read
- Zone / DNS / Write
- Zone / Zone Settings / Read and Write for Cloudflare TLS controls
- SSL and Certificates / Read for edge certificate inventory
Restrict the token to only the accounts and zones DomainOps should manage. For an account-owned token, provide its Cloudflare account ID during onboarding. A user-owned token can discover zones from multiple visible accounts.
Press `a` on the Dashboard or Accounts screen to add a token. DomainOps masks it immediately and stores it only in the encrypted vault.
Cloudflare’s token-verification response does not disclose effective write scopes. DomainOps therefore labels reads from live probes and records `dns:write`/`tls:write` only after a real mutation succeeds, scoped to that credential and zone. An authoritative later DNS-access denial removes only that zone’s read evidence and detaches the denied route; network failures, rate limits, and Cloudflare 5xx responses preserve the last known-good route. Before removing a preferred connection, perform a successful DNS operation through its replacement on every affected zone within 15 minutes; DomainOps then re-probes exact-zone DNS read access, and removal otherwise fails closed.
## TUI workflow
| Key | Action |
| --- | --- |
| `1` … `7` | Navigate sections |
| `j` / `k` | Move selection |
| `/` | Filter the current view |
| `Ctrl+K` | Open the command palette |
| `r` | Synchronize Cloudflare and run public health checks |
| `R` | Retry blocked crash recovery after correcting the underlying problem |
| `a` | Add a Cloudflare connection |
| `n`, `e`, `d` | Create, edit, or delete a DNS record |
| `n`, `u`, `i`, `x`, `d` | Issue, renew due, import, export, or revoke a certificate in the Certificates view |
| `m`, `h`, `t`, `v` | Adjust the TLS mode, HTTPS, TLS 1.3, or minimum TLS version |
| `s` | Review and apply the Cloudflare TLS diff |
| `?` | Contextual help |
| `q` | Quit and restore the terminal |
Long-running synchronization, certificate, and public endpoint jobs run outside the render loop. The TUI remains navigable while they work.
## Certificate issuance
Wildcard certificates use DNS-01. A default plan for `example.com` contains both:
```text
example.com
*.example.com
```
`*.example.com` does not cover the apex or deeper names such as `a.api.example.com`. Add the nested label `api` to include `api.example.com` and `*.api.example.com`.
Always validate a new setup against Let’s Encrypt staging first:
```bash
domainops cert account-register \
--environment staging \
--email ops@example.com \
--accept-tos
domainops cert issue \
--zone example.com \
--environment staging
```
Issue one independent wildcard lineage for every synchronized zone:
```bash
domainops cert issue \
--all \
--environment production \
--email ops@example.com \
--accept-tos \
--confirm-production
```
Production issuance always requires explicit confirmation. A large selection creates independent certificates rather than one coupled SAN certificate.
Each order first verifies the active zone, exact preferred DNS credential, and nested challenge routing, then checks read-probed DNS-access and cached CAA signals. Cloudflare enforces write permission when the challenge is created, and Let’s Encrypt performs the authoritative live DNS and CAA checks.
Renew only certificates inside their stored renewal window:
```bash
domainops cert renew --due \
--environment production \
--confirm-production
```
## Files and headless automation
Default data locations:
- macOS: `~/Library/Application Support/DomainOps`
- Linux: `$XDG_DATA_HOME/domainops` or `~/.local/share/domainops`
- Override: `--data-dir PATH` or `DOMAINOPS_DATA_DIR`
An explicit data directory is self-contained and does not require `$HOME`, which makes it suitable for systemd services and containers with a single writable mount.
Each managed certificate has immutable version directories and an atomically updated `current` symlink. Production lives under `certificates/DOMAIN`; staging is isolated under `certificates/staging/DOMAIN`. Private-key files and their parent directories are owner-only. Export retries verify every file, its metadata, permissions, and certificate/key relationship; symbolic-link path redirection and replacement of a non-symlink `current` path are rejected.
Managed version directories contain an intentionally unencrypted `privkey.pem` for server deployment. The encrypted vault also retains the key, but backups of the certificate directory must be protected as sensitive material.
For a headless command, put the vault password in an owner-only file and pass its path rather than the password itself:
```bash
chmod 600 /etc/domainops/vault-password
domainops --no-keyring \
--vault-password-file /etc/domainops/vault-password \
sync --json
```
The password is never accepted as a literal command-line flag or printed in JSON.
If crash recovery cannot clean a journaled DNS challenge, ACME account-key commit, or certificate commit, DomainOps persists a critical dashboard finding and disables mutations in both the TUI and headless commands until recovery succeeds. In the TUI, correct the underlying provider/filesystem problem and press `R` to retry without restarting.
Headless exit statuses are stable: `0` means success, `1` means the operation failed before producing any per-item result, and `3` means a multi-item operation returned per-item failures, a provider outcome was partial/unknown, or certificate metadata committed with an activation warning. Inspect the JSON result and warnings before retrying an exit-`3` operation.
Useful commands:
```bash
domainops status --json
domainops account list --json
domainops account remove CREDENTIAL_ID --confirm 'Connection label'
domainops zone list --json
domainops zone prefer example.com --credential CREDENTIAL_ID --confirm example.com
domainops dns list --zone example.com --json
domainops sync --json
domainops cert list --json
domainops cert import --file fullchain.pem --zone example.com
domainops cert export LINEAGE_ID --to ./server-certs
domainops cert revoke LINEAGE_ID --environment production --confirm example.com
domainops health check --json
```
## Safe DNS batches
Use `domainops dns list` to obtain stable local record IDs, then create a zone-scoped mutation file:
```json
{
"schema_version": 1,
"mutations": [
{
"kind": "create",
"after": {
"type": "A",
"name": "api",
"content": "192.0.2.20",
"ttl": 300,
"proxied": true
}
},
{
"kind": "delete",
"record_id": "cfrecord_REMOTE_ID"
}
]
}
```
Preview is the default and performs fresh remote reads without changing Cloudflare:
```bash
domainops dns batch --zone example.com --file changes.json --json
domainops dns batch --zone example.com --file changes.json --apply --json
```
Apply revalidates the complete plan, submits one Cloudflare zone batch, reloads the full remote zone, replaces the local cache, and attempts to record one redacted audit event. Record changes detected during revalidation fail closed; a change made after the final read but before submission can still race with apply. A lost/ambiguous provider response is returned as `outcome_unknown: true`, triggers a best-effort full refresh, and must be reviewed before retrying.
## Verification
```bash
make test
make race
make check
```
The test suite covers Cloudflare request mapping and rate-limit errors, legacy SQLite upgrades and recovery state, encrypted-vault tampering, DNS-01 exact-record cleanup, 60-order bounded ACME batches, staging/production isolation, durable account/certificate commits and revocation retry, ARI renewal replacement, PEM validation/export, public TLS findings, non-blocking worker limits, CLI JSON envelopes, and responsive TUI rendering.
Live Cloudflare and Let’s Encrypt production operations should first be exercised with a dedicated test zone and the staging CA. The automated suite never issues a real production certificate.
See [architecture](docs/architecture.md) and [security](docs/security.md) for implementation boundaries and threat-model details.
+29
View File
@@ -0,0 +1,29 @@
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/MeghdadFadaee/domainops/internal/cli"
)
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
err := cli.Execute(ctx, os.Stdout, os.Stderr, os.Args[1:])
if err == nil {
return
}
if !cli.IsReportedError(err) {
fmt.Fprintln(os.Stderr, "domainops:", err)
}
var exitErr *cli.ExitError
if errors.As(err, &exitErr) {
os.Exit(exitErr.Code)
}
os.Exit(1)
}
+83
View File
@@ -0,0 +1,83 @@
# Architecture
DomainOps is a modular monolith. It deliberately keeps network providers, certificate automation, persistence, and terminal presentation behind provider-neutral contracts so the project can grow without becoming a set of distributed services.
## Runtime flow
```text
TUI / CLI
│
Application services ───── Background health workers
│ │
Provider contracts DNS + TLS probes
│
Cloudflare REST adapter ─── ACME engine (lego)
│ │
Cloudflare API Journaled DNS-01 solver
Application services ───── SQLite metadata/cache/jobs/audit
└──── Encrypted local secret vault
```
The TUI uses unidirectional Bubble Tea messages. Rendering reads in-memory state only; it never performs HTTP, DNS, TLS, SQLite, or cryptographic work. Commands execute application use cases and send typed results back to the model.
## Provider boundaries
The provider package defines focused capabilities:
- `CredentialVerifier`
- `ZoneInventory`
- `DNSRecordService`
- `DNSBatchService`
- `DNS01Solver`
- `EdgeTLSService`
Cloudflare is the first adapter. Its wire types do not escape the adapter. Unknown DNS record JSON is retained so new provider fields remain visible even before DomainOps adds an editor for them.
Credential identities and remote accounts are separate. One user token may expose several Cloudflare accounts, while an account token belongs to one account. A zone stores an explicit preferred credential; ACME and DNS writes never silently switch credentials.
After a successful full sync, a zone no longer visible to its preferred credential is retained as cached history but marked unknown and detached from that stale preference. DNS-read authority is also stored per credential and zone. An authoritative 401/403 on a later zone read atomically removes that evidence and detaches only the denied route, while transient transport, rate-limit, and server failures preserve the last successful observation. A later credential that rediscovers the zone can restore routing without trapping credential removal behind an unreachable zone.
Future providers should implement only their supported capabilities and register statically. A future third-party plugin system should be an out-of-process, versioned protocol rather than Go’s in-process plugin mechanism.
## Persistence
SQLite stores metadata, cached zones and records, public certificate metadata, endpoint observations, durable jobs, challenge journals, commit intents, and redacted audit events. Migrations are embedded and transactional, including forward-only repair of legacy duplicate endpoint identities before host/port uniqueness is enforced. WAL with full synchronous durability, foreign keys, a busy timeout, and bounded connections are enabled at open. The full durability setting is intentional: an acknowledged recovery journal or certificate commit must survive power loss before filesystem cleanup or activation can rely on it.
The encrypted vault is a separate atomic file. SQLite stores secret references only. A random 256-bit data key encrypts the vault payload with XChaCha20-Poly1305. Argon2id derives the passphrase wrapping key. OS keyrings are optional unlock slots, not a runtime requirement.
Only one DomainOps process can open a data directory at a time. This keeps vault, migration, cache, and certificate activation semantics deterministic. An advisory lock is used on macOS and Linux and is automatically released after a crash.
## DNS changes
Single changes follow this sequence:
1. Load the cached record and explicit zone credential.
2. Re-fetch the exact remote record ID.
3. Reject provider-managed/read-only records.
4. Validate and normalize the requested record.
5. Submit the mutation.
6. Reconcile the returned provider state into SQLite.
7. Attempt to append a redacted before/after audit event.
If a single write returns an ambiguous transport/server/schema result, DomainOps records an outcome-unknown audit event, reloads the complete provider zone into SQLite, reconciles generated health endpoints, and returns an explicit do-not-retry error. A provider-confirmed write whose local reconciliation fails is reported separately as applied-but-unreconciled.
Cloudflare batches are zone-scoped. The CLI previews a normalized plan first; apply repeats every fresh-read safety check, submits the provider batch, fully reloads the zone cache, and attempts to append one audit event. Fresh reads reject changes already visible before submission, but the Cloudflare API does not make the read-and-submit pair conditional, so a later change can race with apply. Audit persistence is best-effort and cannot roll back a provider mutation. Cross-zone automation should invoke independent batches because DNS propagation cannot be atomic across zones.
TLS changes carry the displayed baseline into the Cloudflare adapter. The adapter reads all supported settings, rejects a concurrent change to any requested field before the first patch, patches only fields the operator changed, and preserves unrelated settings—including Cloudflare's distinct TLS 1.3 `zrt` mode. Any later partial or ambiguous failure triggers a live refresh, cache update, and audit finding.
## Certificate lifecycle
Each lineage is an independent order, usually containing the apex plus its one-label wildcard. The engine caps issuance at three concurrent orders.
Before an order, local preflight checks active-zone state, exact credential routing, a DNS-access capability inferred from successful read probes, and cached CAA records. Cloudflare remains authoritative for write permission, and the CA performs the authoritative live DNS and CAA checks.
DNS-01 intent is journaled before the provider write, including the exact credential, zone, job marker, owner, and hashed value. The returned provider record ID is then attached before ACME validation proceeds. Ambiguous creates are reconciled by the job marker and value hash; cleanup deletes only the exact ID and treats an already-absent record as clean. Open rows are recovered after either password or keyring unlock.
Managed certificate keys are generated fresh for issuance and renewal. ACME account keys and certificate keys are stored in the vault. Account registration journals its key before contacting the CA, then insert-only account metadata and intent closure commit in one SQLite transaction. Certificate storage similarly writes a durable commit-intent row before a key or plaintext PEM appears. PEM exports are versioned, written and synced in a deterministic temporary directory, then renamed atomically. The lineage/version rows advance and delete that intent in one SQLite transaction before the `current` symlink changes, so filesystem activation can never expose an untracked certificate. On an ambiguous commit return, the intent is re-read before any compensation; unlock recovery validates secret bindings and configured-root containment, removes journaled orphan keys and both final and temporary PEM paths, then reconciles missing or stale links from the authoritative database. Interrupted jobs are finalized only after every journal, challenge, and link repair succeeds. Recovery failures are persisted as critical health findings. Staging and production use separate lineages and export roots.
Renewal timing prefers validated ACME Renewal Information and safely falls back to a two-thirds-lifetime window. Renewals send the previous certificate’s ARI replacement identifier and retain prior versions after success. Revocation is bound to the lineage’s original ACME account. Its intent and reason are durable before the CA call; a retry that receives the standard `alreadyRevoked` response completes the local state transition instead of leaving a split-brain lineage.
## Growth path
The current application is intentionally local-first. Natural next additions are unattended renewal through systemd/launchd, notifications and deployment hooks, DNSSEC, BIND import/export, additional provider adapters, registrar lifecycle data, and finally an optional remote control plane with RBAC.
+63
View File
@@ -0,0 +1,63 @@
# Security Model
DomainOps manages credentials and private keys, so its defaults assume the local user account and operating system are trusted while backups, logs, shell history, and accidental file exposure are not.
## Protected material
The encrypted vault contains:
- Cloudflare API tokens
- Let’s Encrypt account private keys
- Managed certificate private keys
The metadata database never stores these values. JSON output, TUI views, audit events, and provider errors omit them.
The vault uses XChaCha20-Poly1305 authenticated encryption. A random data key encrypts all entries; Argon2id wraps that key with the local password. The file is replaced atomically and uses mode `0600` inside a `0700` directory.
OS keyrings may retain the random data key to provide automatic local unlock. `--no-keyring` disables this behavior. On a headless machine, a vault password is sufficient and no D-Bus/Secret Service process is required.
## Cloudflare access
Global API Keys are rejected. Use least-privilege API tokens scoped to the necessary accounts and zones. DNS issuance requires Zone Read and DNS Write. Cloudflare TLS changes require Zone Settings Write. The app verifies the token namespace and performs real read probes, which provide capability hints but cannot prove write access; Cloudflare remains authoritative for write permission enforcement. DomainOps records write capability only after a real provider mutation succeeds, scoped to that credential and zone, and credential removal requires matching evidence from the last 15 minutes.
Tokens are masked during entry. Headless use accepts a token file or vault-password file only when it is a regular file with no group/other permission bits. Literal secret flags are intentionally unavailable.
## ACME safety
- Staging is the default issuance environment.
- Production issuance requires explicit confirmation.
- The first and renewed certificate keys are generated locally.
- Wildcard validation uses DNS-01 only.
- Each challenge TXT record is stored by exact Cloudflare record ID.
- Cleanup never deletes every TXT value at `_acme-challenge`.
- Open challenge journals survive crashes and are retried after unlock.
- ACME account keys are journaled before registration and account metadata closes that intent transactionally; a losing or failed registration is compensated without replacing an existing environment account.
- Certificate commit intents survive power loss and recover orphaned vault keys and plaintext temporary/final PEM paths before normal mutations resume.
- A failed recovery is persisted as a critical health finding; application-level mutation guards remain closed until a later unlock completes recovery successfully.
- Batches are bounded to three active orders.
- Renewals preserve identifier sets and use ARI replacement IDs.
- Every order preflights active-zone state, explicit credential routing, exact per-zone read-probed DNS access, and cached CAA records. An authoritative later access denial revokes that local evidence; transient provider failures do not. The advisory CAA check rejects unknown issuer-critical properties, incompatible validation methods, and unverifiable account-only bindings. Cloudflare and the CA remain authoritative for live write permission and CAA policy.
- Staging and production use different lineages and filesystem `current` links.
- Revocation intent is persisted before contacting the CA; an `alreadyRevoked` retry safely converges local state after a prior local-write failure.
Certificate names are public through Certificate Transparency; do not put private internal hostnames into a public ACME order.
## PEM export boundary
Server-ready `privkey.pem` files are intentionally unencrypted because common web servers need to read them unattended. DomainOps creates them in the managed certificate version directory during issuance and in any explicit export destination. Both locations are owner-only; export path components and immutable files are checked against symbolic-link redirection, unsafe types, altered permissions, and material/metadata mismatches. Pending or revoked versions are refused by explicit export. Backups still contain plaintext private keys: copy them through a trusted transport such as SFTP, verify fingerprints after deployment, and remove unnecessary copies.
Metadata-only imports refuse PEM blocks containing private keys.
## Operational recommendations
- Use separate staging and production ACME accounts.
- Start with a dedicated test zone.
- Prefer one certificate lineage per registered domain.
- Keep the DomainOps data directory out of general-purpose cloud synchronization.
- Protect password files with `chmod 600` and a restricted parent directory.
- Review the local audit view before applying another change after a timeout.
- Treat a public fingerprint mismatch as “not yet deployed” until verified.
## Non-goals in the current release
DomainOps is not a multi-user secrets server, HSM client, deployment agent, or continuous monitoring service. It does not protect against a fully compromised local account, a malicious kernel, or an attacker who can read the process memory while the vault is unlocked.
+53
View File
@@ -0,0 +1,53 @@
module github.com/MeghdadFadaee/domainops
go 1.26.0
require (
charm.land/bubbles/v2 v2.1.1
charm.land/bubbletea/v2 v2.0.8
charm.land/lipgloss/v2 v2.0.5
github.com/charmbracelet/x/term v0.2.2
github.com/go-acme/lego/v5 v5.2.2
github.com/spf13/cobra v1.10.2
github.com/zalando/go-keyring v0.2.8
golang.org/x/crypto v0.54.0
golang.org/x/net v0.57.0
golang.org/x/sync v0.22.0
golang.org/x/sys v0.47.0
modernc.org/sqlite v1.53.0
)
require (
github.com/atotto/clipboard v0.1.4 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20260703014108-f5a850f9c2b7 // indirect
github.com/charmbracelet/x/ansi v0.11.7 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/danieljoos/wincred v1.2.3 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/godbus/dbus/v5 v5.2.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/mattn/go-runewidth v0.0.24 // indirect
github.com/miekg/dns v1.1.72 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/mod v0.37.0 // indirect
golang.org/x/text v0.40.0 // indirect
golang.org/x/tools v0.47.0 // indirect
modernc.org/libc v1.73.4 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
software.sslmate.com/src/go-pkcs12 v0.7.2 // indirect
)
+134
View File
@@ -0,0 +1,134 @@
charm.land/bubbles/v2 v2.1.1 h1:7r55WzBxpo/R3z98hGmY7KKPd3ET6vsf0Fb9sDHOV60=
charm.land/bubbles/v2 v2.1.1/go.mod h1:GE6M31gaWZVXzGw73OeuTTgy4lX+OtkH0E5ymnNsHxo=
charm.land/bubbletea/v2 v2.0.8 h1:SxTJMhCAI3lbPmy4SgX5LWZ24AdINr4I6UEqzZvYJuY=
charm.land/bubbletea/v2 v2.0.8/go.mod h1:2SkdgoTXluXJHOUwAoRlRXF/28vklb1rFl6GcgV1/ss=
charm.land/lipgloss/v2 v2.0.5 h1:kbNxgeeUOYv5J0YdpxFjfvf3dFvqH8Aci4zB6xqFtrY=
charm.land/lipgloss/v2 v2.0.5/go.mod h1:9oqhxt4yxIMe6q5A4kHr44DremZk7J9UNh74GlWa5nc=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o=
github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/ultraviolet v0.0.0-20260703014108-f5a850f9c2b7 h1:3FmWoGNWK4STvqg0O0Aeav2T7rodWJAPeF0QpH+8gFw=
github.com/charmbracelet/ultraviolet v0.0.0-20260703014108-f5a850f9c2b7/go.mod h1:f/jRa757WUmaOZrbPspXymbg/GnbF+rwe4OLsG7aXYo=
github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI=
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-acme/lego/v5 v5.2.2 h1:KqFas/Ak2QDdU+Qm7MO9OEnS35zC000kPmM+5tLdZKk=
github.com/go-acme/lego/v5 v5.2.2/go.mod h1:H/hb7OJKmpVGa8zypgZh0ys5P4VUu++ZNgAEcOwq+OI=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
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/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU=
github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.28.4 h1:Hd/4Es+MBj+/7hSdZaisNyu6bv3V0Dp2MdllyfqaH+c=
modernc.org/cc/v4 v4.28.4/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.4 h1:OVnSOWQjVKOYkFxoHYB+qQmSHK5gqMqARM+K9DpR/Ws=
modernc.org/ccgo/v4 v4.34.4/go.mod h1:qdKqE8FNIYyysougB1RX9MxCzp5oJOcQXSobANJ4TuE=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.3 h1:6QAplYyVO+KdPW3pGnqmJDUxtkec8ooEWvks/hhU3lc=
modernc.org/gc/v3 v3.1.3/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA=
modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M=
modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
software.sslmate.com/src/go-pkcs12 v0.7.2 h1:Rh9FoMaI5k7Oo6EOS+2/BnoZ+JFIS+XHjM0VGkSPXLM=
software.sslmate.com/src/go-pkcs12 v0.7.2/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI=
+82
View File
@@ -0,0 +1,82 @@
package app
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/MeghdadFadaee/domainops/internal/certificates"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
type CertificateInventoryItem struct {
Lineage domain.CertificateLineage `json:"lineage"`
Current *domain.CertificateVersion `json:"current,omitempty"`
Environment string `json:"environment"`
Status string `json:"status"`
}
func (s *Service) CertificateInventory(ctx context.Context) ([]CertificateInventoryItem, error) {
lineages, err := s.repo.ListCertificateLineages(ctx)
if err != nil {
return nil, err
}
environmentByAccount := make(map[string]string)
for _, environment := range []string{certificates.EnvironmentStaging, certificates.EnvironmentProduction} {
account, accountErr := s.repo.GetACMEAccountByEnvironment(ctx, environment)
if accountErr == nil {
environmentByAccount[account.ID] = environment
} else if !errors.Is(accountErr, sql.ErrNoRows) {
return nil, fmt.Errorf("load %s ACME account for inventory: %w", environment, accountErr)
}
}
now := s.now().UTC()
items := make([]CertificateInventoryItem, 0, len(lineages))
for _, lineage := range lineages {
item := CertificateInventoryItem{Lineage: lineage, Environment: environmentByAccount[lineage.ACMEAccountID], Status: "missing"}
if lineage.Source == domain.CertificateImported {
item.Environment = "external"
}
if item.Environment == "" {
item.Environment = "unknown"
}
versions, versionErr := s.repo.ListCertificateVersions(ctx, lineage.ID)
if versionErr != nil {
return nil, versionErr
}
for index := range versions {
if versions[index].ID != lineage.CurrentVersionID {
continue
}
current := versions[index]
item.Current = &current
item.Status = certificateStatus(current, now)
break
}
items = append(items, item)
}
return items, nil
}
func certificateStatus(version domain.CertificateVersion, now time.Time) string {
if version.RevokedAt != nil {
return "revoked"
}
if version.RevocationPendingAt != nil {
return "revocation-pending"
}
if !now.Before(version.NotAfter) {
return "expired"
}
due := version.RenewalWindowStart
if due == nil {
value := version.NotBefore.Add(version.NotAfter.Sub(version.NotBefore) * 2 / 3)
due = &value
}
if !now.Before(*due) {
return "due"
}
return "valid"
}
@@ -0,0 +1,30 @@
package app
import (
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
func TestCertificateStatus(t *testing.T) {
t.Parallel()
now := time.Date(2026, 7, 12, 12, 0, 0, 0, time.UTC)
notBefore, notAfter := now.Add(-60*24*time.Hour), now.Add(30*24*time.Hour)
due := now.Add(-time.Hour)
revoked := now.Add(-2 * time.Hour)
for name, fixture := range map[string]struct {
version domain.CertificateVersion
want string
}{
"valid": {domain.CertificateVersion{NotBefore: now.Add(-time.Hour), NotAfter: now.Add(89 * 24 * time.Hour)}, "valid"},
"due": {domain.CertificateVersion{NotBefore: notBefore, NotAfter: notAfter, RenewalWindowStart: &due}, "due"},
"expired": {domain.CertificateVersion{NotBefore: notBefore, NotAfter: now.Add(-time.Second)}, "expired"},
"revoked": {domain.CertificateVersion{NotBefore: notBefore, NotAfter: notAfter, RevokedAt: &revoked}, "revoked"},
"pending": {domain.CertificateVersion{NotBefore: notBefore, NotAfter: notAfter, RevocationPendingAt: &revoked}, "revocation-pending"},
} {
if got := certificateStatus(fixture.version, now); got != fixture.want {
t.Errorf("%s status = %q, want %q", name, got, fixture.want)
}
}
}
+250
View File
@@ -0,0 +1,250 @@
package app
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/MeghdadFadaee/domainops/internal/certificates"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
// CertificatePreflight validates local provider routing and cached CAA policy
// before an ACME order is created. The CA remains authoritative and performs
// its own live DNS/CAA checks; this catches deterministic operator errors early.
func (s *Service) CertificatePreflight(ctx context.Context, plan certificates.Plan) error {
zone, err := s.repo.GetZone(ctx, plan.ZoneID)
if err != nil {
return fmt.Errorf("load certificate zone: %w", err)
}
if zone.Status != domain.ZoneActive {
return fmt.Errorf("zone %s is %s; ACME issuance requires an active zone", zone.Name, zone.Status)
}
credential, err := s.repo.GetCredential(ctx, zone.PreferredCredentialID)
if err != nil {
return fmt.Errorf("load preferred DNS credential: %w", err)
}
if credential.Status != domain.CredentialValid {
return fmt.Errorf("preferred DNS credential %q is %s", credential.Label, credential.Status)
}
seenOwners := make(map[string]struct{})
for _, identifier := range plan.Identifiers {
base := strings.TrimPrefix(identifier, "*.")
owner := "_acme-challenge." + base + "."
if _, duplicate := seenOwners[owner]; duplicate {
continue
}
seenOwners[owner] = struct{}{}
auth, providerZoneID, resolveErr := s.ResolveDNS01(ctx, owner)
if resolveErr != nil {
return resolveErr
}
if auth.CredentialID == "" || providerZoneID == "" {
return fmt.Errorf("DNS-01 owner %s has no explicit zone credential", owner)
}
}
zones, err := s.repo.ListZones(ctx)
if err != nil {
return fmt.Errorf("load zones for cached CAA checks: %w", err)
}
for _, identifier := range plan.Identifiers {
base := strings.ToLower(strings.TrimPrefix(identifier, "*."))
var ancestors []domain.Zone
for index := range zones {
name := strings.ToLower(strings.TrimSuffix(zones[index].Name, "."))
if base != name && !strings.HasSuffix(base, "."+name) {
continue
}
ancestors = append(ancestors, zones[index])
}
if len(ancestors) == 0 {
return fmt.Errorf("no configured zone owns CAA lookup for %s", identifier)
}
rootZone := ancestors[0]
var records []domain.DNSRecord
for _, ancestor := range ancestors {
if len(ancestor.Name) < len(rootZone.Name) {
rootZone = ancestor
}
values, recordErr := s.repo.ListDNSRecords(ctx, ancestor.ID)
if recordErr != nil {
return fmt.Errorf("load cached CAA records for %s: %w", ancestor.Name, recordErr)
}
records = append(records, values...)
}
if caaErr := validateLetsEncryptCAA(rootZone.Name, []string{identifier}, records); caaErr != nil {
return caaErr
}
}
return nil
}
type caaDirective struct {
flags uint8
tag string
value string
}
func validateLetsEncryptCAA(zoneName string, identifiers []string, records []domain.DNSRecord) error {
byOwner := make(map[string][]caaDirective)
for _, record := range records {
if record.Type != domain.RecordCAA {
continue
}
directive, ok := parseCAADirective(record)
if !ok {
continue
}
owner := strings.ToLower(strings.TrimSuffix(record.Name, "."))
byOwner[owner] = append(byOwner[owner], directive)
}
zoneName = strings.ToLower(strings.TrimSuffix(zoneName, "."))
for _, identifier := range identifiers {
wildcard := strings.HasPrefix(identifier, "*.")
name := strings.ToLower(strings.TrimPrefix(strings.TrimSuffix(identifier, "."), "*."))
var directives []caaDirective
for current := name; ; current = parentDNSName(current) {
if values := byOwner[current]; len(values) > 0 {
directives = values
break
}
if current == zoneName || !strings.HasSuffix(current, "."+zoneName) {
break
}
}
if len(directives) == 0 {
continue
}
for _, directive := range directives {
if directive.flags&128 != 0 && !knownCAAPropertyTag(directive.tag) {
return fmt.Errorf("CAA policy for %s contains unknown issuer-critical tag %q", identifier, directive.tag)
}
}
tag := "issue"
if wildcard {
for _, directive := range directives {
if directive.tag == "issuewild" {
tag = "issuewild"
break
}
}
}
relevant, allowed := 0, false
var methodRestricted, accountRestricted bool
for _, directive := range directives {
if directive.tag != tag {
continue
}
relevant++
issuer, parameters, valid := parseCAAIssueValue(directive.value)
if !valid || !strings.EqualFold(issuer, "letsencrypt.org") {
continue
}
if methods, constrained := parameters["validationmethods"]; constrained && !containsCAAParameterValue(methods, "dns-01") {
methodRestricted = true
continue
}
// The engine preflight hook receives only a certificate plan, not the
// selected ACME account. It therefore cannot safely prove that an
// account-bound authorization applies. A separate unrestricted
// letsencrypt.org property may still authorize this DNS-01 order.
if _, constrained := parameters["accounturi"]; constrained {
accountRestricted = true
continue
}
allowed = true
}
if relevant > 0 && !allowed {
if accountRestricted {
return fmt.Errorf("CAA policy for %s authorizes letsencrypt.org only through accounturi, which cannot be verified before the ACME account is selected", identifier)
}
if methodRestricted {
return fmt.Errorf("CAA policy for %s does not authorize letsencrypt.org with validationmethods=dns-01 via %s", identifier, tag)
}
return fmt.Errorf("CAA policy for %s does not authorize letsencrypt.org via %s", identifier, tag)
}
}
return nil
}
func knownCAAPropertyTag(tag string) bool {
switch strings.ToLower(strings.TrimSpace(tag)) {
case "issue", "issuewild", "iodef":
return true
default:
return false
}
}
// parseCAAIssueValue returns an issuer domain and the RFC 8657 parameters used
// by DomainOps. Unknown parameters remain present but authoritative handling is
// deliberately left to the CA.
func parseCAAIssueValue(value string) (string, map[string][]string, bool) {
value = strings.TrimSpace(value)
if unquoted, err := strconv.Unquote(value); err == nil {
value = unquoted
}
parts := strings.Split(value, ";")
issuer := strings.TrimSuffix(strings.TrimSpace(parts[0]), ".")
parameters := make(map[string][]string)
for _, raw := range parts[1:] {
raw = strings.TrimSpace(raw)
if raw == "" {
return issuer, parameters, false
}
name, parameterValue, found := strings.Cut(raw, "=")
name = strings.ToLower(strings.TrimSpace(name))
parameterValue = strings.TrimSpace(parameterValue)
if !found || name == "" || parameterValue == "" {
return issuer, parameters, false
}
parameters[name] = append(parameters[name], parameterValue)
}
return issuer, parameters, true
}
func containsCAAParameterValue(values []string, wanted string) bool {
for _, value := range values {
for _, candidate := range strings.Split(value, ",") {
if strings.EqualFold(strings.TrimSpace(candidate), wanted) {
return true
}
}
}
return false
}
func parseCAADirective(record domain.DNSRecord) (caaDirective, bool) {
var structured struct {
Flags uint8 `json:"flags"`
Tag string `json:"tag"`
Value string `json:"value"`
}
if len(record.Data) > 0 && string(record.Data) != "null" && json.Unmarshal(record.Data, &structured) == nil && structured.Tag != "" {
return caaDirective{flags: structured.Flags, tag: strings.ToLower(structured.Tag), value: structured.Value}, true
}
parts := strings.Fields(record.Content)
if len(parts) < 3 {
return caaDirective{}, false
}
flags, err := strconv.ParseUint(parts[0], 10, 8)
if err != nil {
return caaDirective{}, false
}
value := strings.Join(parts[2:], " ")
if unquoted, err := strconv.Unquote(value); err == nil {
value = unquoted
}
return caaDirective{flags: uint8(flags), tag: strings.ToLower(parts[1]), value: value}, true
}
func parentDNSName(name string) string {
if index := strings.IndexByte(name, '.'); index >= 0 {
return name[index+1:]
}
return ""
}
+165
View File
@@ -0,0 +1,165 @@
package app
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/certificates"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
func TestLetsEncryptCAAPreflightHonorsWildcardOverride(t *testing.T) {
t.Parallel()
records := []domain.DNSRecord{{
Type: domain.RecordCAA, Name: "example.com",
Data: mustJSON(t, map[string]any{"flags": 0, "tag": "issue", "value": "letsencrypt.org"}),
}, {
Type: domain.RecordCAA, Name: "example.com",
Data: mustJSON(t, map[string]any{"flags": 0, "tag": "issuewild", "value": "other-ca.example"}),
}}
err := validateLetsEncryptCAA("example.com", []string{"example.com", "*.example.com"}, records)
if err == nil || !strings.Contains(err.Error(), "issuewild") {
t.Fatalf("wildcard CAA error = %v", err)
}
records[1].Data = mustJSON(t, map[string]any{"flags": 0, "tag": "issuewild", "value": "letsencrypt.org; validationmethods=dns-01"})
if err := validateLetsEncryptCAA("example.com", []string{"example.com", "*.example.com"}, records); err != nil {
t.Fatal(err)
}
}
func TestLetsEncryptCAAPreflightUsesClosestAncestorAndQuotedContent(t *testing.T) {
t.Parallel()
records := []domain.DNSRecord{
{Type: domain.RecordCAA, Name: "example.com", Content: `0 issue "other-ca.example"`},
{Type: domain.RecordCAA, Name: "api.example.com", Content: `0 issue "letsencrypt.org"`},
}
if err := validateLetsEncryptCAA("example.com", []string{"api.example.com", "*.api.example.com"}, records); err != nil {
t.Fatal(err)
}
if err := validateLetsEncryptCAA("example.com", []string{"www.example.com"}, records); err == nil {
t.Fatal("parent CAA denial was ignored")
}
}
func TestLetsEncryptCAAPreflightHonorsDNS01MethodBinding(t *testing.T) {
t.Parallel()
record := domain.DNSRecord{
Type: domain.RecordCAA, Name: "example.com",
Content: `0 issue "letsencrypt.org; validationmethods=http-01,tls-alpn-01"`,
}
if err := validateLetsEncryptCAA("example.com", []string{"example.com"}, []domain.DNSRecord{record}); err == nil || !strings.Contains(err.Error(), "validationmethods=dns-01") {
t.Fatalf("non-DNS method binding error = %v", err)
}
record.Content = `0 issue "letsencrypt.org; validationmethods=http-01,dns-01"`
if err := validateLetsEncryptCAA("example.com", []string{"example.com"}, []domain.DNSRecord{record}); err != nil {
t.Fatalf("DNS-01 method binding was rejected: %v", err)
}
}
func TestLetsEncryptCAAPreflightRejectsUnknownCriticalProperty(t *testing.T) {
t.Parallel()
records := []domain.DNSRecord{
{Type: domain.RecordCAA, Name: "example.com", Content: `0 issue "letsencrypt.org"`},
{Type: domain.RecordCAA, Name: "example.com", Content: `128 futurepolicy "required"`},
}
if err := validateLetsEncryptCAA("example.com", []string{"example.com"}, records); err == nil || !strings.Contains(err.Error(), "unknown issuer-critical tag") {
t.Fatalf("unknown critical property error = %v", err)
}
records[1].Content = `0 futurepolicy "advisory"`
if err := validateLetsEncryptCAA("example.com", []string{"example.com"}, records); err != nil {
t.Fatalf("noncritical unknown property was rejected: %v", err)
}
records[1].Content = `128 iodef "mailto:security@example.com"`
if err := validateLetsEncryptCAA("example.com", []string{"example.com"}, records); err != nil {
t.Fatalf("known critical property was rejected: %v", err)
}
}
func TestLetsEncryptCAAPreflightFailsClosedForUnverifiableAccountBinding(t *testing.T) {
t.Parallel()
bound := domain.DNSRecord{
Type: domain.RecordCAA, Name: "example.com",
Content: `0 issue "letsencrypt.org; accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/123"`,
}
if err := validateLetsEncryptCAA("example.com", []string{"example.com"}, []domain.DNSRecord{bound}); err == nil || !strings.Contains(err.Error(), "accounturi") {
t.Fatalf("unverifiable account binding error = %v", err)
}
unrestricted := domain.DNSRecord{Type: domain.RecordCAA, Name: "example.com", Content: `0 issue "letsencrypt.org"`}
if err := validateLetsEncryptCAA("example.com", []string{"example.com"}, []domain.DNSRecord{bound, unrestricted}); err != nil {
t.Fatalf("unrestricted alternative did not authorize issuance: %v", err)
}
}
func TestCertificatePreflightUsesExplicitZoneCredentialAndCachedCAA(t *testing.T) {
ctx := context.Background()
service, repository, zone := newBatchTestService(t, newFakeCloudProvider())
plan, err := certificates.NewWildcardPlan(zone.ID, zone.Name)
if err != nil {
t.Fatal(err)
}
if err := service.CertificatePreflight(ctx, plan); err != nil {
t.Fatal(err)
}
records, err := service.DNSRecords(ctx, zone.ID)
if err != nil {
t.Fatal(err)
}
records = append(records, domain.DNSRecord{ID: "cfrecord_caa", ProviderID: "caa", ZoneID: zone.ID, Type: domain.RecordCAA, Name: zone.Name, Content: `0 issue "other-ca.example"`, TTL: 300})
if err := repository.ReplaceDNSRecords(ctx, zone.ID, records, time.Now()); err != nil {
t.Fatal(err)
}
if err := service.CertificatePreflight(ctx, plan); err == nil || !strings.Contains(err.Error(), "does not authorize") {
t.Fatalf("CAA denial preflight error = %v", err)
}
}
func TestCertificatePreflightUsesPerZoneDNSReadWhenGlobalFirstZoneProbeWasDenied(t *testing.T) {
ctx := context.Background()
fake := newFakeCloudProvider()
fake.zoneReadOnlyVerification = true // no credential-global dns:read claim
fake.zones = []domain.Zone{
{ID: "zone-denied", ProviderID: "zone-denied", Provider: domain.ProviderCloudflare, AccountID: "account-provider", Name: "denied.example", Status: domain.ZoneActive},
{ID: "zone-allowed", ProviderID: "zone-allowed", Provider: domain.ProviderCloudflare, AccountID: "account-provider", Name: "allowed.example", Status: domain.ZoneActive},
}
fake.dnsReadDenied = map[string]map[string]bool{"scoped-token": {"zone-denied": true}}
service, repository := newUnsyncedProviderService(t, fake)
credential, err := service.AddCloudflareCredential(ctx, AddCredentialInput{Label: "Scoped", Token: "scoped-token", Kind: domain.CredentialUserToken})
if err != nil {
t.Fatal(err)
}
if _, err := service.SyncCredential(ctx, credential.ID); err == nil {
t.Fatal("partially denied fixture sync unexpectedly succeeded")
}
zones, err := repository.ListZones(ctx)
if err != nil {
t.Fatal(err)
}
var allowed domain.Zone
for _, zone := range zones {
if zone.Name == "allowed.example" {
allowed = zone
}
}
if allowed.ID == "" || allowed.PreferredCredentialID != credential.ID {
t.Fatalf("allowed zone routing = %#v", allowed)
}
plan, err := certificates.NewWildcardPlan(allowed.ID, allowed.Name)
if err != nil {
t.Fatal(err)
}
if err := service.CertificatePreflight(ctx, plan); err != nil {
t.Fatalf("per-zone-authorized certificate preflight failed: %v", err)
}
}
func mustJSON(t *testing.T, value any) json.RawMessage {
t.Helper()
encoded, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
return encoded
}
+741
View File
@@ -0,0 +1,741 @@
package app
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/MeghdadFadaee/domainops/internal/certificates"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/identifier"
"github.com/MeghdadFadaee/domainops/internal/store"
"golang.org/x/sync/errgroup"
)
type CertificateService struct {
Repository store.Repository
Secrets store.SecretStore
Engine *certificates.Engine
Lifecycle *certificates.Lifecycle
ExportRoot string
Now func() time.Time
}
type IssueZonesRequest struct {
ZoneIDs []string
NestedNames []string
Environment string
Email string
AcceptTerms bool
ConfirmProduction bool
KeyAlgorithm domain.KeyAlgorithm
}
type IssueZonesResult struct {
Completed []certificates.CommitResult `json:"completed"`
Failed []IssueFailure `json:"failed"`
}
func (r IssueZonesResult) WarningCount() int {
total := 0
for _, commit := range r.Completed {
total += len(commit.Warnings)
}
return total
}
type IssueFailure struct {
ZoneID string `json:"zone_id"`
Name string `json:"name"`
Error string `json:"error"`
}
func NewCertificateService(repository store.Repository, secrets store.SecretStore, engine *certificates.Engine, exportRoot string) *CertificateService {
return &CertificateService{
Repository: repository,
Secrets: secrets,
Engine: engine,
Lifecycle: &certificates.Lifecycle{Repository: repository, Secrets: secrets},
ExportRoot: exportRoot,
Now: time.Now,
}
}
func (s *CertificateService) RegisterAccount(ctx context.Context, environment, email string, acceptTerms bool) (domain.ACMEAccount, error) {
if s == nil || s.Engine == nil {
return domain.ACMEAccount{}, errors.New("certificate service is not configured")
}
if existing, err := s.Repository.GetACMEAccountByEnvironment(ctx, environment); err == nil {
return domain.ACMEAccount{}, fmt.Errorf("a %s ACME account already exists (%s); account replacement is intentionally not automatic", environment, existing.Email)
} else if !errors.Is(err, sql.ErrNoRows) {
return domain.ACMEAccount{}, err
}
return s.Engine.Accounts().Register(ctx, certificates.RegisterAccountRequest{
Environment: environment, Email: email, TermsOfServiceAgreed: acceptTerms,
})
}
func (s *CertificateService) IssueZones(ctx context.Context, request IssueZonesRequest) (IssueZonesResult, error) {
if s == nil || s.Repository == nil || s.Engine == nil || s.Lifecycle == nil {
return IssueZonesResult{}, errors.New("certificate service is not configured")
}
if len(request.ZoneIDs) == 0 {
return IssueZonesResult{}, errors.New("at least one zone is required")
}
if request.Environment == "" {
request.Environment = certificates.EnvironmentStaging
}
if request.KeyAlgorithm == "" {
request.KeyAlgorithm = domain.KeyECDSAP256
}
account, err := s.Repository.GetACMEAccountByEnvironment(ctx, request.Environment)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) || strings.TrimSpace(request.Email) == "" {
return IssueZonesResult{}, fmt.Errorf("load %s ACME account (register it first or provide --email): %w", request.Environment, err)
}
account, err = s.RegisterAccount(ctx, request.Environment, request.Email, request.AcceptTerms)
if err != nil {
return IssueZonesResult{}, err
}
}
lineages, err := s.Repository.ListCertificateLineages(ctx)
if err != nil {
return IssueZonesResult{}, err
}
existing := make(map[string]domain.CertificateLineage)
for _, lineage := range lineages {
if lineage.Source == domain.CertificateManaged && lineage.ZoneID != "" {
existing[certificateLineageKey(lineage.ZoneID, lineage.ACMEAccountID)] = lineage
}
}
type workItem struct {
zone domain.Zone
plan certificates.Plan
job domain.Job
}
items := make([]workItem, 0, len(request.ZoneIDs))
seen := make(map[string]struct{})
for _, zoneID := range request.ZoneIDs {
if _, duplicate := seen[zoneID]; duplicate {
continue
}
seen[zoneID] = struct{}{}
zone, zoneErr := s.Repository.GetZone(ctx, zoneID)
if zoneErr != nil {
return IssueZonesResult{}, fmt.Errorf("load zone %s: %w", zoneID, zoneErr)
}
plan, planErr := certificates.NewWildcardPlan(zone.ID, zone.Name, request.NestedNames...)
if planErr != nil {
return IssueZonesResult{}, planErr
}
plan.KeyAlgorithm = request.KeyAlgorithm
now := s.now().UTC()
payload, _ := json.Marshal(map[string]any{"environment": request.Environment, "plan": plan})
job := domain.Job{ID: identifier.New("job"), Kind: "certificate.issue", State: domain.JobRunning, ResourceID: zone.ID, Progress: 5, Message: "Preparing ACME order for " + zone.Name, Payload: payload, CreatedAt: now, StartedAt: &now, UpdatedAt: now}
if err := s.Repository.SaveJob(ctx, job); err != nil {
return IssueZonesResult{}, err
}
items = append(items, workItem{zone: zone, plan: plan, job: job})
}
type zoneOutcome struct {
commit *certificates.CommitResult
failure *IssueFailure
err error
}
outcomes := make([]zoneOutcome, len(items))
group, groupCtx := errgroup.WithContext(ctx)
group.SetLimit(3)
for index := range items {
index := index
group.Go(func() error {
item := items[index]
job := item.job
issued, issueErr := s.Engine.Issue(groupCtx, certificates.IssueRequest{
JobID: item.job.ID, Environment: request.Environment, Plan: item.plan,
ConfirmProduction: request.ConfirmProduction,
})
finished := s.now().UTC()
if issueErr != nil {
job.State, job.Progress = domain.JobFailed, 100
job.Message, job.Error = "Certificate issuance failed", issueErr.Error()
job.FinishedAt, job.UpdatedAt = &finished, finished
_ = s.Repository.SaveJob(context.WithoutCancel(groupCtx), job)
failure := IssueFailure{ZoneID: item.zone.ID, Name: item.zone.Name, Error: issueErr.Error()}
outcomes[index] = zoneOutcome{failure: &failure, err: fmt.Errorf("%s: %w", item.zone.Name, issueErr)}
return nil
}
// Once the CA has issued material, finalization must get a brief chance
// to persist it even if the caller cancels the remaining bulk job.
finalizeCtx, cancel := context.WithTimeout(context.WithoutCancel(groupCtx), 2*time.Minute)
defer cancel()
var previous *domain.CertificateLineage
if value, ok := existing[certificateLineageKey(item.zone.ID, account.ID)]; ok {
copy := value
previous = &copy
}
commit, commitErr := s.Lifecycle.CommitManaged(finalizeCtx, certificates.CommitRequest{
ExistingLineage: previous,
Plan: item.plan,
ACMEAccountID: account.ID,
Artifact: issued.Artifact,
RenewalWindow: &issued.RenewalWindow,
ExportRoot: s.managedExportRoot(request.Environment, item.zone.Name),
})
finished = s.now().UTC()
if commitErr != nil {
job.State, job.Message, job.Error = domain.JobFailed, "Certificate storage failed", commitErr.Error()
failure := IssueFailure{ZoneID: item.zone.ID, Name: item.zone.Name, Error: commitErr.Error()}
outcomes[index] = zoneOutcome{failure: &failure, err: fmt.Errorf("%s: %w", item.zone.Name, commitErr)}
} else {
job.State, job.Message = domain.JobSucceeded, "Certificate issued and stored"
if len(commit.Warnings) > 0 {
job.Message = "Certificate issued and stored with activation warning"
}
outcomes[index].commit = &commit
_ = s.Repository.AppendAudit(finalizeCtx, domain.AuditEvent{ID: identifier.New("audit"), Actor: "local-user", Action: "certificate.issue", ResourceID: commit.Lineage.ID, CreatedAt: finished})
}
job.Progress = 100
job.FinishedAt, job.UpdatedAt = &finished, finished
_ = s.Repository.SaveJob(finalizeCtx, job)
return nil
})
}
groupErr := group.Wait()
result := IssueZonesResult{}
var failures []error
for _, outcome := range outcomes {
if outcome.commit != nil {
result.Completed = append(result.Completed, *outcome.commit)
}
if outcome.failure != nil {
result.Failed = append(result.Failed, *outcome.failure)
}
if outcome.err != nil {
failures = append(failures, outcome.err)
}
}
if groupErr != nil {
failures = append(failures, groupErr)
}
return result, errors.Join(failures...)
}
func (s *CertificateService) RenewDue(ctx context.Context, environment string, confirmProduction bool) (IssueZonesResult, error) {
if environment == "" {
environment = certificates.EnvironmentProduction
}
account, err := s.Repository.GetACMEAccountByEnvironment(ctx, environment)
if err != nil {
return IssueZonesResult{}, fmt.Errorf("load %s ACME account: %w", environment, err)
}
lineages, err := s.Repository.ListCertificateLineages(ctx)
if err != nil {
return IssueZonesResult{}, err
}
now := s.now()
type renewalItem struct {
lineage domain.CertificateLineage
version domain.CertificateVersion
zone domain.Zone
certificatePEM []byte
}
var items []renewalItem
for _, lineage := range lineages {
if lineage.Source != domain.CertificateManaged || lineage.CurrentVersionID == "" || lineage.ACMEAccountID != account.ID {
continue
}
versions, versionErr := s.Repository.ListCertificateVersions(ctx, lineage.ID)
if versionErr != nil {
return IssueZonesResult{}, versionErr
}
for _, version := range versions {
if version.ID != lineage.CurrentVersionID {
continue
}
if version.RevokedAt != nil || version.RevocationPendingAt != nil {
continue
}
due := version.RenewalWindowStart
if due == nil {
value := version.NotBefore.Add(version.NotAfter.Sub(version.NotBefore) * 2 / 3)
due = &value
}
if !now.Before(*due) {
zone, zoneErr := s.Repository.GetZone(ctx, lineage.ZoneID)
if zoneErr != nil {
return IssueZonesResult{}, fmt.Errorf("load renewal zone for %s: %w", lineage.Name, zoneErr)
}
certificatePEM, readErr := os.ReadFile(version.CertificatePath)
if readErr != nil {
return IssueZonesResult{}, fmt.Errorf("read current certificate for %s: %w", lineage.Name, readErr)
}
items = append(items, renewalItem{lineage: lineage, version: version, zone: zone, certificatePEM: certificatePEM})
}
}
}
if len(items) == 0 {
return IssueZonesResult{}, nil
}
result := IssueZonesResult{}
var resultMu sync.Mutex
var failures []error
group, groupCtx := errgroup.WithContext(ctx)
group.SetLimit(3)
for _, current := range items {
item := current
group.Go(func() error {
started := s.now()
job := domain.Job{ID: identifier.New("job"), Kind: "certificate.renew", State: domain.JobRunning, ResourceID: item.zone.ID, Progress: 5, Message: "Renewing " + item.lineage.Name, CreatedAt: started, StartedAt: &started, UpdatedAt: started}
if saveErr := s.Repository.SaveJob(groupCtx, job); saveErr != nil {
return saveErr
}
plan := certificates.Plan{Name: item.lineage.Name, ZoneID: item.zone.ID, ZoneName: item.zone.Name, Identifiers: slices.Clone(item.lineage.Identifiers), KeyAlgorithm: item.lineage.KeyAlgorithm, Profile: item.lineage.Profile}
issued, renewErr := s.Engine.Renew(groupCtx, certificates.RenewRequest{IssueRequest: certificates.IssueRequest{JobID: job.ID, Environment: environment, Plan: plan, ConfirmProduction: confirmProduction}, PreviousCertificatePEM: item.certificatePEM})
finished := s.now()
if renewErr != nil {
job.State, job.Progress, job.Message, job.Error = domain.JobFailed, 100, "Certificate renewal failed", renewErr.Error()
job.FinishedAt, job.UpdatedAt = &finished, finished
_ = s.Repository.SaveJob(context.Background(), job)
resultMu.Lock()
result.Failed = append(result.Failed, IssueFailure{ZoneID: item.zone.ID, Name: item.lineage.Name, Error: renewErr.Error()})
failures = append(failures, fmt.Errorf("%s: %w", item.lineage.Name, renewErr))
resultMu.Unlock()
return nil
}
finalizeCtx, cancel := context.WithTimeout(context.WithoutCancel(groupCtx), 2*time.Minute)
defer cancel()
exportRoot := s.managedExportRoot(environment, item.zone.Name)
if item.version.ExportPath != "" {
exportRoot = filepath.Dir(item.version.ExportPath)
}
commit, commitErr := s.Lifecycle.CommitManaged(finalizeCtx, certificates.CommitRequest{ExistingLineage: &item.lineage, Plan: plan, ACMEAccountID: account.ID, Artifact: issued.Artifact, RenewalWindow: &issued.RenewalWindow, ExportRoot: exportRoot})
if commitErr != nil {
job.State, job.Message, job.Error = domain.JobFailed, "Certificate renewal storage failed", commitErr.Error()
resultMu.Lock()
result.Failed = append(result.Failed, IssueFailure{ZoneID: item.zone.ID, Name: item.lineage.Name, Error: commitErr.Error()})
failures = append(failures, fmt.Errorf("%s: %w", item.lineage.Name, commitErr))
resultMu.Unlock()
} else {
job.State, job.Message = domain.JobSucceeded, "Certificate renewed and stored"
if len(commit.Warnings) > 0 {
job.Message = "Certificate renewed and stored with activation warning"
}
_ = s.Repository.AppendAudit(finalizeCtx, domain.AuditEvent{ID: identifier.New("audit"), Actor: "local-user", Action: "certificate.renew", ResourceID: commit.Lineage.ID, CreatedAt: finished})
resultMu.Lock()
result.Completed = append(result.Completed, commit)
resultMu.Unlock()
}
job.Progress, job.FinishedAt, job.UpdatedAt = 100, &finished, finished
_ = s.Repository.SaveJob(finalizeCtx, job)
return nil
})
}
if groupErr := group.Wait(); groupErr != nil {
failures = append(failures, groupErr)
}
return result, errors.Join(failures...)
}
func (s *CertificateService) ImportMetadata(ctx context.Context, path, name, zoneID string) (domain.CertificateLineage, domain.CertificateVersion, error) {
data, err := os.ReadFile(path)
if err != nil {
return domain.CertificateLineage{}, domain.CertificateVersion{}, fmt.Errorf("read certificate: %w", err)
}
lineage, version, err := certificates.ImportMetadata("", name, zoneID, data, s.now())
if err != nil {
return domain.CertificateLineage{}, domain.CertificateVersion{}, err
}
dir := filepath.Join(s.ExportRoot, "imported", lineage.ID)
certificatePath := filepath.Join(dir, version.ID+".pem")
intent := domain.CertificateCommitIntent{
VersionID: version.ID, LineageID: lineage.ID,
ArtifactPath: certificatePath, CreatedAt: s.now(),
}
if err := s.Repository.SaveCertificateCommitIntent(ctx, intent); err != nil {
return domain.CertificateLineage{}, domain.CertificateVersion{}, fmt.Errorf("journal imported certificate: %w", err)
}
cleanup := func(importErr error) (domain.CertificateLineage, domain.CertificateVersion, error) {
cleanupErr := certificates.CleanupCertificateCommitIntent(context.WithoutCancel(ctx), s.Lifecycle.Repository, s.Secrets, intent)
return domain.CertificateLineage{}, domain.CertificateVersion{}, errors.Join(importErr, cleanupErr)
}
if err := certificates.EnsurePrivateDirectoryDurable(dir); err != nil {
return cleanup(err)
}
if err := writeSyncedPrivateFile(certificatePath, data); err != nil {
return cleanup(err)
}
version.CertificatePath = certificatePath
auditAction := "certificate.import_metadata"
if persistErr := s.Lifecycle.PersistImportedMetadata(ctx, lineage, version); persistErr != nil {
pending, inspectErr := certificates.CertificateCommitIntentPending(context.WithoutCancel(ctx), s.Lifecycle.Repository, version.ID)
if inspectErr != nil {
// The transaction may have committed. Preserve the journal and PEM so
// startup recovery can resolve the outcome without destroying a live
// imported certificate.
return domain.CertificateLineage{}, domain.CertificateVersion{}, errors.Join(
fmt.Errorf("imported certificate commit outcome is unknown; artifact was preserved: %w", persistErr),
fmt.Errorf("inspect certificate commit journal: %w", inspectErr),
)
}
if pending {
return cleanup(persistErr)
}
auditAction = "certificate.import_metadata.commit_reconciled"
}
_ = s.Repository.AppendAudit(ctx, domain.AuditEvent{ID: identifier.New("audit"), Actor: "local-user", Action: auditAction, ResourceID: lineage.ID, CreatedAt: s.now()})
return lineage, version, nil
}
func writeSyncedPrivateFile(path string, data []byte) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
}
ok := false
defer func() {
_ = file.Close()
if !ok {
_ = os.Remove(path)
}
}()
if _, err := file.Write(data); err != nil {
return err
}
if err := file.Sync(); err != nil {
return err
}
if err := file.Close(); err != nil {
return err
}
if err := syncPrivateDirectory(filepath.Dir(path)); err != nil {
return err
}
ok = true
return nil
}
func syncPrivateDirectory(path string) error {
directory, err := os.Open(path)
if err != nil {
return err
}
defer directory.Close()
return directory.Sync()
}
func (s *CertificateService) Export(ctx context.Context, lineageID, destination string) (certificates.ExportResult, error) {
lineage, err := s.Repository.GetCertificateLineage(ctx, lineageID)
if err != nil {
return certificates.ExportResult{}, err
}
if lineage.Source != domain.CertificateManaged {
return certificates.ExportResult{}, errors.New("metadata-only certificates do not have an exportable private key")
}
versions, err := s.Repository.ListCertificateVersions(ctx, lineage.ID)
if err != nil {
return certificates.ExportResult{}, err
}
var version domain.CertificateVersion
for _, candidate := range versions {
if candidate.ID == lineage.CurrentVersionID {
version = candidate
break
}
}
if version.ID == "" {
return certificates.ExportResult{}, errors.New("current certificate version is missing")
}
if version.RevocationPendingAt != nil {
return certificates.ExportResult{}, errors.New("current certificate revocation is pending; refusing to export deployable key material")
}
if version.RevokedAt != nil {
return certificates.ExportResult{}, fmt.Errorf("current certificate was revoked at %s; refusing to export deployable key material", version.RevokedAt.UTC().Format(time.RFC3339))
}
certificatePEM, err := os.ReadFile(version.CertificatePath)
if err != nil {
return certificates.ExportResult{}, err
}
var chainPEM []byte
if version.ChainPath != "" {
chainPEM, err = os.ReadFile(version.ChainPath)
if err != nil {
return certificates.ExportResult{}, err
}
}
keyPEM, err := s.Secrets.Get(ctx, version.PrivateKeyRef)
if err != nil {
return certificates.ExportResult{}, err
}
_, _, _, metadata, err := certificates.ParseCertificatePEM(append(slices.Clone(certificatePEM), chainPEM...))
if err != nil {
return certificates.ExportResult{}, err
}
artifact := certificates.Artifact{CertificatePEM: certificatePEM, ChainPEM: chainPEM, PrivateKeyPEM: keyPEM, Metadata: metadata}
result, err := certificates.ExportVersion(filepath.Join(destination, lineage.Name), lineage, version, artifact, s.now().UTC())
if err == nil {
_ = s.Repository.AppendAudit(ctx, domain.AuditEvent{ID: identifier.New("audit"), Actor: "local-user", Action: "certificate.export", ResourceID: lineage.ID, CreatedAt: s.now()})
}
return result, err
}
// RepairManagedCurrentLinks converges filesystem convenience links from the
// authoritative lineage/version rows. It is safe to run repeatedly after a
// crash or a post-commit symlink failure.
func (s *CertificateService) RepairManagedCurrentLinks(ctx context.Context) error {
lineages, err := s.Repository.ListCertificateLineages(ctx)
if err != nil {
return err
}
var repairErrors []error
for _, lineage := range lineages {
if lineage.Source != domain.CertificateManaged || lineage.CurrentVersionID == "" {
continue
}
versions, listErr := s.Repository.ListCertificateVersions(ctx, lineage.ID)
if listErr != nil {
repairErrors = append(repairErrors, fmt.Errorf("%s: %w", lineage.Name, listErr))
continue
}
for _, version := range versions {
if version.ID != lineage.CurrentVersionID || version.ExportPath == "" {
continue
}
if activateErr := certificates.ActivateVersion(filepath.Dir(version.ExportPath), version.ID); activateErr != nil {
repairErrors = append(repairErrors, fmt.Errorf("%s: %w", lineage.Name, activateErr))
}
break
}
}
return errors.Join(repairErrors...)
}
func (s *CertificateService) Revoke(ctx context.Context, lineageID, environment, confirmation string, reason *uint) error {
lineage, err := s.Repository.GetCertificateLineage(ctx, lineageID)
if err != nil {
return err
}
if confirmation != lineage.Name {
return fmt.Errorf("revocation confirmation must exactly match %q", lineage.Name)
}
if reason != nil && (*reason > 10 || *reason == 7) {
return errors.New("revocation reason must be an RFC 5280 code from 0 through 10, excluding 7")
}
account, err := s.Repository.GetACMEAccountByEnvironment(ctx, environment)
if err != nil {
return fmt.Errorf("load %s ACME account: %w", environment, err)
}
if lineage.ACMEAccountID == "" || lineage.ACMEAccountID != account.ID {
return fmt.Errorf("certificate %q is not owned by the selected %s ACME account", lineage.Name, environment)
}
versions, err := s.Repository.ListCertificateVersions(ctx, lineage.ID)
if err != nil {
return err
}
var version domain.CertificateVersion
for _, candidate := range versions {
if candidate.ID == lineage.CurrentVersionID {
version = candidate
break
}
}
if version.ID == "" {
return errors.New("current certificate version is missing")
}
if version.RevokedAt != nil {
return fmt.Errorf("certificate %q was already revoked at %s", lineage.Name, version.RevokedAt.UTC().Format(time.RFC3339))
}
if version.RevocationPendingAt != nil && !sameRevocationReason(version.RevocationReason, reason) {
return errors.New("a revocation intent already exists with a different reason; retry with the original reason")
}
certificatePEM, err := os.ReadFile(version.CertificatePath)
if err != nil {
return err
}
now := s.now()
job := domain.Job{ID: identifier.New("job"), Kind: "certificate.revoke", State: domain.JobRunning, ResourceID: lineage.ID, Progress: 10, Message: "Revoking " + lineage.Name, CreatedAt: now, StartedAt: &now, UpdatedAt: now}
if err := s.Repository.SaveJob(ctx, job); err != nil {
return err
}
if version.RevocationPendingAt == nil {
pendingAt := now
version.RevocationPendingAt = &pendingAt
if reason != nil {
value := *reason
version.RevocationReason = &value
}
if err := s.Repository.SaveCertificateVersion(ctx, version); err != nil {
job.State, job.Progress, job.Message, job.Error = domain.JobFailed, 100, "Could not persist revocation intent", err.Error()
finished := s.now()
job.FinishedAt, job.UpdatedAt = &finished, finished
_ = s.Repository.SaveJob(context.WithoutCancel(ctx), job)
return fmt.Errorf("persist revocation intent before contacting CA: %w", err)
}
}
revokeErr := s.Engine.Revoke(ctx, certificates.RevokeRequest{Environment: environment, Lineage: lineage, CertificatePEM: certificatePEM, Reason: reason, ConfirmRevocation: true})
finished := s.now()
if revokeErr == nil || certificates.IsAlreadyRevoked(revokeErr) {
revokeErr = nil
version.RevokedAt = &finished
version.RevocationPendingAt = nil
finalizeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if saveErr := s.Repository.SaveCertificateVersion(finalizeCtx, version); saveErr != nil {
revokeErr = fmt.Errorf("certificate was revoked by the CA but local state could not be updated: %w", saveErr)
}
}
job.Progress, job.FinishedAt, job.UpdatedAt = 100, &finished, finished
if revokeErr != nil {
job.State, job.Message, job.Error = domain.JobFailed, "Certificate revocation failed", revokeErr.Error()
} else {
job.State, job.Message = domain.JobSucceeded, "Certificate revoked"
_ = s.Repository.AppendAudit(context.WithoutCancel(ctx), domain.AuditEvent{ID: identifier.New("audit"), Actor: "local-user", Action: "certificate.revoke", ResourceID: lineage.ID, CreatedAt: finished})
}
_ = s.Repository.SaveJob(context.Background(), job)
return revokeErr
}
func sameRevocationReason(left, right *uint) bool {
return (left == nil && right == nil) || (left != nil && right != nil && *left == *right)
}
func (s *CertificateService) ExpectedFingerprint(ctx context.Context, endpoint domain.ObservedEndpoint) (string, error) {
// A proxied A/AAAA/CNAME endpoint serves Cloudflare's edge certificate, not
// the locally stored origin certificate. Continue checking trust, hostname,
// and expiry at the edge, but do not raise a false stale-origin warning.
if endpoint.ZoneID != "" {
records, recordErr := s.Repository.ListDNSRecords(ctx, endpoint.ZoneID)
if recordErr != nil {
return "", recordErr
}
host := strings.ToLower(strings.TrimSuffix(endpoint.Host, "."))
for _, record := range records {
recordHost := strings.ToLower(strings.TrimSuffix(record.Name, "."))
if recordHost != host || !record.Proxied {
continue
}
if record.Type == domain.RecordA || record.Type == domain.RecordAAAA || record.Type == domain.RecordCNAME {
return "", nil
}
}
}
lineages, err := s.Repository.ListCertificateLineages(ctx)
if err != nil {
return "", err
}
host := strings.ToLower(strings.TrimSuffix(endpoint.Host, "."))
productionAccountID := ""
if account, accountErr := s.Repository.GetACMEAccountByEnvironment(ctx, certificates.EnvironmentProduction); accountErr == nil {
productionAccountID = account.ID
} else if !errors.Is(accountErr, sql.ErrNoRows) {
return "", accountErr
}
type candidate struct {
lineage domain.CertificateLineage
score int
}
var candidates []candidate
for _, lineage := range lineages {
if lineage.CurrentVersionID == "" || !identifiersCover(lineage.Identifiers, host) ||
(endpoint.ZoneID != "" && lineage.ZoneID != "" && lineage.ZoneID != endpoint.ZoneID) {
continue
}
score := identifierSpecificity(lineage.Identifiers, host)
// Imports are not always associated with a managed zone. Keep them
// eligible by identifier, but prefer an otherwise comparable lineage
// that is explicitly owned by the endpoint's zone.
if endpoint.ZoneID != "" && lineage.ZoneID == endpoint.ZoneID {
score += 25
}
if lineage.Source == domain.CertificateManaged {
score += 20
} else if lineage.Source == domain.CertificateImported {
score += 50
}
if productionAccountID != "" && lineage.ACMEAccountID == productionAccountID {
score += 100
}
candidates = append(candidates, candidate{lineage: lineage, score: score})
}
sort.SliceStable(candidates, func(i, j int) bool {
if candidates[i].score != candidates[j].score {
return candidates[i].score > candidates[j].score
}
return candidates[i].lineage.UpdatedAt.After(candidates[j].lineage.UpdatedAt)
})
for _, candidate := range candidates {
lineage := candidate.lineage
versions, versionErr := s.Repository.ListCertificateVersions(ctx, lineage.ID)
if versionErr != nil {
return "", versionErr
}
for _, version := range versions {
if version.ID == lineage.CurrentVersionID {
if version.RevokedAt != nil {
return "revoked:" + version.FingerprintSHA256, nil
}
if version.RevocationPendingAt != nil {
return "revocation-pending:" + version.FingerprintSHA256, nil
}
return version.FingerprintSHA256, nil
}
}
}
return "", nil
}
func identifierSpecificity(identifiers []string, host string) int {
for _, value := range identifiers {
value = strings.ToLower(strings.TrimSuffix(value, "."))
if value == host {
return 10
}
}
return 1
}
func identifiersCover(identifiers []string, host string) bool {
for _, identifier := range identifiers {
identifier = strings.ToLower(strings.TrimSuffix(identifier, "."))
if identifier == host {
return true
}
if strings.HasPrefix(identifier, "*.") {
suffix := strings.TrimPrefix(identifier, "*.")
if strings.HasSuffix(host, "."+suffix) && strings.Count(host, ".") == strings.Count(suffix, ".")+1 {
return true
}
}
}
return false
}
func (s *CertificateService) now() time.Time {
if s.Now != nil {
return s.Now().UTC()
}
return time.Now().UTC()
}
func certificateLineageKey(zoneID, accountID string) string {
return zoneID + "\x00" + accountID
}
func (s *CertificateService) managedExportRoot(environment, zoneName string) string {
if environment == certificates.EnvironmentStaging {
return filepath.Join(s.ExportRoot, "staging", zoneName)
}
return filepath.Join(s.ExportRoot, zoneName)
}
+589
View File
@@ -0,0 +1,589 @@
package app
import (
"context"
"crypto"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"errors"
"math/big"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/certificates"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
"github.com/MeghdadFadaee/domainops/internal/secrets"
"github.com/MeghdadFadaee/domainops/internal/store"
sqlitestore "github.com/MeghdadFadaee/domainops/internal/store/sqlite"
"github.com/go-acme/lego/v5/acme"
"github.com/go-acme/lego/v5/certificate"
"github.com/go-acme/lego/v5/challenge"
)
func TestIssueZonesPersistsCompletedCertificateBeforeBulkFinishes(t *testing.T) {
ctx := context.Background()
service, repository, backend, zones := newStreamingCertificateService(t)
resultChannel := make(chan struct {
result IssueZonesResult
err error
}, 1)
go func() {
result, err := service.IssueZones(ctx, IssueZonesRequest{ZoneIDs: []string{zones[0].ID, zones[1].ID}, Environment: certificates.EnvironmentStaging})
resultChannel <- struct {
result IssueZonesResult
err error
}{result, err}
}()
select {
case <-backend.fastReturned:
case <-time.After(3 * time.Second):
t.Fatal("fast ACME order did not return")
}
deadline := time.Now().Add(3 * time.Second)
for {
lineages, err := repository.ListCertificateLineages(ctx)
if err != nil {
t.Fatal(err)
}
persisted := false
for _, lineage := range lineages {
if lineage.ZoneID == zones[0].ID && lineage.CurrentVersionID != "" {
persisted = true
break
}
}
if persisted {
break
}
if time.Now().After(deadline) {
t.Fatal("completed certificate was not persisted while the slow order remained active")
}
time.Sleep(10 * time.Millisecond)
}
select {
case outcome := <-resultChannel:
t.Fatalf("bulk returned before slow order was released: %#v, %v", outcome.result, outcome.err)
default:
}
close(backend.releaseSlow)
outcome := <-resultChannel
if outcome.err != nil || len(outcome.result.Completed) != 2 || len(outcome.result.Failed) != 0 {
t.Fatalf("bulk outcome = %#v, %v", outcome.result, outcome.err)
}
}
func TestRenewAndRevokeRejectDifferentACMEAccount(t *testing.T) {
ctx := context.Background()
service, repository, backend, zones := newStreamingCertificateService(t)
close(backend.releaseSlow)
issued, err := service.IssueZones(ctx, IssueZonesRequest{ZoneIDs: []string{zones[0].ID}, Environment: certificates.EnvironmentStaging})
if err != nil || len(issued.Completed) != 1 {
t.Fatalf("issue fixture = %#v, %v", issued, err)
}
lineage := issued.Completed[0].Lineage
lineage.ACMEAccountID = "another-account"
if err := repository.SaveCertificateLineage(ctx, lineage); err != nil {
t.Fatal(err)
}
version := issued.Completed[0].Version
due := time.Now().Add(-time.Hour)
version.RenewalWindowStart = &due
if err := repository.SaveCertificateVersion(ctx, version); err != nil {
t.Fatal(err)
}
calls := backend.calls.Load()
renewed, err := service.RenewDue(ctx, certificates.EnvironmentStaging, false)
if err != nil || len(renewed.Completed) != 0 || len(renewed.Failed) != 0 || backend.calls.Load() != calls {
t.Fatalf("mismatched renewal = %#v, %v, calls=%d→%d", renewed, err, calls, backend.calls.Load())
}
if err := service.Revoke(ctx, lineage.ID, certificates.EnvironmentStaging, lineage.Name, nil); err == nil || !strings.Contains(err.Error(), "not owned") {
t.Fatalf("mismatched revocation error = %v", err)
}
}
func TestIssueZonesKeepsStagingAndProductionLineagesAndCurrentLinksSeparate(t *testing.T) {
ctx := context.Background()
service, repository, backend, zones := newStreamingCertificateService(t)
registerTestACMEAccount(t, ctx, repository, service.Secrets, certificates.EnvironmentProduction, "acme-production")
staging, err := service.IssueZones(ctx, IssueZonesRequest{ZoneIDs: []string{zones[0].ID}, Environment: certificates.EnvironmentStaging})
if err != nil || len(staging.Completed) != 1 {
t.Fatalf("staging issue = %#v, %v", staging, err)
}
production, err := service.IssueZones(ctx, IssueZonesRequest{ZoneIDs: []string{zones[0].ID}, Environment: certificates.EnvironmentProduction, ConfirmProduction: true})
if err != nil || len(production.Completed) != 1 {
t.Fatalf("production issue = %#v, %v", production, err)
}
stagingCommit, productionCommit := staging.Completed[0], production.Completed[0]
if stagingCommit.Lineage.ID == productionCommit.Lineage.ID || stagingCommit.Lineage.ACMEAccountID == productionCommit.Lineage.ACMEAccountID {
t.Fatalf("environments shared lineage/account: staging=%#v production=%#v", stagingCommit.Lineage, productionCommit.Lineage)
}
if !strings.Contains(stagingCommit.Version.ExportPath, string(filepath.Separator)+"staging"+string(filepath.Separator)) {
t.Fatalf("staging export path was not isolated: %s", stagingCommit.Version.ExportPath)
}
if strings.Contains(productionCommit.Version.ExportPath, string(filepath.Separator)+"staging"+string(filepath.Separator)) {
t.Fatalf("production export path entered staging tree: %s", productionCommit.Version.ExportPath)
}
for _, commit := range []certificates.CommitResult{stagingCommit, productionCommit} {
target, readErr := filepath.EvalSymlinks(commit.Export.CurrentLink)
wantTarget, wantErr := filepath.EvalSymlinks(commit.Version.ExportPath)
if readErr != nil || wantErr != nil || target != wantTarget {
t.Fatalf("current link %s = %s, %v; want %s, %v", commit.Export.CurrentLink, target, readErr, wantTarget, wantErr)
}
}
stagingAgain, err := service.IssueZones(ctx, IssueZonesRequest{ZoneIDs: []string{zones[0].ID}, Environment: certificates.EnvironmentStaging})
if err != nil || len(stagingAgain.Completed) != 1 || stagingAgain.Completed[0].Lineage.ID != stagingCommit.Lineage.ID {
t.Fatalf("second staging issue = %#v, %v", stagingAgain, err)
}
storedProduction, err := repository.GetCertificateLineage(ctx, productionCommit.Lineage.ID)
if err != nil || storedProduction.CurrentVersionID != productionCommit.Version.ID {
t.Fatalf("staging issue changed production current version: %#v, %v", storedProduction, err)
}
due := time.Now().Add(-time.Hour)
productionVersion := productionCommit.Version
productionVersion.RenewalWindowStart = &due
if err := repository.SaveCertificateVersion(ctx, productionVersion); err != nil {
t.Fatal(err)
}
renewed, err := service.RenewDue(ctx, certificates.EnvironmentProduction, true)
if err != nil || len(renewed.Completed) != 1 || renewed.Completed[0].Lineage.ID != productionCommit.Lineage.ID || renewed.Completed[0].Version.ID == productionCommit.Version.ID {
t.Fatalf("production renewal = %#v, %v", renewed, err)
}
storedStaging, err := repository.GetCertificateLineage(ctx, stagingCommit.Lineage.ID)
if err != nil || storedStaging.CurrentVersionID != stagingAgain.Completed[0].Version.ID {
t.Fatalf("production renewal changed staging current version: %#v, %v", storedStaging, err)
}
if backend.calls.Load() != 4 {
t.Fatalf("ACME calls = %d, want 4", backend.calls.Load())
}
endpoint := domain.ObservedEndpoint{ZoneID: zones[0].ID, Host: zones[0].Name}
fingerprint, err := service.ExpectedFingerprint(ctx, endpoint)
if err != nil || fingerprint != renewed.Completed[0].Version.FingerprintSHA256 {
t.Fatalf("public fingerprint selection = %q, %v; want production %q", fingerprint, err, renewed.Completed[0].Version.FingerprintSHA256)
}
}
func TestRevocationIntentConvergesAfterCASuccessAndLocalSaveFailure(t *testing.T) {
ctx := context.Background()
service, repository, backend, zones := newStreamingCertificateService(t)
issued, err := service.IssueZones(ctx, IssueZonesRequest{ZoneIDs: []string{zones[0].ID}, Environment: certificates.EnvironmentStaging})
if err != nil || len(issued.Completed) != 1 {
t.Fatalf("issue fixture = %#v, %v", issued, err)
}
due := time.Now().Add(-time.Hour)
dueVersion := issued.Completed[0].Version
dueVersion.RenewalWindowStart = &due
if err := repository.SaveCertificateVersion(ctx, dueVersion); err != nil {
t.Fatal(err)
}
backend.alreadyRevokedAfterFirst = true
flaky := &failNthVersionSaveRepository{Repository: repository, failAt: 2}
service.Repository = flaky
reason := uint(1)
lineage := issued.Completed[0].Lineage
err = service.Revoke(ctx, lineage.ID, certificates.EnvironmentStaging, lineage.Name, &reason)
if err == nil || !strings.Contains(err.Error(), "revoked by the CA") {
t.Fatalf("first revocation error = %v", err)
}
versions, err := repository.ListCertificateVersions(ctx, lineage.ID)
if err != nil || len(versions) == 0 || versions[0].RevocationPendingAt == nil || versions[0].RevokedAt != nil {
t.Fatalf("durable revocation intent = %#v, %v", versions, err)
}
if _, exportErr := service.Export(ctx, lineage.ID, t.TempDir()); exportErr == nil || !strings.Contains(exportErr.Error(), "revocation is pending") {
t.Fatalf("pending-revocation certificate export = %v", exportErr)
}
issueCalls := backend.calls.Load()
if result, renewErr := service.RenewDue(ctx, certificates.EnvironmentStaging, false); renewErr != nil || len(result.Completed) != 0 || backend.calls.Load() != issueCalls {
t.Fatalf("pending revocation was renewed: %#v, %v, calls=%d→%d", result, renewErr, issueCalls, backend.calls.Load())
}
if err := service.Revoke(ctx, lineage.ID, certificates.EnvironmentStaging, lineage.Name, &reason); err != nil {
t.Fatalf("retry after alreadyRevoked did not converge: %v", err)
}
versions, err = repository.ListCertificateVersions(ctx, lineage.ID)
if err != nil || versions[0].RevocationPendingAt != nil || versions[0].RevokedAt == nil || versions[0].RevocationReason == nil || *versions[0].RevocationReason != reason {
t.Fatalf("converged revocation state = %#v, %v", versions, err)
}
if _, exportErr := service.Export(ctx, lineage.ID, t.TempDir()); exportErr == nil || !strings.Contains(exportErr.Error(), "was revoked") {
t.Fatalf("revoked certificate export = %v", exportErr)
}
if backend.revokeCalls.Load() != 2 {
t.Fatalf("revocation calls = %d, want 2", backend.revokeCalls.Load())
}
}
func TestImportMetadataCleansJournaledFileWhenDatabaseCommitFails(t *testing.T) {
ctx := context.Background()
service, repository, _, _ := newStreamingCertificateService(t)
failing := &failCertificateCommitRepository{Repository: repository}
service.Repository = failing
service.Lifecycle.Repository = failing
key, err := certificates.GeneratePrivateKey(domain.KeyECDSAP256)
if err != nil {
t.Fatal(err)
}
certificatePEM, err := certificateForAppTest(key, []string{"import.example.com"})
if err != nil {
t.Fatal(err)
}
source := filepath.Join(t.TempDir(), "source.pem")
if err := os.WriteFile(source, certificatePEM, 0o600); err != nil {
t.Fatal(err)
}
if _, _, err := service.ImportMetadata(ctx, source, "import.example.com", ""); err == nil || !strings.Contains(err.Error(), "injected certificate commit failure") {
t.Fatalf("import failure = %v", err)
}
intents, err := repository.ListCertificateCommitIntents(ctx)
if err != nil || len(intents) != 0 {
t.Fatalf("failed import retained commit intent: %#v, %v", intents, err)
}
var pemFiles []string
_ = filepath.Walk(service.ExportRoot, func(path string, info os.FileInfo, walkErr error) error {
if walkErr == nil && info != nil && !info.IsDir() && strings.HasSuffix(path, ".pem") {
pemFiles = append(pemFiles, path)
}
return nil
})
if len(pemFiles) != 0 {
t.Fatalf("failed import retained PEM artifacts: %#v", pemFiles)
}
}
func TestImportMetadataPreservesCertificateWhenCommitReturnsAmbiguousError(t *testing.T) {
ctx := context.Background()
service, repository, _, _ := newStreamingCertificateService(t)
ambiguous := &ambiguousCertificateCommitRepository{Repository: repository}
service.Repository = ambiguous
service.Lifecycle.Repository = ambiguous
key, err := certificates.GeneratePrivateKey(domain.KeyECDSAP256)
if err != nil {
t.Fatal(err)
}
certificatePEM, err := certificateForAppTest(key, []string{"import.example.com"})
if err != nil {
t.Fatal(err)
}
source := filepath.Join(t.TempDir(), "source.pem")
if err := os.WriteFile(source, certificatePEM, 0o600); err != nil {
t.Fatal(err)
}
lineage, version, err := service.ImportMetadata(ctx, source, "import.example.com", "")
if err != nil {
t.Fatalf("reconciled import failed: %v", err)
}
if lineage.CurrentVersionID != version.ID {
t.Fatalf("reconciled import relationship = %#v / %#v", lineage, version)
}
if _, err := os.Stat(version.CertificatePath); err != nil {
t.Fatalf("reconciled import deleted committed PEM: %v", err)
}
intents, err := repository.ListCertificateCommitIntents(ctx)
if err != nil || len(intents) != 0 {
t.Fatalf("reconciled import journal = %#v, %v", intents, err)
}
stored, err := repository.GetCertificateLineage(ctx, lineage.ID)
if err != nil || stored.CurrentVersionID != version.ID {
t.Fatalf("reconciled imported lineage = %#v, %v", stored, err)
}
audit, err := repository.ListAudit(ctx, 1)
if err != nil || len(audit) != 1 || audit[0].Action != "certificate.import_metadata.commit_reconciled" {
t.Fatalf("reconciled import audit = %#v, %v", audit, err)
}
}
func TestExpectedFingerprintPrefersImportedCurrentCertificateOverStaging(t *testing.T) {
ctx := context.Background()
service, repository, _, zones := newStreamingCertificateService(t)
staging, err := service.IssueZones(ctx, IssueZonesRequest{ZoneIDs: []string{zones[0].ID}, Environment: certificates.EnvironmentStaging})
if err != nil || len(staging.Completed) != 1 {
t.Fatalf("staging fixture = %#v, %v", staging, err)
}
now := time.Now().UTC()
lineage := domain.CertificateLineage{ID: "imported-current", Name: zones[0].Name, ZoneID: zones[0].ID, Source: domain.CertificateImported, Identifiers: []string{zones[0].Name}, KeyAlgorithm: domain.KeyECDSAP256, CurrentVersionID: "imported-version", CreatedAt: now, UpdatedAt: now}
version := domain.CertificateVersion{ID: lineage.CurrentVersionID, LineageID: lineage.ID, FingerprintSHA256: "imported-fingerprint", Identifiers: lineage.Identifiers, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(24 * time.Hour), CertificatePath: "/metadata/import.pem", CreatedAt: now}
if err := repository.CommitCertificateVersion(ctx, lineage, version); err != nil {
t.Fatal(err)
}
fingerprint, err := service.ExpectedFingerprint(ctx, domain.ObservedEndpoint{ZoneID: zones[0].ID, Host: zones[0].Name})
if err != nil || fingerprint != version.FingerprintSHA256 {
t.Fatalf("expected fingerprint = %q, %v; want imported %q", fingerprint, err, version.FingerprintSHA256)
}
}
func TestExpectedFingerprintSkipsOriginComparisonForProxiedEndpoint(t *testing.T) {
ctx := context.Background()
service, repository, _, zones := newStreamingCertificateService(t)
now := time.Now().UTC()
lineage := domain.CertificateLineage{
ID: "proxied-origin", Name: zones[0].Name, ZoneID: zones[0].ID,
Source: domain.CertificateImported, Identifiers: []string{zones[0].Name},
KeyAlgorithm: domain.KeyECDSAP256, CurrentVersionID: "proxied-origin-version",
CreatedAt: now, UpdatedAt: now,
}
version := domain.CertificateVersion{
ID: lineage.CurrentVersionID, LineageID: lineage.ID, FingerprintSHA256: "origin-fingerprint",
Identifiers: lineage.Identifiers, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(24 * time.Hour),
CertificatePath: "/metadata/origin.pem", CreatedAt: now,
}
if err := repository.CommitCertificateVersion(ctx, lineage, version); err != nil {
t.Fatal(err)
}
record := domain.DNSRecord{
ID: "cfrecord_proxied", ProviderID: "proxied", ZoneID: zones[0].ID,
Type: domain.RecordA, Name: zones[0].Name, Content: "192.0.2.1", TTL: 1,
Proxied: true, Proxiable: true,
}
if err := repository.SaveDNSRecord(ctx, record); err != nil {
t.Fatal(err)
}
endpoint := domain.ObservedEndpoint{ZoneID: zones[0].ID, Host: zones[0].Name, Port: 443}
fingerprint, err := service.ExpectedFingerprint(ctx, endpoint)
if err != nil || fingerprint != "" {
t.Fatalf("proxied endpoint expected fingerprint = %q, %v; want empty", fingerprint, err)
}
record.Proxied = false
if err := repository.SaveDNSRecord(ctx, record); err != nil {
t.Fatal(err)
}
fingerprint, err = service.ExpectedFingerprint(ctx, endpoint)
if err != nil || fingerprint != version.FingerprintSHA256 {
t.Fatalf("unproxied endpoint expected fingerprint = %q, %v; want %q", fingerprint, err, version.FingerprintSHA256)
}
}
func TestExpectedFingerprintUsesZoneLessImportAndPrefersSameZoneImport(t *testing.T) {
ctx := context.Background()
service, repository, _, zones := newStreamingCertificateService(t)
now := time.Now().UTC()
zoneLess := domain.CertificateLineage{
ID: "zone-less-import", Name: zones[0].Name, Source: domain.CertificateImported,
Identifiers: []string{zones[0].Name}, KeyAlgorithm: domain.KeyECDSAP256,
CurrentVersionID: "zone-less-version", CreatedAt: now, UpdatedAt: now,
}
zoneLessVersion := domain.CertificateVersion{
ID: zoneLess.CurrentVersionID, LineageID: zoneLess.ID, FingerprintSHA256: "zone-less-fingerprint",
Identifiers: zoneLess.Identifiers, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(24 * time.Hour),
CertificatePath: "/metadata/zone-less.pem", CreatedAt: now,
}
if err := repository.CommitCertificateVersion(ctx, zoneLess, zoneLessVersion); err != nil {
t.Fatal(err)
}
endpoint := domain.ObservedEndpoint{ZoneID: zones[0].ID, Host: zones[0].Name}
fingerprint, err := service.ExpectedFingerprint(ctx, endpoint)
if err != nil || fingerprint != zoneLessVersion.FingerprintSHA256 {
t.Fatalf("zone-less imported fingerprint = %q, %v; want %q", fingerprint, err, zoneLessVersion.FingerprintSHA256)
}
sameZone := domain.CertificateLineage{
ID: "same-zone-import", Name: zones[0].Name, ZoneID: zones[0].ID, Source: domain.CertificateImported,
Identifiers: []string{zones[0].Name}, KeyAlgorithm: domain.KeyECDSAP256,
CurrentVersionID: "same-zone-version", CreatedAt: now.Add(-time.Hour), UpdatedAt: now.Add(-time.Hour),
}
sameZoneVersion := domain.CertificateVersion{
ID: sameZone.CurrentVersionID, LineageID: sameZone.ID, FingerprintSHA256: "same-zone-fingerprint",
Identifiers: sameZone.Identifiers, NotBefore: now.Add(-2 * time.Hour), NotAfter: now.Add(23 * time.Hour),
CertificatePath: "/metadata/same-zone.pem", CreatedAt: now.Add(-time.Hour),
}
if err := repository.CommitCertificateVersion(ctx, sameZone, sameZoneVersion); err != nil {
t.Fatal(err)
}
fingerprint, err = service.ExpectedFingerprint(ctx, endpoint)
if err != nil || fingerprint != sameZoneVersion.FingerprintSHA256 {
t.Fatalf("preferred imported fingerprint = %q, %v; want same-zone %q", fingerprint, err, sameZoneVersion.FingerprintSHA256)
}
}
func registerTestACMEAccount(t *testing.T, ctx context.Context, repository *sqlitestore.Repository, secretStore store.SecretStore, environment, id string) {
t.Helper()
key, err := certificates.GeneratePrivateKey(domain.KeyECDSAP256)
if err != nil {
t.Fatal(err)
}
keyPEM, err := certificates.MarshalPrivateKeyPKCS8(key)
if err != nil {
t.Fatal(err)
}
keyRef, err := secretStore.Put(ctx, "", keyPEM)
if err != nil {
t.Fatal(err)
}
registration, _ := json.Marshal(&acme.ExtendedAccount{Location: "https://acme.test/acct/" + id})
if err := repository.SaveACMEAccount(ctx, domain.ACMEAccount{ID: id, Environment: environment, DirectoryURL: "https://acme.test/directory", Email: "ops@example.com", Registration: string(registration), SecretRef: keyRef, CreatedAt: time.Now().UTC()}); err != nil {
t.Fatal(err)
}
}
type failNthVersionSaveRepository struct {
store.Repository
mu sync.Mutex
calls int
failAt int
}
type failCertificateCommitRepository struct{ store.Repository }
func (r *failCertificateCommitRepository) CommitCertificateVersion(context.Context, domain.CertificateLineage, domain.CertificateVersion) error {
return errors.New("injected certificate commit failure")
}
type ambiguousCertificateCommitRepository struct{ store.Repository }
func (r *ambiguousCertificateCommitRepository) CommitCertificateVersion(ctx context.Context, lineage domain.CertificateLineage, version domain.CertificateVersion) error {
if err := r.Repository.CommitCertificateVersion(ctx, lineage, version); err != nil {
return err
}
return errors.New("injected connection loss after certificate commit")
}
func (r *failNthVersionSaveRepository) SaveCertificateVersion(ctx context.Context, version domain.CertificateVersion) error {
r.mu.Lock()
defer r.mu.Unlock()
r.calls++
if r.calls == r.failAt {
return errors.New("injected local save failure")
}
return r.Repository.SaveCertificateVersion(ctx, version)
}
func newStreamingCertificateService(t *testing.T) (*CertificateService, *sqlitestore.Repository, *streamingBackend, []domain.Zone) {
t.Helper()
ctx := context.Background()
root := t.TempDir()
repository, err := sqlitestore.New(filepath.Join(root, "domainops.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = repository.Close() })
if err := repository.Migrate(ctx); err != nil {
t.Fatal(err)
}
vault, err := secrets.New(filepath.Join(root, "vault.json"), "", "")
if err != nil {
t.Fatal(err)
}
if err := vault.Unlock(ctx, []byte("long certificate test password")); err != nil {
t.Fatal(err)
}
t.Cleanup(vault.Lock)
credentialSecret, err := vault.Put(ctx, "", []byte("token"))
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
credential := domain.Credential{ID: "credential", Provider: domain.ProviderCloudflare, Label: "CF", Kind: domain.CredentialUserToken, SecretRef: credentialSecret, Status: domain.CredentialValid, CreatedAt: now}
if err := repository.SaveCredential(ctx, credential); err != nil {
t.Fatal(err)
}
account := domain.RemoteAccount{ID: "cfacct_account", Provider: domain.ProviderCloudflare, ProviderID: "account", Name: "Account", CreatedAt: now}
if err := repository.SaveAccounts(ctx, []domain.RemoteAccount{account}, []domain.AccountCredential{{AccountID: account.ID, CredentialID: credential.ID, Preferred: true}}); err != nil {
t.Fatal(err)
}
zones := []domain.Zone{
{ID: "cfzone_fast", Provider: domain.ProviderCloudflare, ProviderID: "fast", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "fast.example.com", Status: domain.ZoneActive},
{ID: "cfzone_slow", Provider: domain.ProviderCloudflare, ProviderID: "slow", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "slow.example.com", Status: domain.ZoneActive},
}
if err := repository.SaveZones(ctx, zones); err != nil {
t.Fatal(err)
}
accountKey, err := certificates.GeneratePrivateKey(domain.KeyECDSAP256)
if err != nil {
t.Fatal(err)
}
accountKeyPEM, err := certificates.MarshalPrivateKeyPKCS8(accountKey)
if err != nil {
t.Fatal(err)
}
accountKeyRef, err := vault.Put(ctx, "", accountKeyPEM)
if err != nil {
t.Fatal(err)
}
registration, _ := json.Marshal(&acme.ExtendedAccount{Location: "https://acme.test/acct/1"})
if err := repository.SaveACMEAccount(ctx, domain.ACMEAccount{ID: "acme-staging", Environment: certificates.EnvironmentStaging, DirectoryURL: "https://acme.test/directory", Email: "ops@example.com", Registration: string(registration), SecretRef: accountKeyRef, CreatedAt: now}); err != nil {
t.Fatal(err)
}
backend := &streamingBackend{releaseSlow: make(chan struct{}), fastReturned: make(chan struct{})}
engine := certificates.NewEngine(repository, vault, noopDNS01Solver{}, func(context.Context, string) (provider.Auth, string, error) {
return provider.Auth{CredentialID: credential.ID, Token: "token", Kind: credential.Kind}, "fast", nil
}, certificates.WithBackendFactory(streamingBackendFactory{backend: backend}))
return NewCertificateService(repository, vault, engine, filepath.Join(root, "certificates")), repository, backend, zones
}
type streamingBackendFactory struct{ backend *streamingBackend }
func (f streamingBackendFactory) New(context.Context, certificates.AccountMaterial, challenge.Provider) (certificates.CertificateBackend, error) {
return f.backend, nil
}
type streamingBackend struct {
releaseSlow chan struct{}
fastReturned chan struct{}
fastOnce sync.Once
calls atomic.Int32
revokeCalls atomic.Int32
alreadyRevokedAfterFirst bool
}
func (b *streamingBackend) Obtain(ctx context.Context, request certificate.ObtainRequest) (*certificate.Resource, error) {
b.calls.Add(1)
if strings.HasPrefix(request.Domains[0], "slow.") {
select {
case <-b.releaseSlow:
case <-ctx.Done():
return nil, ctx.Err()
}
}
certificatePEM, err := certificateForAppTest(request.PrivateKey, request.Domains)
if err != nil {
return nil, err
}
if strings.HasPrefix(request.Domains[0], "fast.") {
b.fastOnce.Do(func() { close(b.fastReturned) })
}
return &certificate.Resource{Certificate: certificatePEM, Domains: request.Domains}, nil
}
func (b *streamingBackend) RevokeWithReason(context.Context, []byte, *uint) error {
call := b.revokeCalls.Add(1)
if b.alreadyRevokedAfterFirst && call > 1 {
return &acme.ProblemDetails{Type: acme.AlreadyRevokedErrorType, HTTPStatus: 400, Detail: "certificate already revoked"}
}
return nil
}
func (b *streamingBackend) GetRenewalInfo(context.Context, *x509.Certificate) (*certificate.RenewalInfo, error) {
return nil, errors.New("ARI unavailable in test")
}
type noopDNS01Solver struct{}
func (noopDNS01Solver) PresentDNS01(context.Context, provider.Auth, string, string, string, string) (string, error) {
return "record", nil
}
func (noopDNS01Solver) CleanupDNS01(context.Context, provider.Auth, string, string) error { return nil }
func certificateForAppTest(key crypto.Signer, identifiers []string) ([]byte, error) {
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120))
if err != nil {
return nil, err
}
now := time.Now().UTC()
template := &x509.Certificate{
SerialNumber: serial, Subject: pkix.Name{CommonName: identifiers[0]}, DNSNames: append([]string(nil), identifiers...),
NotBefore: now.Add(-time.Hour), NotAfter: now.Add(24 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), nil
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+167
View File
@@ -0,0 +1,167 @@
package bootstrap
import (
"context"
"errors"
"fmt"
"net/http"
"path/filepath"
"time"
"github.com/MeghdadFadaee/domainops/internal/app"
"github.com/MeghdadFadaee/domainops/internal/certificates"
"github.com/MeghdadFadaee/domainops/internal/config"
"github.com/MeghdadFadaee/domainops/internal/health"
"github.com/MeghdadFadaee/domainops/internal/lockfile"
cloudflareprovider "github.com/MeghdadFadaee/domainops/internal/providers/cloudflare"
"github.com/MeghdadFadaee/domainops/internal/secrets"
sqlitestore "github.com/MeghdadFadaee/domainops/internal/store/sqlite"
)
type Options struct {
DataDir string
NoKeyring bool
}
type Runtime struct {
Paths config.Paths
Repository *sqlitestore.Repository
Vault *secrets.Vault
Application *app.Service
Certificates *app.CertificateService
Health *health.Checker
Cloudflare *cloudflareprovider.Client
lock *lockfile.Lock
}
func Open(ctx context.Context, options Options) (*Runtime, error) {
paths, err := config.Resolve(options.DataDir)
if err != nil {
return nil, err
}
if err := paths.Ensure(); err != nil {
return nil, err
}
lock, err := lockfile.Acquire(filepath.Join(paths.DataDir, "domainops.lock"))
if err != nil {
return nil, err
}
fail := func(openErr error) (*Runtime, error) {
_ = lock.Close()
return nil, openErr
}
repository, err := sqlitestore.New(paths.Database)
if err != nil {
return fail(err)
}
if err := repository.Migrate(ctx); err != nil {
_ = repository.Close()
return fail(err)
}
var vault *secrets.Vault
if options.NoKeyring {
vault, err = secrets.New(paths.Vault, "", "")
} else {
vault, err = secrets.NewDefault(paths.Vault)
}
if err != nil {
_ = repository.Close()
return fail(err)
}
cloudflareClient := cloudflareprovider.New()
application := app.New(repository, vault)
application.RegisterProvider("cloudflare", cloudflareClient)
httpClient := &http.Client{Timeout: 45 * time.Second}
engine := certificates.NewEngine(repository, vault, cloudflareClient, application.ResolveDNS01,
certificates.WithACMEHTTPClient(httpClient, "DomainOps/1"),
certificates.WithPreflight(application.CertificatePreflight),
certificates.WithDNSWriteObserver(func(observeCtx context.Context, credentialID, providerZoneID string) error {
return application.ObserveCredentialZoneCapability(observeCtx, credentialID, providerZoneID, "dns:write")
}))
certificateService := app.NewCertificateService(repository, vault, engine, paths.Certificates)
application.SetCertificateService(certificateService)
checker := &health.Checker{
Repository: repository,
Prober: health.NewProber(),
ExpectedFingerprint: certificateService.ExpectedFingerprint,
Concurrency: 8,
}
application.SetHealthCheck(checker.RunOnce)
application.SetUnlockHook(func(unlockCtx context.Context) error {
cleanupCtx, cancel := context.WithTimeout(unlockCtx, 10*time.Minute)
defer cancel()
recoveryErr := errors.Join(
certificates.RecoverACMEAccountCommitIntents(cleanupCtx, repository, vault),
certificates.RecoverCertificateCommitIntents(cleanupCtx, repository, vault, paths.Certificates),
certificates.CleanupOpenChallenges(cleanupCtx, repository, cloudflareClient, application.ResolveDNS01, application.ResolveCredential),
certificateService.RepairManagedCurrentLinks(cleanupCtx),
)
return reconcileJobsAfterRecovery(recoveryErr, func() error {
return application.ReconcileInterruptedJobs(cleanupCtx)
})
})
if !vault.Locked() {
// Keyring auto-unlock happens while the vault is constructed, before the
// recovery hook exists. Re-entering UnlockVault is a no-op for the vault
// but guarantees crash-left DNS-01 records are retried on this path too.
// Match the unlock hook's recovery budget. A large journal can require
// many bounded provider calls, especially after an extended outage; a
// shorter parent deadline would silently reduce the ten-minute hook to
// thirty seconds and leave an otherwise healthy auto-unlocked runtime
// recovery-blocked.
recoveryCtx, cancel := context.WithTimeout(ctx, 10*time.Minute)
_ = application.UnlockVault(recoveryCtx, nil)
cancel()
}
return &Runtime{
Paths: paths, Repository: repository, Vault: vault, Application: application,
Certificates: certificateService, Health: checker, Cloudflare: cloudflareClient, lock: lock,
}, nil
}
func (r *Runtime) Close() error {
if r == nil {
return nil
}
if r.Vault != nil {
r.Vault.Lock()
}
var errs []error
if r.Repository != nil {
errs = append(errs, r.Repository.Close())
}
if r.lock != nil {
errs = append(errs, r.lock.Close())
}
return errors.Join(errs...)
}
func (r *Runtime) Recover(ctx context.Context) error {
if r == nil || r.Vault == nil || r.Vault.Locked() {
return fmt.Errorf("vault must be unlocked before recovery")
}
recoveryErr := errors.Join(
certificates.RecoverACMEAccountCommitIntents(ctx, r.Repository, r.Vault),
certificates.RecoverCertificateCommitIntents(ctx, r.Repository, r.Vault, r.Paths.Certificates),
certificates.CleanupOpenChallenges(ctx, r.Repository, r.Cloudflare, r.Application.ResolveDNS01, r.Application.ResolveCredential),
r.Certificates.RepairManagedCurrentLinks(ctx),
)
return reconcileJobsAfterRecovery(recoveryErr, func() error {
return r.Application.ReconcileInterruptedJobs(ctx)
})
}
func reconcileJobsAfterRecovery(recoveryErr error, reconcile func() error) error {
if recoveryErr != nil {
return recoveryErr
}
if reconcile == nil {
return errors.New("interrupted-job reconciliation is not configured")
}
return reconcile()
}
+28
View File
@@ -0,0 +1,28 @@
package bootstrap
import (
"errors"
"testing"
)
func TestReconcileJobsAfterRecoveryRunsOnlyAfterSuccessfulRecovery(t *testing.T) {
t.Parallel()
recoveryFailure := errors.New("journal recovery failed")
called := false
err := reconcileJobsAfterRecovery(recoveryFailure, func() error {
called = true
return nil
})
if !errors.Is(err, recoveryFailure) || called {
t.Fatalf("failed recovery result = %v, reconcile called=%v", err, called)
}
reconcileFailure := errors.New("job reconciliation failed")
err = reconcileJobsAfterRecovery(nil, func() error {
called = true
return reconcileFailure
})
if !called || !errors.Is(err, reconcileFailure) {
t.Fatalf("successful recovery result = %v, reconcile called=%v", err, called)
}
}
+7
View File
@@ -0,0 +1,7 @@
package buildinfo
var (
Version = "dev"
Commit = "none"
Date = "unknown"
)
+294
View File
@@ -0,0 +1,294 @@
package certificates
import (
"context"
"crypto"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/mail"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/identifier"
"github.com/MeghdadFadaee/domainops/internal/store"
"github.com/go-acme/lego/v5/acme"
"github.com/go-acme/lego/v5/lego"
"github.com/go-acme/lego/v5/registration"
)
type AccountRepository interface {
SaveACMEAccount(context.Context, domain.ACMEAccount) error
CommitACMEAccount(context.Context, domain.ACMEAccount) error
GetACMEAccountByEnvironment(context.Context, string) (domain.ACMEAccount, error)
SaveACMEAccountCommitIntent(context.Context, domain.ACMEAccountCommitIntent) error
ListACMEAccountCommitIntents(context.Context) ([]domain.ACMEAccountCommitIntent, error)
DeleteACMEAccountCommitIntent(context.Context, string) error
}
type SecretStore interface {
Put(context.Context, string, []byte) (string, error)
Get(context.Context, string) ([]byte, error)
Delete(context.Context, string) error
}
type AccountMaterial struct {
Account domain.ACMEAccount
PrivateKey crypto.Signer
Registration *acme.ExtendedAccount
}
type RegisterAccountRequest struct {
Environment string
Email string
TermsOfServiceAgreed bool
DirectoryURL string
AllowCustomDirectory bool
}
type AccountService struct {
Repository AccountRepository
Secrets SecretStore
HTTPClient *http.Client
UserAgent string
}
func DirectoryForEnvironment(environment string) (string, error) {
switch environment {
case EnvironmentStaging:
return lego.DirectoryURLLetsEncryptStaging, nil
case EnvironmentProduction:
return lego.DirectoryURLLetsEncrypt, nil
default:
return "", fmt.Errorf("unknown ACME environment %q", environment)
}
}
// Register creates one independent ACME account per environment. The account
// key goes directly to the encrypted secret store and never to process-global
// environment variables or the metadata database.
func (s *AccountService) Register(ctx context.Context, request RegisterAccountRequest) (domain.ACMEAccount, error) {
if s == nil || s.Repository == nil || s.Secrets == nil {
return domain.ACMEAccount{}, errors.New("ACME account service is not fully configured")
}
if !request.TermsOfServiceAgreed {
return domain.ACMEAccount{}, errors.New("ACME terms of service must be explicitly accepted")
}
address, err := mail.ParseAddress(strings.TrimSpace(request.Email))
if err != nil || address.Address != strings.TrimSpace(request.Email) {
return domain.ACMEAccount{}, errors.New("a valid ACME contact email is required")
}
directoryURL, err := DirectoryForEnvironment(request.Environment)
if err != nil {
return domain.ACMEAccount{}, err
}
if request.DirectoryURL != "" {
if !request.AllowCustomDirectory {
return domain.ACMEAccount{}, errors.New("a custom ACME directory requires explicit opt-in")
}
directoryURL = request.DirectoryURL
}
privateKey, err := GeneratePrivateKey(domain.KeyECDSAP256)
if err != nil {
return domain.ACMEAccount{}, err
}
keyPEM, err := MarshalPrivateKeyPKCS8(privateKey)
if err != nil {
return domain.ACMEAccount{}, err
}
accountID := identifier.New("acmeacct")
now := time.Now().UTC()
intent := domain.ACMEAccountCommitIntent{
AccountID: accountID, SecretRef: "acme-account/" + accountID, CreatedAt: now,
}
if err := s.Repository.SaveACMEAccountCommitIntent(ctx, intent); err != nil {
return domain.ACMEAccount{}, fmt.Errorf("journal ACME account key: %w", err)
}
secretRef, err := s.Secrets.Put(ctx, intent.SecretRef, keyPEM)
if err != nil {
if secretRef != "" && secretRef != intent.SecretRef {
err = errors.Join(err, fmt.Errorf("secret store returned unexpected reference %q", secretRef))
}
cleanupErr := cleanupACMEAccountCommitIntent(context.WithoutCancel(ctx), s.Repository, s.Secrets, intent)
return domain.ACMEAccount{}, errors.Join(fmt.Errorf("store ACME account key: %w", err), cleanupErr)
}
if secretRef != intent.SecretRef {
return domain.ACMEAccount{}, errors.Join(
errors.New("secret store returned an unexpected ACME account key reference"),
cleanupACMEAccountCommitIntent(context.WithoutCancel(ctx), s.Repository, s.Secrets, intent),
)
}
failAfterKey := func(operationErr error) (domain.ACMEAccount, error) {
cleanupErr := cleanupACMEAccountCommitIntent(context.WithoutCancel(ctx), s.Repository, s.Secrets, intent)
return domain.ACMEAccount{}, errors.Join(operationErr, cleanupErr)
}
user := &legoUser{email: address.Address, privateKey: privateKey}
config := lego.NewConfig(user)
config.CADirURL = directoryURL
if s.HTTPClient != nil {
config.HTTPClient = s.HTTPClient
}
if s.UserAgent != "" {
config.UserAgent = s.UserAgent
}
client, err := lego.NewClient(config)
if err != nil {
return failAfterKey(fmt.Errorf("create ACME client: %w", err))
}
registrationResource, err := client.Registration.Register(ctx, registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
return failAfterKey(fmt.Errorf("register ACME account: %w", err))
}
registrationJSON, err := json.Marshal(registrationResource)
if err != nil {
return failAfterKey(fmt.Errorf("encode ACME registration: %w", err))
}
account := domain.ACMEAccount{
ID: accountID,
Environment: request.Environment,
DirectoryURL: directoryURL,
Email: address.Address,
Registration: string(registrationJSON),
SecretRef: secretRef,
CreatedAt: now,
}
if commitErr := s.Repository.CommitACMEAccount(ctx, account); commitErr != nil {
if errors.Is(commitErr, store.ErrACMEAccountConflict) {
cleanupErr := cleanupACMEAccountCommitIntent(context.WithoutCancel(ctx), s.Repository, s.Secrets, intent)
return domain.ACMEAccount{}, errors.Join(commitErr, cleanupErr)
}
pending, inspectErr := ACMEAccountCommitIntentPending(context.WithoutCancel(ctx), s.Repository, account.ID)
if inspectErr != nil {
return domain.ACMEAccount{}, errors.Join(
fmt.Errorf("ACME account commit outcome is unknown; key was preserved: %w", commitErr),
fmt.Errorf("inspect ACME account commit journal: %w", inspectErr),
)
}
if !pending {
return account, nil
}
cleanupErr := cleanupACMEAccountCommitIntent(context.WithoutCancel(ctx), s.Repository, s.Secrets, intent)
return domain.ACMEAccount{}, errors.Join(fmt.Errorf("save ACME account: %w", commitErr), cleanupErr)
}
return account, nil
}
func compensateSecretDelete(ctx context.Context, secrets SecretStore, reference string) error {
firstErr := secrets.Delete(ctx, reference)
if firstErr == nil {
return nil
}
if retryErr := secrets.Delete(ctx, reference); retryErr != nil {
return errors.Join(firstErr, fmt.Errorf("retry secret deletion: %w", retryErr))
}
return nil
}
func ACMEAccountCommitIntentPending(ctx context.Context, repository AccountRepository, accountID string) (bool, error) {
intents, err := repository.ListACMEAccountCommitIntents(ctx)
if err != nil {
return false, err
}
for _, intent := range intents {
if intent.AccountID == accountID {
return true, nil
}
}
return false, nil
}
func cleanupACMEAccountCommitIntent(ctx context.Context, repository AccountRepository, secrets SecretStore, intent domain.ACMEAccountCommitIntent) error {
if err := validateACMEAccountCommitIntent(intent); err != nil {
return err
}
if err := compensateSecretDelete(ctx, secrets, intent.SecretRef); err != nil {
return fmt.Errorf("delete orphaned ACME account key: %w", err)
}
if err := repository.DeleteACMEAccountCommitIntent(ctx, intent.AccountID); err != nil {
return fmt.Errorf("close ACME account commit intent: %w", err)
}
return nil
}
func validateACMEAccountCommitIntent(intent domain.ACMEAccountCommitIntent) error {
if intent.AccountID == "" || intent.SecretRef == "" {
return errors.New("ACME account commit intent is incomplete")
}
if err := safePathComponent(intent.AccountID); err != nil {
return fmt.Errorf("ACME account commit intent account ID: %w", err)
}
if len(intent.AccountID) > 128 {
return errors.New("ACME account commit intent account ID is too long")
}
for _, character := range intent.AccountID {
if (character < 'a' || character > 'z') && (character < 'A' || character > 'Z') &&
(character < '0' || character > '9') && character != '_' && character != '-' {
return errors.New("ACME account commit intent account ID contains an unsafe character")
}
}
expected := "acme-account/" + intent.AccountID
if intent.SecretRef != expected {
return fmt.Errorf("ACME account commit intent secret reference must equal %q", expected)
}
return nil
}
func RecoverACMEAccountCommitIntents(ctx context.Context, repository AccountRepository, secrets SecretStore) error {
if repository == nil || secrets == nil {
return errors.New("ACME account commit recovery is not fully configured")
}
intents, err := repository.ListACMEAccountCommitIntents(ctx)
if err != nil {
return fmt.Errorf("list ACME account commit intents: %w", err)
}
var recoveryErrors []error
for _, intent := range intents {
if err := cleanupACMEAccountCommitIntent(ctx, repository, secrets, intent); err != nil {
recoveryErrors = append(recoveryErrors, fmt.Errorf("recover ACME account %s: %w", intent.AccountID, err))
}
}
return errors.Join(recoveryErrors...)
}
func (s *AccountService) Load(ctx context.Context, environment string) (AccountMaterial, error) {
if s == nil || s.Repository == nil || s.Secrets == nil {
return AccountMaterial{}, errors.New("ACME account service is not fully configured")
}
account, err := s.Repository.GetACMEAccountByEnvironment(ctx, environment)
if err != nil {
return AccountMaterial{}, fmt.Errorf("load %s ACME account: %w", environment, err)
}
keyPEM, err := s.Secrets.Get(ctx, account.SecretRef)
if err != nil {
return AccountMaterial{}, fmt.Errorf("load ACME account key: %w", err)
}
privateKey, err := ParsePrivateKeyPEM(keyPEM)
if err != nil {
return AccountMaterial{}, fmt.Errorf("parse ACME account key: %w", err)
}
var registrationResource acme.ExtendedAccount
if err := json.Unmarshal([]byte(account.Registration), &registrationResource); err != nil {
return AccountMaterial{}, fmt.Errorf("parse ACME account registration: %w", err)
}
if registrationResource.Location == "" {
return AccountMaterial{}, errors.New("ACME registration has no account location")
}
return AccountMaterial{
Account: account,
PrivateKey: privateKey,
Registration: &registrationResource,
}, nil
}
type legoUser struct {
email string
privateKey crypto.Signer
registration *acme.ExtendedAccount
}
func (u *legoUser) GetEmail() string { return u.email }
func (u *legoUser) GetRegistration() *acme.ExtendedAccount { return u.registration }
func (u *legoUser) GetPrivateKey() crypto.Signer { return u.privateKey }
File diff suppressed because it is too large. Load diff
+230
View File
@@ -0,0 +1,230 @@
package certificates
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"sync"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/identifier"
"github.com/MeghdadFadaee/domainops/internal/provider"
"github.com/go-acme/lego/v5/challenge/dns01"
)
type ChallengeRepository interface {
SaveChallenge(context.Context, domain.ChallengeJournal) error
ListOpenChallenges(context.Context) ([]domain.ChallengeJournal, error)
MarkChallengeCleaned(context.Context, string, time.Time) error
}
// ZoneResolver returns the explicit credential and provider zone owning an
// ACME FQDN. It must not silently fall back to another credential.
type ZoneResolver func(context.Context, string) (provider.Auth, string, error)
// CredentialResolver loads the exact provider credential recorded when a
// challenge intent was created. It prevents a later preference change from
// redirecting cleanup through another token.
type CredentialResolver func(context.Context, string) (provider.Auth, error)
type presentedChallenge struct {
journalID string
auth provider.Auth
zoneID string
recordID string
}
// JournaledDNSProvider adapts DomainOps' provider-neutral DNS solver to lego's
// challenge interface. Every exact record ID is durable before Present returns.
type JournaledDNSProvider struct {
Solver provider.DNS01Solver
Repository ChallengeRepository
Resolve ZoneResolver
JobID string
PropagationTimeout time.Duration
PollingInterval time.Duration
OnWriteObserved func(context.Context, string, string) error
mu sync.Mutex
presented map[string]presentedChallenge
}
func NewJournaledDNSProvider(solver provider.DNS01Solver, repository ChallengeRepository, resolve ZoneResolver, jobID string) *JournaledDNSProvider {
return &JournaledDNSProvider{
Solver: solver,
Repository: repository,
Resolve: resolve,
JobID: jobID,
PropagationTimeout: 2 * time.Minute,
PollingInterval: 2 * time.Second,
presented: make(map[string]presentedChallenge),
}
}
func (p *JournaledDNSProvider) Present(ctx context.Context, domainName, token, keyAuth string) error {
if p == nil || p.Solver == nil || p.Repository == nil || p.Resolve == nil {
return errors.New("DNS-01 provider is not fully configured")
}
info := dns01.GetChallengeInfo(ctx, domainName, keyAuth)
auth, zoneID, err := p.Resolve(ctx, info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("resolve DNS-01 zone for %s: %w", info.EffectiveFQDN, err)
}
digest := sha256.Sum256([]byte(info.Value))
journal := domain.ChallengeJournal{
ID: identifier.New("challenge"), JobID: p.JobID, CredentialID: auth.CredentialID,
ZoneID: zoneID, FQDN: info.EffectiveFQDN, ValueHash: hex.EncodeToString(digest[:]), CreatedAt: time.Now().UTC(),
}
// Persist intent before the provider call so an ambiguous response can be
// reconciled by owner, job marker, and value hash on the next unlock.
if err := p.Repository.SaveChallenge(ctx, journal); err != nil {
return fmt.Errorf("persist DNS-01 challenge intent: %w", err)
}
recordID, err := p.Solver.PresentDNS01(ctx, auth, zoneID, info.EffectiveFQDN, info.Value, p.JobID)
if err != nil {
return fmt.Errorf("create DNS-01 record %s: %w", info.EffectiveFQDN, err)
}
journal.RecordID = recordID
if err := p.Repository.SaveChallenge(ctx, journal); err != nil {
cleanupErr := p.Solver.CleanupDNS01(ctx, auth, zoneID, recordID)
if cleanupErr == nil {
_ = p.Repository.MarkChallengeCleaned(context.WithoutCancel(ctx), journal.ID, time.Now().UTC())
return fmt.Errorf("persist DNS-01 record identity: %w", err)
}
return errors.Join(fmt.Errorf("persist DNS-01 record identity: %w", err), fmt.Errorf("rollback DNS-01 record %s: %w", recordID, cleanupErr))
}
if p.OnWriteObserved != nil {
_ = p.OnWriteObserved(context.WithoutCancel(ctx), auth.CredentialID, zoneID)
}
p.mu.Lock()
p.presented[challengeKey(domainName, token)] = presentedChallenge{
journalID: journal.ID,
auth: auth,
zoneID: zoneID,
recordID: recordID,
}
p.mu.Unlock()
return nil
}
func (p *JournaledDNSProvider) CleanUp(ctx context.Context, domainName, token, _ string) error {
if p == nil {
return errors.New("DNS-01 provider is nil")
}
key := challengeKey(domainName, token)
p.mu.Lock()
presented, ok := p.presented[key]
p.mu.Unlock()
if !ok {
return fmt.Errorf("DNS-01 record for %s is not present in this process", domainName)
}
if err := p.Solver.CleanupDNS01(ctx, presented.auth, presented.zoneID, presented.recordID); err != nil {
return fmt.Errorf("delete DNS-01 record %s: %w", presented.recordID, err)
}
cleanedAt := time.Now().UTC()
if err := p.Repository.MarkChallengeCleaned(ctx, presented.journalID, cleanedAt); err != nil {
return fmt.Errorf("mark DNS-01 challenge %s cleaned: %w", presented.journalID, err)
}
p.mu.Lock()
delete(p.presented, key)
p.mu.Unlock()
return nil
}
func (p *JournaledDNSProvider) Timeout() (time.Duration, time.Duration) {
timeout, interval := p.PropagationTimeout, p.PollingInterval
if timeout <= 0 {
timeout = 2 * time.Minute
}
if interval <= 0 {
interval = 2 * time.Second
}
return timeout, interval
}
// CleanupOpenChallenges recovers exact record IDs left by an interrupted
// process. A challenge is marked clean only after the provider confirms delete.
func CleanupOpenChallenges(ctx context.Context, repository ChallengeRepository, solver provider.DNS01Solver, resolve ZoneResolver, resolveCredential CredentialResolver) error {
if repository == nil || solver == nil || resolve == nil {
return errors.New("challenge cleanup is not fully configured")
}
challenges, err := repository.ListOpenChallenges(ctx)
if err != nil {
return fmt.Errorf("list open DNS-01 challenges: %w", err)
}
var cleanupErrors []error
for _, journal := range challenges {
if ctx.Err() != nil {
cleanupErrors = append(cleanupErrors, ctx.Err())
break
}
var auth provider.Auth
zoneID := journal.ZoneID
if journal.CredentialID != "" && resolveCredential != nil {
auth, err = resolveCredential(ctx, journal.CredentialID)
if err != nil {
cleanupErrors = append(cleanupErrors, fmt.Errorf("load challenge %s credential %s: %w", journal.ID, journal.CredentialID, err))
continue
}
} else {
var resolvedZoneID string
auth, resolvedZoneID, err = resolve(ctx, journal.FQDN)
if err != nil {
cleanupErrors = append(cleanupErrors, fmt.Errorf("resolve challenge %s: %w", journal.ID, err))
continue
}
if zoneID == "" {
zoneID = resolvedZoneID
}
if resolvedZoneID != "" && zoneID != resolvedZoneID {
cleanupErrors = append(cleanupErrors, fmt.Errorf("challenge %s zone changed from %s to %s", journal.ID, zoneID, resolvedZoneID))
continue
}
}
if zoneID == "" {
cleanupErrors = append(cleanupErrors, fmt.Errorf("challenge %s has no provider zone ID", journal.ID))
continue
}
if journal.RecordID == "" {
reconciler, ok := solver.(provider.DNS01Reconciler)
if !ok {
cleanupErrors = append(cleanupErrors, fmt.Errorf("challenge %s has an unresolved create intent and provider cannot reconcile it", journal.ID))
continue
}
recordID, found, reconcileErr := reconciler.ReconcileDNS01(ctx, auth, zoneID, journal.FQDN, journal.ValueHash, journal.JobID)
if reconcileErr != nil {
cleanupErrors = append(cleanupErrors, fmt.Errorf("reconcile challenge %s: %w", journal.ID, reconcileErr))
continue
}
if !found {
cleanedAt := time.Now().UTC()
if markErr := repository.MarkChallengeCleaned(ctx, journal.ID, cleanedAt); markErr != nil {
cleanupErrors = append(cleanupErrors, fmt.Errorf("close absent challenge intent %s: %w", journal.ID, markErr))
}
continue
}
journal.RecordID = recordID
if saveErr := repository.SaveChallenge(ctx, journal); saveErr != nil {
cleanupErrors = append(cleanupErrors, fmt.Errorf("save reconciled challenge %s: %w", journal.ID, saveErr))
continue
}
}
if cleanupErr := solver.CleanupDNS01(ctx, auth, zoneID, journal.RecordID); cleanupErr != nil {
cleanupErrors = append(cleanupErrors, fmt.Errorf("clean challenge %s record %s: %w", journal.ID, journal.RecordID, cleanupErr))
continue
}
cleanedAt := time.Now().UTC()
if markErr := repository.MarkChallengeCleaned(ctx, journal.ID, cleanedAt); markErr != nil {
cleanupErrors = append(cleanupErrors, fmt.Errorf("mark challenge %s cleaned: %w", journal.ID, markErr))
}
}
return errors.Join(cleanupErrors...)
}
func challengeKey(domainName, token string) string {
return domainName + "\x00" + token
}
+474
View File
@@ -0,0 +1,474 @@
package certificates
import (
"context"
"crypto"
"crypto/x509"
"errors"
"fmt"
"net/http"
"slices"
"sync"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
"github.com/go-acme/lego/v5/acme"
"github.com/go-acme/lego/v5/acme/api"
"github.com/go-acme/lego/v5/certcrypto"
"github.com/go-acme/lego/v5/certificate"
"github.com/go-acme/lego/v5/challenge"
"github.com/go-acme/lego/v5/lego"
)
const maxIssuanceConcurrency = 3
type EngineRepository interface {
AccountRepository
ChallengeRepository
}
type CertificateBackend interface {
Obtain(context.Context, certificate.ObtainRequest) (*certificate.Resource, error)
RevokeWithReason(context.Context, []byte, *uint) error
GetRenewalInfo(context.Context, *x509.Certificate) (*certificate.RenewalInfo, error)
}
type BackendFactory interface {
New(context.Context, AccountMaterial, challenge.Provider) (CertificateBackend, error)
}
type PreflightHook func(context.Context, Plan) error
type Engine struct {
accounts *AccountService
repository EngineRepository
solver provider.DNS01Solver
resolve ZoneResolver
factory BackendFactory
preflights []PreflightHook
writeObserver func(context.Context, string, string) error
concurrency int
}
type EngineOption func(*Engine)
func WithBackendFactory(factory BackendFactory) EngineOption {
return func(engine *Engine) {
if factory != nil {
engine.factory = factory
}
}
}
func WithPreflight(hook PreflightHook) EngineOption {
return func(engine *Engine) {
if hook != nil {
engine.preflights = append(engine.preflights, hook)
}
}
}
func WithDNSWriteObserver(observer func(context.Context, string, string) error) EngineOption {
return func(engine *Engine) {
engine.writeObserver = observer
}
}
func WithIssuanceConcurrency(concurrency int) EngineOption {
return func(engine *Engine) {
if concurrency > 0 {
engine.concurrency = min(concurrency, maxIssuanceConcurrency)
}
}
}
func WithACMEHTTPClient(client *http.Client, userAgent string) EngineOption {
return func(engine *Engine) {
engine.accounts.HTTPClient = client
engine.accounts.UserAgent = userAgent
engine.factory = &legoBackendFactory{HTTPClient: client, UserAgent: userAgent}
}
}
func NewEngine(repository EngineRepository, secrets SecretStore, solver provider.DNS01Solver, resolve ZoneResolver, options ...EngineOption) *Engine {
engine := &Engine{
accounts: &AccountService{Repository: repository, Secrets: secrets},
repository: repository,
solver: solver,
resolve: resolve,
factory: &legoBackendFactory{},
concurrency: maxIssuanceConcurrency,
}
for _, option := range options {
option(engine)
}
return engine
}
func (e *Engine) Accounts() *AccountService { return e.accounts }
type IssueRequest struct {
JobID string `json:"job_id"`
Environment string `json:"environment"`
Plan Plan `json:"plan"`
ConfirmProduction bool `json:"confirm_production"`
ReplacesCertID string `json:"-"`
}
type IssueResult struct {
Plan Plan `json:"plan"`
Environment string `json:"environment"`
Artifact Artifact `json:"-"`
RenewalWindow RenewalWindow `json:"renewal_window"`
}
func (e *Engine) Issue(ctx context.Context, request IssueRequest) (IssueResult, error) {
if e == nil || e.repository == nil || e.solver == nil || e.resolve == nil || e.factory == nil {
return IssueResult{}, errors.New("certificate engine is not fully configured")
}
if err := ValidatePlan(request.Plan); err != nil {
return IssueResult{}, err
}
if _, err := DirectoryForEnvironment(request.Environment); err != nil {
return IssueResult{}, err
}
if request.Environment == EnvironmentProduction && !request.ConfirmProduction {
return IssueResult{}, errors.New("production issuance requires explicit confirmation")
}
for _, preflight := range e.preflights {
if err := preflight(ctx, request.Plan); err != nil {
return IssueResult{}, fmt.Errorf("certificate preflight: %w", err)
}
}
if err := ctx.Err(); err != nil {
return IssueResult{}, err
}
account, err := e.accounts.Load(ctx, request.Environment)
if err != nil {
return IssueResult{}, err
}
dnsProvider := NewJournaledDNSProvider(e.solver, e.repository, e.resolve, request.JobID)
dnsProvider.OnWriteObserved = e.writeObserver
backend, err := e.factory.New(ctx, account, dnsProvider)
if err != nil {
return IssueResult{}, fmt.Errorf("create ACME backend: %w", err)
}
privateKey, err := GeneratePrivateKey(request.Plan.KeyAlgorithm)
if err != nil {
return IssueResult{}, err
}
resource, err := backend.Obtain(ctx, certificate.ObtainRequest{
Domains: slices.Clone(request.Plan.Identifiers),
PrivateKey: privateKey,
KeyType: certcrypto.KeyType(request.Plan.KeyAlgorithm),
Bundle: false,
EnableCommonName: true,
Profile: request.Plan.Profile,
ReplacesCertID: request.ReplacesCertID,
AlwaysDeactivateAuthorizations: true,
})
if err != nil {
return IssueResult{}, fmt.Errorf("obtain certificate for %s: %w", request.Plan.Name, err)
}
artifact, err := artifactFromResource(resource, privateKey, request.Plan.Identifiers)
if err != nil {
return IssueResult{}, fmt.Errorf("validate ACME result: %w", err)
}
leaf, _, _, _, err := ParseCertificatePEM(artifact.CertificatePEM)
if err != nil {
return IssueResult{}, fmt.Errorf("parse issued certificate for renewal scheduling: %w", err)
}
renewalWindow := fallbackRenewalWindow(leaf)
if ariWindow, ariErr := queryRenewalWindow(ctx, backend, leaf); ariErr == nil {
renewalWindow = ariWindow
}
return IssueResult{
Plan: request.Plan,
Environment: request.Environment,
Artifact: artifact,
RenewalWindow: renewalWindow,
}, nil
}
type BatchResult struct {
Request IssueRequest `json:"request"`
Result IssueResult `json:"-"`
Error error `json:"-"`
}
// IssueBatch preserves input order and caps active orders at three even when a
// caller asks for more. Each plan remains an independent certificate order.
func (e *Engine) IssueBatch(ctx context.Context, requests []IssueRequest) []BatchResult {
results := make([]BatchResult, len(requests))
for index := range requests {
results[index].Request = requests[index]
}
if len(requests) == 0 {
return results
}
concurrency := maxIssuanceConcurrency
if e != nil && e.concurrency > 0 {
concurrency = min(e.concurrency, maxIssuanceConcurrency)
}
concurrency = min(concurrency, len(requests))
jobs := make(chan int)
var workers sync.WaitGroup
for range concurrency {
workers.Add(1)
go func() {
defer workers.Done()
for index := range jobs {
results[index].Result, results[index].Error = e.Issue(ctx, requests[index])
}
}()
}
next := 0
send:
for ; next < len(requests); next++ {
select {
case jobs <- next:
case <-ctx.Done():
break send
}
}
close(jobs)
workers.Wait()
for ; next < len(requests); next++ {
results[next].Error = ctx.Err()
}
return results
}
type RenewRequest struct {
IssueRequest
PreviousCertificatePEM []byte `json:"-"`
}
// Renew obtains a replacement with a fresh private key. It deliberately does
// not reuse the prior key, even when the CA would permit it.
func (e *Engine) Renew(ctx context.Context, request RenewRequest) (IssueResult, error) {
previousCertificate, _, _, previous, err := ParseCertificatePEM(request.PreviousCertificatePEM)
if err != nil {
return IssueResult{}, fmt.Errorf("parse previous certificate: %w", err)
}
expected := slices.Clone(request.Plan.Identifiers)
actual := slices.Clone(previous.Identifiers)
slices.Sort(expected)
slices.Sort(actual)
if !slices.Equal(expected, actual) {
return IssueResult{}, errors.New("renewal plan identifiers differ from the previous certificate")
}
certID, err := api.MakeARICertID(previousCertificate)
if err != nil {
return IssueResult{}, fmt.Errorf("build ARI replacement certificate ID: %w", err)
}
request.IssueRequest.ReplacesCertID = certID
return e.Issue(ctx, request.IssueRequest)
}
type RevokeRequest struct {
Environment string
Lineage domain.CertificateLineage
CertificatePEM []byte
Reason *uint
ConfirmRevocation bool
}
func (e *Engine) Revoke(ctx context.Context, request RevokeRequest) error {
if !request.ConfirmRevocation {
return errors.New("certificate revocation requires explicit confirmation")
}
if request.Lineage.Source != domain.CertificateManaged {
return errors.New("only certificates managed by DomainOps can be revoked")
}
if _, _, _, _, err := ParseCertificatePEM(request.CertificatePEM); err != nil {
return err
}
account, err := e.accounts.Load(ctx, request.Environment)
if err != nil {
return err
}
backend, err := e.factory.New(ctx, account, nil)
if err != nil {
return fmt.Errorf("create ACME backend: %w", err)
}
if err := backend.RevokeWithReason(ctx, request.CertificatePEM, request.Reason); err != nil {
return fmt.Errorf("revoke certificate: %w", err)
}
return nil
}
// IsAlreadyRevoked reports the standardized ACME alreadyRevoked response. It
// lets a durable local revocation intent converge after the CA succeeded but
// the prior local state update failed.
func IsAlreadyRevoked(err error) bool {
var problem *acme.ProblemDetails
return errors.As(err, &problem) && problem.Type == acme.AlreadyRevokedErrorType
}
type RenewalWindow struct {
Start time.Time `json:"start"`
End time.Time `json:"end"`
ARI bool `json:"ari"`
ExplanationURL string `json:"explanation_url,omitempty"`
RetryAfter time.Duration `json:"retry_after,omitempty"`
}
func (e *Engine) RenewalInfo(ctx context.Context, environment string, certificatePEM []byte) (RenewalWindow, error) {
leaf, _, _, _, err := ParseCertificatePEM(certificatePEM)
if err != nil {
return RenewalWindow{}, err
}
account, err := e.accounts.Load(ctx, environment)
if err != nil {
return RenewalWindow{}, err
}
backend, err := e.factory.New(ctx, account, nil)
if err != nil {
return RenewalWindow{}, fmt.Errorf("create ACME backend: %w", err)
}
window, err := queryRenewalWindow(ctx, backend, leaf)
if err != nil {
return fallbackRenewalWindow(leaf), fmt.Errorf("query ACME renewal information: %w", err)
}
return window, nil
}
func fallbackRenewalWindow(certificate *x509.Certificate) RenewalWindow {
return fallbackRenewalWindowForValidity(certificate.NotBefore, certificate.NotAfter)
}
func fallbackRenewalWindowForValidity(notBefore, notAfter time.Time) RenewalWindow {
notBefore = notBefore.UTC()
notAfter = notAfter.UTC()
if notBefore.IsZero() || !notAfter.After(notBefore) {
return RenewalWindow{}
}
lifetime := notAfter.Sub(notBefore)
window := RenewalWindow{
Start: notBefore.Add(lifetime * 2 / 3).UTC(),
End: notBefore.Add(lifetime * 5 / 6).UTC(),
ARI: false,
}
if !validRenewalWindow(window, notBefore, notAfter) {
return RenewalWindow{}
}
return window
}
func queryRenewalWindow(ctx context.Context, backend CertificateBackend, certificate *x509.Certificate) (RenewalWindow, error) {
info, err := backend.GetRenewalInfo(ctx, certificate)
if err != nil {
return RenewalWindow{}, err
}
if info == nil || info.ExtendedRenewalInfo == nil {
return RenewalWindow{}, errors.New("ACME server returned no renewal information")
}
window := normalizeRenewalWindow(RenewalWindow{
Start: info.SuggestedWindow.Start,
End: info.SuggestedWindow.End,
ARI: true,
ExplanationURL: info.ExplanationURL,
RetryAfter: info.RetryAfter,
})
if !validRenewalWindow(window, certificate.NotBefore, certificate.NotAfter) {
return RenewalWindow{}, errors.New("ACME server returned an invalid renewal window")
}
return window, nil
}
func normalizeRenewalWindow(window RenewalWindow) RenewalWindow {
window.Start = window.Start.UTC()
window.End = window.End.UTC()
return window
}
func validRenewalWindow(window RenewalWindow, notBefore, notAfter time.Time) bool {
window = normalizeRenewalWindow(window)
notBefore = notBefore.UTC()
notAfter = notAfter.UTC()
if window.Start.IsZero() || window.End.IsZero() || !window.End.After(window.Start) {
return false
}
if notBefore.IsZero() || !notAfter.After(notBefore) {
return false
}
if window.Start.Before(notBefore) || window.End.After(notAfter) {
return false
}
return window.RetryAfter >= 0
}
func artifactFromResource(resource *certificate.Resource, privateKey crypto.Signer, expected []string) (Artifact, error) {
if resource == nil {
return Artifact{}, errors.New("ACME server returned no certificate resource")
}
_, leafPEM, embeddedChain, metadata, err := ParseCertificatePEM(resource.Certificate)
if err != nil {
return Artifact{}, err
}
chain := append(slices.Clone(embeddedChain), resource.IssuerCertificate...)
keyPEM, err := MarshalPrivateKeyPKCS8(privateKey)
if err != nil {
return Artifact{}, err
}
artifact := Artifact{
CertificatePEM: leafPEM,
ChainPEM: chain,
PrivateKeyPEM: keyPEM,
Metadata: metadata,
}
if _, err := ValidateArtifact(artifact, expected); err != nil {
return Artifact{}, err
}
return artifact, nil
}
type legoBackendFactory struct {
HTTPClient *http.Client
UserAgent string
}
func (f *legoBackendFactory) New(_ context.Context, material AccountMaterial, dnsProvider challenge.Provider) (CertificateBackend, error) {
user := &legoUser{
email: material.Account.Email,
privateKey: material.PrivateKey,
registration: material.Registration,
}
config := lego.NewConfig(user)
config.CADirURL = material.Account.DirectoryURL
if f.HTTPClient != nil {
config.HTTPClient = f.HTTPClient
}
if f.UserAgent != "" {
config.UserAgent = f.UserAgent
}
client, err := lego.NewClient(config)
if err != nil {
return nil, err
}
if dnsProvider != nil {
if err := client.Challenge.SetDNS01Provider(dnsProvider); err != nil {
return nil, fmt.Errorf("configure DNS-01 provider: %w", err)
}
}
return legoCertificateBackend{certifier: client.Certificate}, nil
}
type legoCertificateBackend struct {
certifier *certificate.Certifier
}
func (b legoCertificateBackend) Obtain(ctx context.Context, request certificate.ObtainRequest) (*certificate.Resource, error) {
return b.certifier.Obtain(ctx, request)
}
func (b legoCertificateBackend) RevokeWithReason(ctx context.Context, certificatePEM []byte, reason *uint) error {
return b.certifier.RevokeWithReason(ctx, certificatePEM, reason)
}
func (b legoCertificateBackend) GetRenewalInfo(ctx context.Context, certificate *x509.Certificate) (*certificate.RenewalInfo, error) {
return b.certifier.GetRenewalInfo(ctx, certificate)
}
+508
View File
@@ -0,0 +1,508 @@
package certificates
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/identifier"
)
type ExportMetadata struct {
SchemaVersion int `json:"schema_version"`
Lineage domain.CertificateLineage `json:"lineage"`
Version domain.CertificateVersion `json:"version"`
Certificate Metadata `json:"certificate"`
ExportedAt time.Time `json:"exported_at"`
}
type ExportResult struct {
VersionDirectory string `json:"version_directory"`
CurrentLink string `json:"current_link"`
CertificatePath string `json:"certificate_path"`
ChainPath string `json:"chain_path"`
FullChainPath string `json:"fullchain_path"`
PrivateKeyPath string `json:"private_key_path"`
MetadataPath string `json:"metadata_path"`
}
// ExportVersion atomically installs an immutable version directory and then
// atomically moves the "current" symlink. A failed write can therefore never
// expose a half-written certificate as current.
func ExportVersion(root string, lineage domain.CertificateLineage, version domain.CertificateVersion, artifact Artifact, now time.Time) (ExportResult, error) {
if err := EnsurePrivateDirectoryDurable(root); err != nil {
return ExportResult{}, fmt.Errorf("prepare explicit export root: %w", err)
}
if err := prepareExplicitExportRetry(root, version.ID); err != nil {
return ExportResult{}, err
}
result, exists, err := existingExplicitExport(root, lineage, version, artifact)
if err != nil {
return ExportResult{}, err
}
if !exists {
result, err = InstallVersion(root, lineage, version, artifact, now)
if err != nil {
return ExportResult{}, err
}
}
if err := ActivateVersion(root, version.ID); err != nil {
return result, err
}
result.CurrentLink = filepath.Join(root, "current")
return result, nil
}
func prepareExplicitExportRetry(root, versionID string) error {
if strings.TrimSpace(root) == "" {
return errors.New("export root is required")
}
if err := safePathComponent(versionID); err != nil {
return fmt.Errorf("version ID: %w", err)
}
if _, err := os.Stat(root); errors.Is(err, os.ErrNotExist) {
return nil
} else if err != nil {
return fmt.Errorf("inspect export root: %w", err)
}
for _, path := range []string{
filepath.Join(root, ".tmp-"+versionID),
} {
if err := os.RemoveAll(path); err != nil {
return fmt.Errorf("clean prior explicit export %s: %w", filepath.Base(path), err)
}
}
if err := syncDirectory(root); err != nil {
return fmt.Errorf("persist explicit export cleanup: %w", err)
}
return nil
}
func existingExplicitExport(root string, lineage domain.CertificateLineage, version domain.CertificateVersion, expected Artifact) (ExportResult, bool, error) {
versionDirectory := filepath.Join(root, version.ID)
info, err := os.Lstat(versionDirectory)
if errors.Is(err, os.ErrNotExist) {
return ExportResult{}, false, nil
}
if err != nil {
return ExportResult{}, false, fmt.Errorf("inspect existing explicit export: %w", err)
}
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
return ExportResult{}, true, errors.New("existing explicit export version is not a directory")
}
if info.Mode().Perm() != 0o700 {
return ExportResult{}, true, fmt.Errorf("existing explicit export directory permissions are %04o, want 0700", info.Mode().Perm())
}
result := ExportResult{
VersionDirectory: versionDirectory,
CertificatePath: filepath.Join(versionDirectory, "cert.pem"),
ChainPath: filepath.Join(versionDirectory, "chain.pem"),
FullChainPath: filepath.Join(versionDirectory, "fullchain.pem"),
PrivateKeyPath: filepath.Join(versionDirectory, "privkey.pem"),
MetadataPath: filepath.Join(versionDirectory, "metadata.json"),
}
certificatePEM, err := readPrivateRegularFile(result.CertificatePath)
if err != nil {
return ExportResult{}, true, fmt.Errorf("read existing explicit certificate: %w", err)
}
chainPEM, err := readPrivateRegularFile(result.ChainPath)
if err != nil {
return ExportResult{}, true, fmt.Errorf("read existing explicit chain: %w", err)
}
fullChainPEM, err := readPrivateRegularFile(result.FullChainPath)
if err != nil {
return ExportResult{}, true, fmt.Errorf("read existing explicit full chain: %w", err)
}
keyPEM, err := readPrivateRegularFile(result.PrivateKeyPath)
if err != nil {
return ExportResult{}, true, fmt.Errorf("read existing explicit private key: %w", err)
}
metadataJSON, err := readPrivateRegularFile(result.MetadataPath)
if err != nil {
return ExportResult{}, true, fmt.Errorf("read existing explicit metadata: %w", err)
}
identifiers := version.Identifiers
if len(identifiers) == 0 {
identifiers = expected.Metadata.Identifiers
}
if _, err := ValidateArtifact(expected, identifiers); err != nil {
return ExportResult{}, true, fmt.Errorf("validate expected explicit export: %w", err)
}
_, expectedLeafPEM, expectedChainPEM, expectedMetadata, err := ParseCertificatePEM(append(slices.Clone(expected.CertificatePEM), expected.ChainPEM...))
if err != nil {
return ExportResult{}, true, fmt.Errorf("parse expected explicit export: %w", err)
}
expectedKey, err := ParsePrivateKeyPEM(expected.PrivateKeyPEM)
if err != nil {
return ExportResult{}, true, fmt.Errorf("parse expected explicit private key: %w", err)
}
expectedKeyPEM, err := MarshalPrivateKeyPKCS8(expectedKey)
if err != nil {
return ExportResult{}, true, fmt.Errorf("encode expected explicit private key: %w", err)
}
if err := validateVersionMaterial(version, expectedMetadata); err != nil {
return ExportResult{}, true, err
}
if _, err := ValidateArtifact(Artifact{CertificatePEM: certificatePEM, ChainPEM: chainPEM, PrivateKeyPEM: keyPEM}, identifiers); err != nil {
return ExportResult{}, true, fmt.Errorf("validate existing explicit export: %w", err)
}
if !bytes.Equal(certificatePEM, expectedLeafPEM) || !bytes.Equal(chainPEM, expectedChainPEM) || !bytes.Equal(keyPEM, expectedKeyPEM) {
return ExportResult{}, true, errors.New("existing explicit export belongs to different certificate material")
}
expectedFullChain := append(slices.Clone(expectedLeafPEM), expectedChainPEM...)
if !bytes.Equal(fullChainPEM, expectedFullChain) {
return ExportResult{}, true, errors.New("existing explicit full chain does not match certificate and chain")
}
if err := validateExistingExportMetadata(metadataJSON, result, lineage, version, expectedMetadata); err != nil {
return ExportResult{}, true, err
}
return result, true, nil
}
func readPrivateRegularFile(path string) ([]byte, error) {
info, err := os.Lstat(path)
if err != nil {
return nil, err
}
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
return nil, errors.New("path is not a regular, non-symlink file")
}
if info.Mode().Perm() != 0o600 {
return nil, fmt.Errorf("permissions are %04o, want 0600", info.Mode().Perm())
}
return os.ReadFile(path)
}
func validateVersionMaterial(version domain.CertificateVersion, metadata Metadata) error {
if version.FingerprintSHA256 == "" || !strings.EqualFold(version.FingerprintSHA256, metadata.FingerprintSHA256) ||
version.SerialNumber != metadata.SerialNumber || version.Issuer != metadata.Issuer ||
!slices.Equal(version.Identifiers, metadata.Identifiers) ||
!version.NotBefore.Equal(metadata.NotBefore) || !version.NotAfter.Equal(metadata.NotAfter) {
return errors.New("certificate version metadata does not match expected certificate material")
}
return nil
}
func validateExistingExportMetadata(data []byte, result ExportResult, lineage domain.CertificateLineage, version domain.CertificateVersion, certificateMetadata Metadata) error {
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields()
var actual ExportMetadata
if err := decoder.Decode(&actual); err != nil {
return fmt.Errorf("parse existing explicit metadata: %w", err)
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return errors.New("parse existing explicit metadata: trailing JSON data")
}
if actual.SchemaVersion != 1 || actual.ExportedAt.IsZero() {
return errors.New("existing explicit metadata has an unsupported schema or missing export time")
}
exportedAt := actual.ExportedAt.UTC()
expectedVersion := version
expectedVersion.ExportedAt = &exportedAt
expectedVersion.ExportPath = result.VersionDirectory
expectedVersion.CertificatePath = result.CertificatePath
expectedVersion.ChainPath = result.ChainPath
expected := ExportMetadata{
SchemaVersion: 1,
Lineage: lineage,
Version: expectedVersion,
Certificate: certificateMetadata,
ExportedAt: exportedAt,
}
actualJSON, err := json.Marshal(actual)
if err != nil {
return fmt.Errorf("encode existing explicit metadata: %w", err)
}
expectedJSON, err := json.Marshal(expected)
if err != nil {
return fmt.Errorf("encode expected explicit metadata: %w", err)
}
if !bytes.Equal(actualJSON, expectedJSON) {
return errors.New("existing explicit metadata does not match certificate version and material")
}
return nil
}
// InstallVersion durably installs immutable PEM material without advancing
// the current symlink. Managed lifecycle commits use this split phase so the
// database becomes authoritative before filesystem activation.
func InstallVersion(root string, lineage domain.CertificateLineage, version domain.CertificateVersion, artifact Artifact, now time.Time) (ExportResult, error) {
if root == "" {
return ExportResult{}, errors.New("export root is required")
}
if err := safePathComponent(version.ID); err != nil {
return ExportResult{}, fmt.Errorf("version ID: %w", err)
}
if version.LineageID != "" && lineage.ID != "" && version.LineageID != lineage.ID {
return ExportResult{}, errors.New("certificate version belongs to another lineage")
}
if _, err := ValidateArtifact(artifact, version.Identifiers); err != nil {
return ExportResult{}, fmt.Errorf("validate certificate material: %w", err)
}
_, leafPEM, parsedChain, metadata, err := ParseCertificatePEM(append(slices.Clone(artifact.CertificatePEM), artifact.ChainPEM...))
if err != nil {
return ExportResult{}, err
}
if err := validateVersionMaterial(version, metadata); err != nil {
return ExportResult{}, err
}
key, err := ParsePrivateKeyPEM(artifact.PrivateKeyPEM)
if err != nil {
return ExportResult{}, err
}
keyPEM, err := MarshalPrivateKeyPKCS8(key)
if err != nil {
return ExportResult{}, err
}
if err := EnsurePrivateDirectoryDurable(root); err != nil {
return ExportResult{}, fmt.Errorf("prepare export root: %w", err)
}
// The commit journal records the final version path. Deriving the temporary
// directory from the same immutable version ID lets startup recovery find
// and remove plaintext key material even if the process exits before rename.
tempName := ".tmp-" + version.ID
tempDir := filepath.Join(root, tempName)
if err := os.Mkdir(tempDir, 0o700); err != nil {
return ExportResult{}, fmt.Errorf("create temporary export directory: %w", err)
}
removeTemp := true
defer func() {
if removeTemp {
_ = os.RemoveAll(tempDir)
}
}()
version.ExportedAt = pointer(now.UTC())
version.ExportPath = filepath.Join(root, version.ID)
version.CertificatePath = filepath.Join(version.ExportPath, "cert.pem")
version.ChainPath = filepath.Join(version.ExportPath, "chain.pem")
exportMetadata := ExportMetadata{
SchemaVersion: 1,
Lineage: lineage,
Version: version,
Certificate: metadata,
ExportedAt: now.UTC(),
}
metadataJSON, err := json.MarshalIndent(exportMetadata, "", " ")
if err != nil {
return ExportResult{}, fmt.Errorf("encode export metadata: %w", err)
}
metadataJSON = append(metadataJSON, byte(10))
fullchain := append(slices.Clone(leafPEM), parsedChain...)
files := map[string][]byte{
"cert.pem": leafPEM,
"chain.pem": parsedChain,
"fullchain.pem": fullchain,
"privkey.pem": keyPEM,
"metadata.json": metadataJSON,
}
for name, contents := range files {
if err := writeExclusive(filepath.Join(tempDir, name), contents, 0o600); err != nil {
return ExportResult{}, err
}
}
if err := syncDirectory(tempDir); err != nil {
return ExportResult{}, err
}
versionDir := filepath.Join(root, version.ID)
if err := os.Rename(tempDir, versionDir); err != nil {
return ExportResult{}, fmt.Errorf("install certificate version: %w", err)
}
removeTemp = false
if err := syncDirectory(root); err != nil {
return ExportResult{}, err
}
return ExportResult{
VersionDirectory: versionDir,
CertificatePath: filepath.Join(versionDir, "cert.pem"),
ChainPath: filepath.Join(versionDir, "chain.pem"),
FullChainPath: filepath.Join(versionDir, "fullchain.pem"),
PrivateKeyPath: filepath.Join(versionDir, "privkey.pem"),
MetadataPath: filepath.Join(versionDir, "metadata.json"),
}, nil
}
// EnsurePrivateDirectoryDurable creates every missing directory component with
// owner-only permissions and fsyncs each modified parent. It also syncs an
// existing target and parent, covering directories created earlier in the same
// startup before a certificate commit relies on their persistence.
func EnsurePrivateDirectoryDurable(path string) error {
if strings.TrimSpace(path) == "" {
return errors.New("directory path is required")
}
absolute, err := filepath.Abs(path)
if err != nil {
return err
}
volume := filepath.VolumeName(absolute)
root := volume + string(filepath.Separator)
if filepath.Clean(absolute) == filepath.Clean(root) {
return errors.New("refusing to use the filesystem root as a private directory")
}
relative := strings.TrimPrefix(absolute, root)
current := root
for _, component := range strings.Split(relative, string(filepath.Separator)) {
if component == "" {
continue
}
current = filepath.Join(current, component)
info, statErr := os.Lstat(current)
created := false
if errors.Is(statErr, os.ErrNotExist) {
if err := os.Mkdir(current, 0o700); err != nil && !errors.Is(err, os.ErrExist) {
return fmt.Errorf("create directory %s: %w", current, err)
}
info, statErr = os.Lstat(current)
created = statErr == nil
}
if statErr != nil {
return fmt.Errorf("inspect directory %s: %w", current, statErr)
}
if info.Mode()&os.ModeSymlink != 0 {
if current == absolute || !trustedPlatformDirectoryAlias(current) {
return fmt.Errorf("directory path contains symbolic link %s", current)
}
continue
}
if !info.IsDir() {
return fmt.Errorf("%s is not a directory", current)
}
if created {
if err := os.Chmod(current, 0o700); err != nil {
return fmt.Errorf("secure directory %s: %w", current, err)
}
if err := syncDirectory(filepath.Dir(current)); err != nil {
return fmt.Errorf("persist directory %s: %w", current, err)
}
}
}
if err := os.Chmod(absolute, 0o700); err != nil {
return fmt.Errorf("secure directory %s: %w", absolute, err)
}
if err := syncDirectory(absolute); err != nil {
return err
}
if err := syncDirectory(filepath.Dir(absolute)); err != nil {
return err
}
return nil
}
func trustedPlatformDirectoryAlias(path string) bool {
if runtime.GOOS != "darwin" {
return false
}
want := map[string]string{
string(filepath.Separator) + "etc": "/private/etc",
string(filepath.Separator) + "tmp": "/private/tmp",
string(filepath.Separator) + "var": "/private/var",
}[filepath.Clean(path)]
if want == "" {
return false
}
resolved, err := filepath.EvalSymlinks(path)
return err == nil && filepath.Clean(resolved) == want
}
// ActivateVersion atomically points root/current at an already installed
// immutable version directory.
func ActivateVersion(root, versionID string) error {
if root == "" {
return errors.New("export root is required")
}
if err := safePathComponent(versionID); err != nil {
return fmt.Errorf("version ID: %w", err)
}
if err := EnsurePrivateDirectoryDurable(root); err != nil {
return fmt.Errorf("prepare activation root: %w", err)
}
info, err := os.Lstat(filepath.Join(root, versionID))
if err != nil {
return fmt.Errorf("stat certificate version: %w", err)
}
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
return errors.New("certificate version path is not a regular directory")
}
if info.Mode().Perm() != 0o700 {
return fmt.Errorf("certificate version directory permissions are %04o, want 0700", info.Mode().Perm())
}
current := filepath.Join(root, "current")
currentInfo, err := os.Lstat(current)
if err == nil && currentInfo.Mode()&os.ModeSymlink == 0 {
return errors.New("refusing to replace non-symlink current path")
}
if err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("inspect current certificate link: %w", err)
}
tempLink := filepath.Join(root, ".current-"+identifier.New("link"))
if err := os.Symlink(versionID, tempLink); err != nil {
return fmt.Errorf("create current symlink: %w", err)
}
if err := os.Rename(tempLink, current); err != nil {
_ = os.Remove(tempLink)
return fmt.Errorf("activate certificate version: %w", err)
}
if err := syncDirectory(root); err != nil {
return err
}
return nil
}
func writeExclusive(path string, data []byte, mode os.FileMode) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
if err != nil {
return fmt.Errorf("create %s: %w", filepath.Base(path), err)
}
ok := false
defer func() {
_ = file.Close()
if !ok {
_ = os.Remove(path)
}
}()
if _, err = file.Write(data); err != nil {
return fmt.Errorf("write %s: %w", filepath.Base(path), err)
}
if err = file.Sync(); err != nil {
return fmt.Errorf("sync %s: %w", filepath.Base(path), err)
}
if err = file.Close(); err != nil {
return fmt.Errorf("close %s: %w", filepath.Base(path), err)
}
ok = true
return nil
}
func syncDirectory(path string) error {
directory, err := os.Open(path)
if err != nil {
return fmt.Errorf("open directory for sync: %w", err)
}
defer directory.Close()
if err := directory.Sync(); err != nil {
return fmt.Errorf("sync directory: %w", err)
}
return nil
}
func safePathComponent(value string) error {
if value == "" || value == "." || value == ".." || filepath.Base(value) != value || strings.Contains(value, "/") || strings.Contains(value, string(filepath.Separator)) {
return errors.New("must be a non-empty path component")
}
return nil
}
func pointer[T any](value T) *T { return &value }
+94
View File
@@ -0,0 +1,94 @@
package certificates
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
// GeneratePrivateKey creates only the two key types intentionally supported by
// DomainOps v1. Randomness always comes from crypto/rand.
func GeneratePrivateKey(algorithm domain.KeyAlgorithm) (crypto.Signer, error) {
switch algorithm {
case domain.KeyECDSAP256:
return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case domain.KeyRSA2048:
return rsa.GenerateKey(rand.Reader, 2048)
default:
return nil, fmt.Errorf("unsupported key algorithm %q", algorithm)
}
}
// MarshalPrivateKeyPKCS8 returns a portable unencrypted PKCS#8 PEM. The bytes
// must be sent directly to the encrypted secret store or a mode-0600 export.
func MarshalPrivateKeyPKCS8(key crypto.Signer) ([]byte, error) {
if key == nil {
return nil, errors.New("private key is nil")
}
der, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return nil, fmt.Errorf("marshal private key: %w", err)
}
return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), nil
}
func ParsePrivateKeyPEM(data []byte) (crypto.Signer, error) {
block, rest := pem.Decode(data)
if block == nil || len(rest) != 0 {
return nil, errors.New("private key must contain exactly one PEM block")
}
var key any
var err error
switch block.Type {
case "PRIVATE KEY":
key, err = x509.ParsePKCS8PrivateKey(block.Bytes)
case "EC PRIVATE KEY":
key, err = x509.ParseECPrivateKey(block.Bytes)
case "RSA PRIVATE KEY":
key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
default:
return nil, fmt.Errorf("unsupported private key PEM type %q", block.Type)
}
if err != nil {
return nil, fmt.Errorf("parse private key: %w", err)
}
signer, ok := key.(crypto.Signer)
if !ok {
return nil, fmt.Errorf("private key type %T cannot sign", key)
}
switch typed := signer.(type) {
case *ecdsa.PrivateKey:
if typed.Curve != elliptic.P256() {
return nil, errors.New("only ECDSA P-256 keys are supported")
}
case *rsa.PrivateKey:
if typed.N.BitLen() != 2048 {
return nil, errors.New("only RSA-2048 keys are supported")
}
default:
return nil, fmt.Errorf("unsupported private key type %T", signer)
}
return signer, nil
}
func keyAlgorithm(key crypto.Signer) (domain.KeyAlgorithm, error) {
switch typed := key.(type) {
case *ecdsa.PrivateKey:
if typed.Curve == elliptic.P256() {
return domain.KeyECDSAP256, nil
}
case *rsa.PrivateKey:
if typed.N.BitLen() == 2048 {
return domain.KeyRSA2048, nil
}
}
return "", fmt.Errorf("unsupported private key type %T", key)
}
+404
View File
@@ -0,0 +1,404 @@
package certificates
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/identifier"
)
type CertificateRepository interface {
SaveCertificateLineage(context.Context, domain.CertificateLineage) error
SaveCertificateVersion(context.Context, domain.CertificateVersion) error
CommitCertificateVersion(context.Context, domain.CertificateLineage, domain.CertificateVersion) error
SaveCertificateCommitIntent(context.Context, domain.CertificateCommitIntent) error
ListCertificateCommitIntents(context.Context) ([]domain.CertificateCommitIntent, error)
DeleteCertificateCommitIntent(context.Context, string) error
}
type Lifecycle struct {
Repository CertificateRepository
Secrets SecretStore
Now func() time.Time
}
type CommitRequest struct {
ExistingLineage *domain.CertificateLineage
Plan Plan
ACMEAccountID string
Artifact Artifact
RenewalWindow *RenewalWindow
ExportRoot string
}
type CommitResult struct {
Lineage domain.CertificateLineage `json:"lineage"`
Version domain.CertificateVersion `json:"version"`
Export ExportResult `json:"export"`
Warnings []string `json:"warnings,omitempty"`
}
// CommitManaged validates and exports a new immutable version, stores the key
// in the encrypted vault, and advances the lineage only after the version row
// is durable. Previous versions are intentionally retained.
func (l *Lifecycle) CommitManaged(ctx context.Context, request CommitRequest) (CommitResult, error) {
if l == nil || l.Repository == nil || l.Secrets == nil {
return CommitResult{}, errors.New("certificate lifecycle is not fully configured")
}
if err := ValidatePlan(request.Plan); err != nil {
return CommitResult{}, err
}
if request.ACMEAccountID == "" {
return CommitResult{}, errors.New("ACME account ID is required")
}
if _, err := ValidateArtifact(request.Artifact, request.Plan.Identifiers); err != nil {
return CommitResult{}, err
}
_, _, _, parsedMetadata, err := ParseCertificatePEM(append(slices.Clone(request.Artifact.CertificatePEM), request.Artifact.ChainPEM...))
if err != nil {
return CommitResult{}, err
}
if parsedMetadata.KeyAlgorithm != request.Plan.KeyAlgorithm {
return CommitResult{}, fmt.Errorf("issued certificate key algorithm %s does not match plan %s", parsedMetadata.KeyAlgorithm, request.Plan.KeyAlgorithm)
}
// Never trust caller-supplied metadata for persistence or renewal timing;
// it is only a convenience cache on Artifact.
request.Artifact.Metadata = parsedMetadata
now := time.Now
if l.Now != nil {
now = l.Now
}
committedAt := now().UTC()
lineage := domain.CertificateLineage{}
if request.ExistingLineage != nil {
lineage = *request.ExistingLineage
lineage.Identifiers = slices.Clone(request.ExistingLineage.Identifiers)
if lineage.Source != domain.CertificateManaged {
return CommitResult{}, errors.New("an imported lineage cannot be converted to a managed lineage")
}
if lineage.ZoneID != "" && request.Plan.ZoneID != "" && lineage.ZoneID != request.Plan.ZoneID {
return CommitResult{}, errors.New("certificate plan belongs to another zone")
}
if lineage.ACMEAccountID != "" && lineage.ACMEAccountID != request.ACMEAccountID {
return CommitResult{}, errors.New("certificate lineage belongs to another ACME account")
}
} else {
lineage.ID = identifier.New("lineage")
lineage.Source = domain.CertificateManaged
lineage.CreatedAt = committedAt
}
lineage.Name = request.Plan.Name
lineage.ZoneID = request.Plan.ZoneID
lineage.Identifiers = slices.Clone(request.Plan.Identifiers)
lineage.KeyAlgorithm = request.Plan.KeyAlgorithm
lineage.Profile = request.Plan.Profile
lineage.ACMEAccountID = request.ACMEAccountID
lineage.UpdatedAt = committedAt
version := domain.CertificateVersion{
ID: identifier.New("certver"),
LineageID: lineage.ID,
SerialNumber: request.Artifact.Metadata.SerialNumber,
FingerprintSHA256: request.Artifact.Metadata.FingerprintSHA256,
Issuer: request.Artifact.Metadata.Issuer,
Identifiers: slices.Clone(request.Artifact.Metadata.Identifiers),
NotBefore: request.Artifact.Metadata.NotBefore,
NotAfter: request.Artifact.Metadata.NotAfter,
CreatedAt: committedAt,
}
window := fallbackRenewalWindowFromMetadata(request.Artifact.Metadata)
if request.RenewalWindow != nil {
candidate := normalizeRenewalWindow(*request.RenewalWindow)
if validRenewalWindow(candidate, request.Artifact.Metadata.NotBefore, request.Artifact.Metadata.NotAfter) {
window = candidate
}
}
version.RenewalWindowStart = &window.Start
version.RenewalWindowEnd = &window.End
intent := domain.CertificateCommitIntent{
VersionID: version.ID, LineageID: lineage.ID,
SecretRef: "certificate-key/" + version.ID,
ArtifactPath: filepath.Join(request.ExportRoot, version.ID), CreatedAt: committedAt,
}
if err := l.Repository.SaveCertificateCommitIntent(ctx, intent); err != nil {
return CommitResult{}, fmt.Errorf("journal certificate commit intent: %w", err)
}
secretRef, err := l.Secrets.Put(ctx, intent.SecretRef, request.Artifact.PrivateKeyPEM)
if err != nil {
if secretRef != "" && secretRef != intent.SecretRef {
err = errors.Join(err, fmt.Errorf("secret store returned unexpected reference %q", secretRef))
}
cleanupErr := cleanupCertificateCommitIntent(context.WithoutCancel(ctx), l.Repository, l.Secrets, intent)
return CommitResult{}, errors.Join(fmt.Errorf("store certificate private key: %w", err), cleanupErr)
}
if secretRef != intent.SecretRef {
return CommitResult{}, errors.Join(
errors.New("secret store returned an unexpected certificate key reference"),
cleanupCertificateCommitIntent(context.WithoutCancel(ctx), l.Repository, l.Secrets, intent),
)
}
version.PrivateKeyRef = secretRef
lineage.CurrentVersionID = version.ID
lineage.UpdatedAt = committedAt
exported, err := InstallVersion(request.ExportRoot, lineage, version, request.Artifact, committedAt)
if err != nil {
cleanupErr := cleanupCertificateCommitIntent(context.WithoutCancel(ctx), l.Repository, l.Secrets, intent)
return CommitResult{}, errors.Join(err, cleanupErr)
}
version.CertificatePath = exported.CertificatePath
version.ChainPath = exported.ChainPath
version.ExportPath = exported.VersionDirectory
version.ExportedAt = pointer(committedAt)
result := CommitResult{Lineage: lineage, Version: version, Export: exported}
if err := l.Repository.CommitCertificateVersion(ctx, lineage, version); err != nil {
// A database commit may succeed durably and still return an I/O error to
// the caller. The journal row is deleted in that same transaction, so it
// is the authoritative commit-outcome marker. Never compensate until the
// marker can be re-read and is confirmed to remain pending.
pending, inspectErr := CertificateCommitIntentPending(context.WithoutCancel(ctx), l.Repository, version.ID)
if inspectErr != nil {
return CommitResult{}, errors.Join(
fmt.Errorf("certificate commit outcome is unknown; artifacts were preserved: %w", err),
fmt.Errorf("inspect certificate commit journal: %w", inspectErr),
)
}
if pending {
return CommitResult{}, errors.Join(
fmt.Errorf("commit certificate version: %w", err),
cleanupCertificateCommitIntent(context.WithoutCancel(ctx), l.Repository, l.Secrets, intent),
)
}
result.Warnings = append(result.Warnings, "certificate commit returned an error, but the durable journal confirms it completed: "+err.Error())
}
if err := ActivateVersion(request.ExportRoot, version.ID); err != nil {
// SQLite remains authoritative and startup reconciliation can retry this
// local activation without obtaining another certificate.
result.Warnings = append(result.Warnings, "certificate metadata committed, but current symlink activation failed: "+err.Error())
return result, nil
}
result.Export.CurrentLink = filepath.Join(request.ExportRoot, "current")
return result, nil
}
// SaveImportedMetadata persists an external lineage without a private key.
func (l *Lifecycle) SaveImportedMetadata(ctx context.Context, lineageID, name, zoneID string, certificatePEM []byte) (domain.CertificateLineage, domain.CertificateVersion, error) {
if l == nil || l.Repository == nil {
return domain.CertificateLineage{}, domain.CertificateVersion{}, errors.New("certificate lifecycle repository is required")
}
now := time.Now
if l.Now != nil {
now = l.Now
}
lineage, version, err := ImportMetadata(lineageID, name, zoneID, certificatePEM, now().UTC())
if err != nil {
return domain.CertificateLineage{}, domain.CertificateVersion{}, err
}
if err := l.PersistImportedMetadata(ctx, lineage, version); err != nil {
return domain.CertificateLineage{}, domain.CertificateVersion{}, err
}
return lineage, version, nil
}
func (l *Lifecycle) PersistImportedMetadata(ctx context.Context, lineage domain.CertificateLineage, version domain.CertificateVersion) error {
if l == nil || l.Repository == nil {
return errors.New("certificate lifecycle repository is required")
}
if lineage.Source != domain.CertificateImported || lineage.CurrentVersionID != version.ID || version.LineageID != lineage.ID {
return errors.New("imported certificate lineage/version relationship is invalid")
}
return l.Repository.CommitCertificateVersion(ctx, lineage, version)
}
func wrapCleanupError(action string, err error) error {
if err == nil {
return nil
}
return fmt.Errorf("%s: %w", action, err)
}
// RecoverCertificateCommitIntents removes vault/file artifacts whose SQLite
// lineage transaction never committed. The transaction deletes its intent in
// the same commit, so every row returned here is definitively orphaned.
func RecoverCertificateCommitIntents(ctx context.Context, repository CertificateRepository, secrets SecretStore, certificatesRoot string) error {
if repository == nil || secrets == nil {
return errors.New("certificate commit recovery is not fully configured")
}
if strings.TrimSpace(certificatesRoot) == "" {
return errors.New("certificate commit recovery root is required")
}
if err := EnsurePrivateDirectoryDurable(certificatesRoot); err != nil {
return fmt.Errorf("prepare certificate commit recovery root: %w", err)
}
intents, err := repository.ListCertificateCommitIntents(ctx)
if err != nil {
return fmt.Errorf("list certificate commit intents: %w", err)
}
var recoveryErrors []error
for _, intent := range intents {
if err := validateCertificateCommitIntentRecoveryRoot(intent, certificatesRoot); err != nil {
recoveryErrors = append(recoveryErrors, fmt.Errorf("recover certificate version %s: %w", intent.VersionID, err))
continue
}
if err := cleanupCertificateCommitIntent(ctx, repository, secrets, intent); err != nil {
recoveryErrors = append(recoveryErrors, fmt.Errorf("recover certificate version %s: %w", intent.VersionID, err))
}
}
return errors.Join(recoveryErrors...)
}
func CleanupCertificateCommitIntent(ctx context.Context, repository CertificateRepository, secrets SecretStore, intent domain.CertificateCommitIntent) error {
if repository == nil || secrets == nil {
return errors.New("certificate commit cleanup is not fully configured")
}
return cleanupCertificateCommitIntent(ctx, repository, secrets, intent)
}
// CertificateCommitIntentPending checks the durable outcome marker for one
// certificate version. Absence means CommitCertificateVersion atomically
// installed the metadata and deleted the marker; presence means compensating
// cleanup is safe.
func CertificateCommitIntentPending(ctx context.Context, repository CertificateRepository, versionID string) (bool, error) {
if repository == nil {
return false, errors.New("certificate commit repository is required")
}
if versionID == "" {
return false, errors.New("certificate version ID is required")
}
intents, err := repository.ListCertificateCommitIntents(ctx)
if err != nil {
return false, err
}
for _, intent := range intents {
if intent.VersionID == versionID {
return true, nil
}
}
return false, nil
}
func cleanupCertificateCommitIntent(ctx context.Context, repository CertificateRepository, secrets SecretStore, intent domain.CertificateCommitIntent) error {
if err := validateCertificateCommitIntentPath(intent); err != nil {
return err
}
var cleanupErrors []error
if intent.SecretRef != "" {
if err := wrapCleanupError("delete orphaned certificate key", compensateSecretDelete(ctx, secrets, intent.SecretRef)); err != nil {
cleanupErrors = append(cleanupErrors, err)
}
}
artifactDirectory := filepath.Dir(intent.ArtifactPath)
paths := []string{
intent.ArtifactPath,
filepath.Join(artifactDirectory, ".tmp-"+intent.VersionID),
}
for _, path := range paths {
if err := os.RemoveAll(path); err != nil {
cleanupErrors = append(cleanupErrors, fmt.Errorf("remove orphaned certificate artifact %s: %w", filepath.Base(path), err))
}
}
if err := syncDirectory(artifactDirectory); err != nil && !errors.Is(err, os.ErrNotExist) {
cleanupErrors = append(cleanupErrors, fmt.Errorf("sync orphan cleanup: %w", err))
}
if err := errors.Join(cleanupErrors...); err != nil {
return err
}
if err := repository.DeleteCertificateCommitIntent(ctx, intent.VersionID); err != nil {
return fmt.Errorf("close certificate commit intent: %w", err)
}
return nil
}
func validateCertificateCommitIntentPath(intent domain.CertificateCommitIntent) error {
if intent.VersionID == "" || intent.ArtifactPath == "" {
return errors.New("certificate commit intent is incomplete")
}
if err := safePathComponent(intent.VersionID); err != nil {
return fmt.Errorf("certificate commit intent version ID: %w", err)
}
base := filepath.Base(filepath.Clean(intent.ArtifactPath))
if base != intent.VersionID && base != intent.VersionID+".pem" {
return errors.New("certificate commit intent artifact path does not match its version")
}
if base == intent.VersionID+".pem" {
if intent.SecretRef != "" {
return errors.New("imported certificate commit intent must not reference a vault secret")
}
return nil
}
expectedSecretRef := "certificate-key/" + intent.VersionID
if intent.SecretRef != expectedSecretRef {
return fmt.Errorf("managed certificate commit intent secret reference must equal %q", expectedSecretRef)
}
return nil
}
func validateCertificateCommitIntentRecoveryRoot(intent domain.CertificateCommitIntent, certificatesRoot string) error {
if err := validateCertificateCommitIntentPath(intent); err != nil {
return err
}
root, err := filepath.Abs(certificatesRoot)
if err != nil {
return fmt.Errorf("resolve certificate recovery root: %w", err)
}
rootInfo, err := os.Stat(root)
if err != nil {
return fmt.Errorf("inspect certificate recovery root: %w", err)
}
if !rootInfo.IsDir() {
return errors.New("certificate recovery root is not a directory")
}
artifact, err := filepath.Abs(intent.ArtifactPath)
if err != nil {
return fmt.Errorf("resolve certificate recovery artifact: %w", err)
}
if !pathContainedBy(root, artifact) {
return errors.New("certificate commit intent artifact is outside the configured certificates root")
}
resolvedRoot, err := filepath.EvalSymlinks(root)
if err != nil {
return fmt.Errorf("resolve certificate recovery root links: %w", err)
}
existing := artifact
for {
if _, err := os.Lstat(existing); err == nil {
break
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("inspect certificate recovery artifact path: %w", err)
}
parent := filepath.Dir(existing)
if parent == existing {
return errors.New("certificate recovery artifact has no existing ancestor")
}
existing = parent
}
resolvedExisting, err := filepath.EvalSymlinks(existing)
if err != nil {
return fmt.Errorf("resolve certificate recovery artifact links: %w", err)
}
if !pathContainedBy(resolvedRoot, resolvedExisting) {
return errors.New("certificate commit intent artifact resolves outside the configured certificates root")
}
return nil
}
func pathContainedBy(root, candidate string) bool {
relative, err := filepath.Rel(filepath.Clean(root), filepath.Clean(candidate))
if err != nil || relative == ".." || filepath.IsAbs(relative) {
return false
}
return !strings.HasPrefix(relative, ".."+string(filepath.Separator))
}
func fallbackRenewalWindowFromMetadata(metadata Metadata) RenewalWindow {
return fallbackRenewalWindowForValidity(metadata.NotBefore, metadata.NotAfter)
}
+220
View File
@@ -0,0 +1,220 @@
package certificates
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"slices"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/identifier"
)
// Metadata is safe to display and persist outside the encrypted vault.
type Metadata struct {
SerialNumber string `json:"serial_number"`
FingerprintSHA256 string `json:"fingerprint_sha256"`
Issuer string `json:"issuer"`
Subject string `json:"subject"`
Identifiers []string `json:"identifiers"`
NotBefore time.Time `json:"not_before"`
NotAfter time.Time `json:"not_after"`
KeyAlgorithm domain.KeyAlgorithm `json:"key_algorithm"`
}
// Artifact contains the material returned by an ACME server or read for a
// managed certificate. PrivateKeyPEM must be PKCS#8 when exported.
type Artifact struct {
CertificatePEM []byte `json:"-"`
ChainPEM []byte `json:"-"`
PrivateKeyPEM []byte `json:"-"`
Metadata Metadata `json:"metadata"`
}
// ParseCertificatePEM parses a leaf-first PEM bundle, separates the leaf from
// its chain, and rejects any non-certificate PEM block (especially keys).
func ParseCertificatePEM(data []byte) (*x509.Certificate, []byte, []byte, Metadata, error) {
var certificates []*x509.Certificate
var encoded [][]byte
rest := data
for len(bytes.TrimSpace(rest)) > 0 {
block, remaining := pem.Decode(rest)
if block == nil {
return nil, nil, nil, Metadata{}, errors.New("certificate input contains invalid PEM data")
}
if block.Type != "CERTIFICATE" {
return nil, nil, nil, Metadata{}, fmt.Errorf("certificate input contains forbidden PEM block %q", block.Type)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, nil, nil, Metadata{}, fmt.Errorf("parse certificate: %w", err)
}
certificates = append(certificates, cert)
encoded = append(encoded, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: block.Bytes}))
rest = remaining
}
if len(certificates) == 0 {
return nil, nil, nil, Metadata{}, errors.New("certificate input contains no certificates")
}
leaf := certificates[0]
if leaf.IsCA {
return nil, nil, nil, Metadata{}, errors.New("certificate bundle starts with a CA certificate")
}
leafPEM := slices.Clone(encoded[0])
chainPEM := bytes.Join(encoded[1:], nil)
metadata, err := metadataFromCertificate(leaf)
if err != nil {
return nil, nil, nil, Metadata{}, err
}
return leaf, leafPEM, chainPEM, metadata, nil
}
// ImportMetadata creates an external, read-only lineage and version. It never
// accepts or stores a private key.
func ImportMetadata(lineageID, name, zoneID string, certificatePEM []byte, now time.Time) (domain.CertificateLineage, domain.CertificateVersion, error) {
_, _, _, metadata, err := ParseCertificatePEM(certificatePEM)
if err != nil {
return domain.CertificateLineage{}, domain.CertificateVersion{}, err
}
if lineageID == "" {
lineageID = identifier.New("lineage")
}
if name == "" && len(metadata.Identifiers) > 0 {
name = metadata.Identifiers[0]
}
if name == "" {
name = metadata.Subject
}
versionID := identifier.New("certver")
lineage := domain.CertificateLineage{
ID: lineageID,
Name: name,
ZoneID: zoneID,
Source: domain.CertificateImported,
Identifiers: slices.Clone(metadata.Identifiers),
KeyAlgorithm: metadata.KeyAlgorithm,
Profile: "external",
CurrentVersionID: versionID,
CreatedAt: now.UTC(),
UpdatedAt: now.UTC(),
}
version := domain.CertificateVersion{
ID: versionID,
LineageID: lineageID,
SerialNumber: metadata.SerialNumber,
FingerprintSHA256: metadata.FingerprintSHA256,
Issuer: metadata.Issuer,
Identifiers: slices.Clone(metadata.Identifiers),
NotBefore: metadata.NotBefore,
NotAfter: metadata.NotAfter,
CreatedAt: now.UTC(),
}
return lineage, version, nil
}
// ValidateArtifact verifies the leaf/key relationship, requested SANs, and
// basic validity ordering before any material is committed or exported.
func ValidateArtifact(artifact Artifact, expectedIdentifiers []string) (*x509.Certificate, error) {
leaf, _, _, metadata, err := ParseCertificatePEM(append(slices.Clone(artifact.CertificatePEM), artifact.ChainPEM...))
if err != nil {
return nil, err
}
if len(artifact.PrivateKeyPEM) == 0 {
return nil, errors.New("managed certificate has no private key")
}
key, err := ParsePrivateKeyPEM(artifact.PrivateKeyPEM)
if err != nil {
return nil, err
}
if err := verifyKeyPair(leaf, key); err != nil {
return nil, err
}
if !leaf.NotAfter.After(leaf.NotBefore) {
return nil, errors.New("certificate validity window is empty")
}
expected := slices.Clone(expectedIdentifiers)
for index := range expected {
expected[index] = strings.ToLower(strings.TrimSuffix(expected[index], "."))
}
slices.Sort(expected)
expected = slices.Compact(expected)
if !slices.Equal(metadata.Identifiers, expected) {
return nil, fmt.Errorf("issued certificate identifiers %v do not exactly match requested identifiers %v", metadata.Identifiers, expected)
}
return leaf, nil
}
func metadataFromCertificate(cert *x509.Certificate) (Metadata, error) {
algorithm, err := publicKeyAlgorithm(cert.PublicKey)
if err != nil {
return Metadata{}, err
}
identifiers := slices.Clone(cert.DNSNames)
if len(identifiers) == 0 && cert.Subject.CommonName != "" {
identifiers = []string{cert.Subject.CommonName}
}
for i, name := range identifiers {
identifiers[i] = strings.ToLower(strings.TrimSuffix(name, "."))
}
slices.Sort(identifiers)
identifiers = slices.Compact(identifiers)
digest := sha256.Sum256(cert.Raw)
return Metadata{
SerialNumber: strings.ToUpper(cert.SerialNumber.Text(16)),
FingerprintSHA256: hex.EncodeToString(digest[:]),
Issuer: cert.Issuer.String(),
Subject: cert.Subject.String(),
Identifiers: identifiers,
NotBefore: cert.NotBefore.UTC(),
NotAfter: cert.NotAfter.UTC(),
KeyAlgorithm: algorithm,
}, nil
}
func publicKeyAlgorithm(publicKey any) (domain.KeyAlgorithm, error) {
switch key := publicKey.(type) {
case *ecdsa.PublicKey:
switch key.Curve {
case elliptic.P256():
return domain.KeyECDSAP256, nil
case elliptic.P384():
return domain.KeyAlgorithm("EC384"), nil
case elliptic.P521():
return domain.KeyAlgorithm("EC521"), nil
}
case *rsa.PublicKey:
if bits := key.N.BitLen(); bits >= 2048 {
return domain.KeyAlgorithm(fmt.Sprintf("RSA%d", bits)), nil
}
case ed25519.PublicKey:
return domain.KeyAlgorithm("ED25519"), nil
}
return "", fmt.Errorf("unsupported certificate public key type %T", publicKey)
}
func verifyKeyPair(cert *x509.Certificate, key crypto.Signer) error {
certPublic, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
if err != nil {
return fmt.Errorf("marshal certificate public key: %w", err)
}
keyPublic, err := x509.MarshalPKIXPublicKey(key.Public())
if err != nil {
return fmt.Errorf("marshal private key public component: %w", err)
}
if !bytes.Equal(certPublic, keyPublic) {
return errors.New("certificate and private key do not match")
}
return nil
}
+189
View File
@@ -0,0 +1,189 @@
// Package certificates implements certificate planning, ACME issuance, metadata
// inspection, and safe local export.
package certificates
import (
"errors"
"fmt"
"net"
"slices"
"strings"
"github.com/MeghdadFadaee/domainops/internal/domain"
"golang.org/x/net/idna"
)
const (
DefaultProfile = "classic"
MaxIdentifiers = 100
EnvironmentStaging = "staging"
EnvironmentProduction = "production"
)
// Plan is one independent ACME certificate order. Bulk operations should use
// one Plan per zone so a failure or rate limit never invalidates other zones.
type Plan struct {
Name string `json:"name"`
ZoneID string `json:"zone_id,omitempty"`
ZoneName string `json:"zone_name"`
Identifiers []string `json:"identifiers"`
KeyAlgorithm domain.KeyAlgorithm `json:"key_algorithm"`
Profile string `json:"profile"`
}
// NewWildcardPlan returns an apex-plus-wildcard plan. Each nested name adds
// its own exact identifier and one-label wildcard. For example, "api" adds
// api.example.com and *.api.example.com; *.example.com does not cover either
// foo.api.example.com or the apex.
func NewWildcardPlan(zoneID, zoneName string, nestedNames ...string) (Plan, error) {
zoneName, err := canonicalDNSName(zoneName, false)
if err != nil {
return Plan{}, fmt.Errorf("zone name: %w", err)
}
identifiers := []string{zoneName, "*." + zoneName}
for _, nested := range nestedNames {
nested = strings.TrimSpace(nested)
if nested == "" {
continue
}
if !strings.Contains(nested, ".") {
nested += "." + zoneName
}
name, canonErr := canonicalDNSName(nested, false)
if canonErr != nil {
return Plan{}, fmt.Errorf("nested name %q: %w", nested, canonErr)
}
if name == zoneName || !strings.HasSuffix(name, "."+zoneName) {
return Plan{}, fmt.Errorf("nested name %q is outside zone %q", name, zoneName)
}
identifiers = append(identifiers, name, "*."+name)
}
plan := Plan{
Name: zoneName,
ZoneID: zoneID,
ZoneName: zoneName,
Identifiers: deduplicate(identifiers),
KeyAlgorithm: domain.KeyECDSAP256,
Profile: DefaultProfile,
}
return plan, ValidatePlan(plan)
}
// ValidatePlan normalizes no input and returns an error for unsafe or invalid
// order shapes. Callers retain full control of identifier ordering (the first
// identifier becomes the certificate common name when enabled by the CA).
func ValidatePlan(plan Plan) error {
if len(plan.Identifiers) == 0 {
return errors.New("certificate plan has no identifiers")
}
if len(plan.Identifiers) > MaxIdentifiers {
return fmt.Errorf("certificate plan has %d identifiers; maximum is %d", len(plan.Identifiers), MaxIdentifiers)
}
if plan.KeyAlgorithm != domain.KeyECDSAP256 && plan.KeyAlgorithm != domain.KeyRSA2048 {
return fmt.Errorf("unsupported key algorithm %q", plan.KeyAlgorithm)
}
if strings.TrimSpace(plan.Profile) == "" {
return errors.New("certificate profile is required")
}
zone, err := canonicalDNSName(plan.ZoneName, false)
if err != nil {
return fmt.Errorf("zone name: %w", err)
}
if zone != plan.ZoneName {
return fmt.Errorf("zone name %q is not canonical; use %q", plan.ZoneName, zone)
}
seen := make(map[string]struct{}, len(plan.Identifiers))
for _, identifier := range plan.Identifiers {
canon, canonErr := canonicalDNSName(identifier, true)
if canonErr != nil {
return fmt.Errorf("identifier %q: %w", identifier, canonErr)
}
if canon != identifier {
return fmt.Errorf("identifier %q is not canonical; use %q", identifier, canon)
}
base := strings.TrimPrefix(canon, "*.")
if base != zone && !strings.HasSuffix(base, "."+zone) {
return fmt.Errorf("identifier %q is outside zone %q", identifier, zone)
}
if _, ok := seen[canon]; ok {
return fmt.Errorf("duplicate identifier %q", canon)
}
seen[canon] = struct{}{}
}
return nil
}
func canonicalDNSName(name string, allowWildcard bool) (string, error) {
name = strings.TrimSuffix(strings.TrimSpace(name), ".")
if name == "" {
return "", errors.New("DNS name is empty")
}
if strings.ContainsAny(name, "/:@ \\") {
return "", errors.New("DNS name must not contain a scheme, port, path, or whitespace")
}
wildcard := strings.HasPrefix(name, "*.")
if strings.Contains(name, "*") && !wildcard {
return "", errors.New("wildcard must be the complete left-most label")
}
if wildcard {
if !allowWildcard {
return "", errors.New("wildcards are not allowed here")
}
name = strings.TrimPrefix(name, "*.")
if strings.Contains(name, "*") {
return "", errors.New("only one wildcard label is allowed")
}
}
ascii, err := idna.Lookup.ToASCII(name)
if err != nil {
return "", fmt.Errorf("invalid internationalized DNS name: %w", err)
}
ascii = strings.ToLower(ascii)
if len(ascii) > 253 {
return "", errors.New("DNS name exceeds 253 bytes")
}
if ip := net.ParseIP(ascii); ip != nil {
return "", errors.New("IP addresses are not supported by DNS-01 plans")
}
labels := strings.Split(ascii, ".")
if len(labels) < 2 {
return "", errors.New("DNS name must contain at least two labels")
}
for _, label := range labels {
if len(label) == 0 || len(label) > 63 {
return "", errors.New("DNS label is empty or exceeds 63 bytes")
}
if label[0] == '-' || label[len(label)-1] == '-' {
return "", errors.New("DNS labels must not begin or end with a hyphen")
}
for _, r := range label {
if (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '-' {
return "", fmt.Errorf("DNS label %q contains an invalid character", label)
}
}
}
if wildcard {
return "*." + ascii, nil
}
return ascii, nil
}
func deduplicate(values []string) []string {
out := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
if _, ok := seen[value]; ok {
continue
}
seen[value] = struct{}{}
out = append(out, value)
}
return slices.Clip(out)
}
+1022
View File
File diff suppressed because it is too large. Load diff
+379
View File
@@ -0,0 +1,379 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/app"
"github.com/MeghdadFadaee/domainops/internal/bootstrap"
"github.com/MeghdadFadaee/domainops/internal/certificates"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
func TestVersionJSONEnvelope(t *testing.T) {
var stdout, stderr bytes.Buffer
if err := Execute(context.Background(), &stdout, &stderr, []string{"--json", "version"}); err != nil {
t.Fatal(err)
}
var envelope Envelope
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode output %q: %v", stdout.String(), err)
}
if !envelope.OK || envelope.SchemaVersion != 1 || envelope.Command != "domainops version" {
t.Fatalf("envelope = %#v", envelope)
}
}
func TestRootJSONRequiresSubcommand(t *testing.T) {
var stdout, stderr bytes.Buffer
err := Execute(context.Background(), &stdout, &stderr, []string{"--json"})
if err == nil || !IsReportedError(err) {
t.Fatalf("root JSON error = %v", err)
}
var envelope Envelope
if decodeErr := json.Unmarshal(stdout.Bytes(), &envelope); decodeErr != nil {
t.Fatalf("decode output %q: %v", stdout.String(), decodeErr)
}
if envelope.OK || envelope.Command != "domainops" || len(envelope.Errors) != 1 || !strings.Contains(envelope.Errors[0], "subcommand") {
t.Fatalf("root JSON envelope = %#v", envelope)
}
}
func TestLeafCommandsRejectStrayArgumentsAndConflictingBulkFlags(t *testing.T) {
for _, args := range [][]string{
{"--json", "status", "stray"},
{"--json", "cert", "issue", "--all", "--zone", "example.com"},
} {
var stdout, stderr bytes.Buffer
if err := Execute(context.Background(), &stdout, &stderr, args); err == nil {
t.Fatalf("unsafe arguments were accepted: %#v", args)
}
envelope := decodeSingleEnvelope(t, stdout.Bytes())
if envelope.OK || len(envelope.Errors) == 0 {
t.Fatalf("argument error envelope for %#v = %#v", args, envelope)
}
}
}
func TestResolveZonesRejectsDuplicateNamesAcrossAccounts(t *testing.T) {
ctx := context.Background()
runtime, err := bootstrap.Open(ctx, bootstrap.Options{DataDir: filepath.Join(t.TempDir(), "state"), NoKeyring: true})
if err != nil {
t.Fatal(err)
}
defer runtime.Close()
now := time.Now().UTC()
accounts := []domain.RemoteAccount{
{ID: "account-a", Provider: domain.ProviderCloudflare, ProviderID: "a", Name: "A", CreatedAt: now},
{ID: "account-b", Provider: domain.ProviderCloudflare, ProviderID: "b", Name: "B", CreatedAt: now},
}
if err := runtime.Repository.SaveAccounts(ctx, accounts, nil); err != nil {
t.Fatal(err)
}
zones := []domain.Zone{
{ID: "zone-a", Provider: domain.ProviderCloudflare, ProviderID: "a", AccountID: accounts[0].ID, Name: "example.com", Status: domain.ZoneActive},
{ID: "zone-b", Provider: domain.ProviderCloudflare, ProviderID: "b", AccountID: accounts[1].ID, Name: "example.com", Status: domain.ZoneActive},
}
if err := runtime.Repository.SaveZones(ctx, zones); err != nil {
t.Fatal(err)
}
if _, err := resolveZones(ctx, runtime, []string{"example.com"}, false); err == nil || !strings.Contains(err.Error(), "ambiguous") {
t.Fatalf("duplicate zone name resolution = %v", err)
}
ids, err := resolveZones(ctx, runtime, []string{"zone-b"}, false)
if err != nil || len(ids) != 1 || ids[0] != "zone-b" {
t.Fatalf("explicit zone ID resolution = %#v, %v", ids, err)
}
}
func TestZonePreferHelpUsesCredentialIDMetavariable(t *testing.T) {
var stdout, stderr bytes.Buffer
if err := Execute(context.Background(), &stdout, &stderr, []string{"zone", "prefer", "--help"}); err != nil {
t.Fatal(err)
}
if stderr.Len() != 0 {
t.Fatalf("stderr = %q, want empty", stderr.String())
}
help := stdout.String()
if !strings.Contains(help, "--credential CREDENTIAL_ID") {
t.Fatalf("credential flag help has the wrong metavariable: %q", help)
}
if strings.Contains(help, "--credential domainops account list") {
t.Fatalf("credential flag help contains a multi-word metavariable: %q", help)
}
}
func TestStatusInitializesLocalMetadataWithoutVaultUnlock(t *testing.T) {
var stdout, stderr bytes.Buffer
dataDir := filepath.Join(t.TempDir(), "state")
if err := Execute(context.Background(), &stdout, &stderr, []string{"--data-dir", dataDir, "--json", "status"}); err != nil {
t.Fatal(err)
}
if !strings.Contains(stdout.String(), `"zones":0`) || !strings.Contains(stdout.String(), `"schema_version":1`) {
t.Fatalf("status output = %s", stdout.String())
}
if _, err := os.Stat(filepath.Join(dataDir, "domainops.db")); err != nil {
t.Fatal(err)
}
}
func TestReadSecretRequiresPrivatePermissions(t *testing.T) {
path := filepath.Join(t.TempDir(), "password")
if err := os.WriteFile(path, []byte("secret\n"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := readSecret("test", path, false, &bytes.Buffer{}); err == nil {
t.Fatal("world-readable secret file unexpectedly accepted")
}
if err := os.Chmod(path, 0o600); err != nil {
t.Fatal(err)
}
value, err := readSecret("test", path, false, &bytes.Buffer{})
if err != nil {
t.Fatal(err)
}
if string(value) != "secret" {
t.Fatalf("value = %q", value)
}
}
func TestReadDNSBatchFileSupportsVersionedDocumentAndArray(t *testing.T) {
t.Parallel()
for name, body := range map[string]string{
"document": `{"schema_version":1,"mutations":[{"kind":"create","after":{"type":"A","name":"www","content":"192.0.2.1","ttl":300}}]}`,
"array": `[{"kind":"delete","record_id":"cfrecord_1"}]`,
} {
name, body := name, body
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "batch.json")
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
mutations, err := readDNSBatchFile(path)
if err != nil {
t.Fatal(err)
}
if len(mutations) != 1 || mutations[0].Kind == "" {
t.Fatalf("mutations = %#v", mutations)
}
})
}
}
func TestReadDNSBatchFileRejectsUnknownFields(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "batch.json")
if err := os.WriteFile(path, []byte(`[{"kind":"create","after":{"type":"A","name":"www","contnet":"192.0.2.1","ttl":300}}]`), 0o600); err != nil {
t.Fatal(err)
}
if _, err := readDNSBatchFile(path); err == nil || !strings.Contains(err.Error(), "unknown field") {
t.Fatalf("unknown DNS field error = %v", err)
}
}
func TestRenewDueFlagIsRequiredAndJSONErrorIsReportedOnce(t *testing.T) {
var stdout, stderr bytes.Buffer
err := Execute(context.Background(), &stdout, &stderr, []string{"--json", "cert", "renew"})
if err == nil {
t.Fatal("renew without --due unexpectedly succeeded")
}
if !IsReportedError(err) {
t.Fatalf("error was not marked as JSON-reported: %v", err)
}
if stderr.Len() != 0 {
t.Fatalf("stderr = %q, want empty", stderr.String())
}
envelope := decodeSingleEnvelope(t, stdout.Bytes())
if envelope.OK || envelope.Command != "domainops cert renew" || len(envelope.Errors) != 1 || !strings.Contains(envelope.Errors[0], "due") {
t.Fatalf("envelope = %#v", envelope)
}
command, _, findErr := NewRoot(io.Discard, io.Discard).Find([]string{"cert", "renew"})
if findErr != nil {
t.Fatal(findErr)
}
if command.Flags().Lookup("due") == nil {
t.Fatal("renew command does not register --due")
}
}
func TestOperationErrorsUseSingleFailedJSONEnvelopeAndAccurateExitCode(t *testing.T) {
t.Run("sync", func(t *testing.T) {
dataDir, passwordFile := seedUnlockedRuntime(t, func(runtime *bootstrap.Runtime) {
now := time.Now().UTC()
err := runtime.Repository.SaveCredential(context.Background(), domain.Credential{
ID: "cred_missing_secret", Provider: domain.ProviderCloudflare, Label: "Broken token",
Kind: domain.CredentialUserToken, SecretRef: "secret-does-not-exist",
Status: domain.CredentialUnknown, CreatedAt: now,
})
if err != nil {
t.Fatal(err)
}
})
assertPartialJSONExit3(t, []string{
"--data-dir", dataDir, "--no-keyring", "--vault-password-file", passwordFile,
"--json", "sync", "--skip-health",
}, "domainops sync")
})
t.Run("issue", func(t *testing.T) {
dataDir, passwordFile := seedUnlockedRuntime(t, func(runtime *bootstrap.Runtime) {
now := time.Now().UTC()
account := domain.RemoteAccount{ID: "cfacct_test", Provider: domain.ProviderCloudflare, ProviderID: "test", Name: "Test", CreatedAt: now}
if err := runtime.Repository.SaveAccounts(context.Background(), []domain.RemoteAccount{account}, nil); err != nil {
t.Fatal(err)
}
if err := runtime.Repository.SaveZones(context.Background(), []domain.Zone{{
ID: "cfzone_test", Provider: domain.ProviderCloudflare, ProviderID: "test", AccountID: account.ID,
PreferredCredentialID: "cred_test", Name: "example.com", Status: domain.ZoneActive,
}}); err != nil {
t.Fatal(err)
}
})
assertJSONExitCode(t, []string{
"--data-dir", dataDir, "--no-keyring", "--vault-password-file", passwordFile,
"--json", "cert", "issue", "--zone", "example.com",
}, "domainops cert issue", 1)
})
t.Run("renew", func(t *testing.T) {
dataDir, passwordFile := seedUnlockedRuntime(t, nil)
assertJSONExitCode(t, []string{
"--data-dir", dataDir, "--no-keyring", "--vault-password-file", passwordFile,
"--json", "cert", "renew", "--due", "--confirm-production",
}, "domainops cert renew", 1)
})
}
func TestCertificateOperationExitCodeDistinguishesGlobalAndPerItemFailure(t *testing.T) {
if code := certificateOperationExitCode(app.IssueZonesResult{}); code != 1 {
t.Fatalf("global certificate failure exit code = %d", code)
}
if code := certificateOperationExitCode(app.IssueZonesResult{Failed: []app.IssueFailure{{ZoneID: "zone", Error: "failed"}}}); code != 3 {
t.Fatalf("per-item certificate failure exit code = %d", code)
}
}
func TestCertificateActivationWarningsAreTopLevelPartialJSON(t *testing.T) {
result := app.IssueZonesResult{Completed: []certificates.CommitResult{{
Lineage: domain.CertificateLineage{ID: "lineage", Name: "example.com"},
Warnings: []string{"current symlink activation failed"},
}}}
warnings := certificateResultWarnings(result)
if len(warnings) != 1 || !strings.Contains(warnings[0], "example.com") {
t.Fatalf("certificate warnings = %#v", warnings)
}
var stdout bytes.Buffer
opts := &options{json: true, stdout: &stdout, stderr: io.Discard}
if err := writeOperationOutput(opts, "domainops cert issue", result, "partial", nil, warnings...); err != nil {
t.Fatal(err)
}
envelope := decodeSingleEnvelope(t, stdout.Bytes())
if envelope.OK || len(envelope.Warnings) != 1 || len(envelope.Errors) != 0 || !opts.jsonReported {
t.Fatalf("activation warning envelope = %#v reported=%v", envelope, opts.jsonReported)
}
}
func TestPlainCertificateListIncludesLineageID(t *testing.T) {
dataDir := filepath.Join(t.TempDir(), "state")
runtime, err := bootstrap.Open(context.Background(), bootstrap.Options{DataDir: dataDir, NoKeyring: true})
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
lineage := domain.CertificateLineage{
ID: "lineage_example", Name: "example.com", Source: domain.CertificateImported,
Identifiers: []string{"example.com", "*.example.com"}, KeyAlgorithm: domain.KeyECDSAP256,
Profile: "classic", CreatedAt: now, UpdatedAt: now,
}
if err := runtime.Repository.SaveCertificateLineage(context.Background(), lineage); err != nil {
_ = runtime.Close()
t.Fatal(err)
}
if err := runtime.Close(); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
if err := Execute(context.Background(), &stdout, &stderr, []string{"--data-dir", dataDir, "--no-keyring", "cert", "list"}); err != nil {
t.Fatal(err)
}
if !strings.Contains(stdout.String(), lineage.ID) {
t.Fatalf("certificate list omitted lineage ID: %q", stdout.String())
}
}
func seedUnlockedRuntime(t *testing.T, seed func(*bootstrap.Runtime)) (string, string) {
t.Helper()
root := t.TempDir()
dataDir := filepath.Join(root, "state")
runtime, err := bootstrap.Open(context.Background(), bootstrap.Options{DataDir: dataDir, NoKeyring: true})
if err != nil {
t.Fatal(err)
}
password := []byte("correct horse battery staple")
if err := runtime.Application.UnlockVault(context.Background(), password); err != nil {
_ = runtime.Close()
t.Fatal(err)
}
if seed != nil {
seed(runtime)
}
if err := runtime.Close(); err != nil {
t.Fatal(err)
}
passwordFile := filepath.Join(root, "vault-password")
if err := os.WriteFile(passwordFile, password, 0o600); err != nil {
t.Fatal(err)
}
return dataDir, passwordFile
}
func assertPartialJSONExit3(t *testing.T, args []string, command string) {
assertJSONExitCode(t, args, command, 3)
}
func assertJSONExitCode(t *testing.T, args []string, command string, code int) {
t.Helper()
var stdout, stderr bytes.Buffer
err := Execute(context.Background(), &stdout, &stderr, args)
if err == nil {
t.Fatal("partial operation unexpectedly succeeded")
}
var exitErr *ExitError
if !errors.As(err, &exitErr) || exitErr.Code != code {
t.Fatalf("error = %v, want exit code %d", err, code)
}
if !IsReportedError(err) {
t.Fatalf("error was not marked as JSON-reported: %v", err)
}
if stderr.Len() != 0 {
t.Fatalf("stderr = %q, want empty", stderr.String())
}
envelope := decodeSingleEnvelope(t, stdout.Bytes())
if envelope.OK || envelope.Command != command || envelope.Data == nil || len(envelope.Errors) == 0 {
t.Fatalf("envelope = %#v", envelope)
}
}
func decodeSingleEnvelope(t *testing.T, data []byte) Envelope {
t.Helper()
decoder := json.NewDecoder(bytes.NewReader(data))
var envelope Envelope
if err := decoder.Decode(&envelope); err != nil {
t.Fatalf("decode output %q: %v", data, err)
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
t.Fatalf("output contained more than one JSON value: %q (next decode: %v)", data, err)
}
return envelope
}
+96
View File
@@ -0,0 +1,96 @@
package config
import (
"errors"
"os"
"path/filepath"
"runtime"
)
type Paths struct {
DataDir string
ConfigDir string
CacheDir string
Database string
Vault string
Certificates string
Exports string
Logs string
}
func Resolve(dataOverride string) (Paths, error) {
dataDir := dataOverride
if dataDir == "" {
dataDir = os.Getenv("DOMAINOPS_DATA_DIR")
}
explicitDataDir := dataDir != ""
var err error
if dataDir == "" {
switch runtime.GOOS {
case "darwin":
home, homeErr := os.UserHomeDir()
if homeErr != nil {
return Paths{}, homeErr
}
dataDir = filepath.Join(home, "Library", "Application Support", "DomainOps")
default:
base := os.Getenv("XDG_DATA_HOME")
if base == "" {
home, homeErr := os.UserHomeDir()
if homeErr != nil {
return Paths{}, homeErr
}
base = filepath.Join(home, ".local", "share")
}
dataDir = filepath.Join(base, "domainops")
}
}
dataDir, err = filepath.Abs(dataDir)
if err != nil {
return Paths{}, err
}
if dataDir == string(filepath.Separator) {
return Paths{}, errors.New("refusing to use filesystem root as the data directory")
}
// An explicit data directory must be fully self-contained so headless
// services and containers do not require HOME or writes outside that root.
configBase := filepath.Join(dataDir, "config")
cacheBase := filepath.Join(dataDir, "cache")
if !explicitDataDir {
configBase, err = os.UserConfigDir()
if err != nil {
configBase = filepath.Join(dataDir, "config")
}
cacheBase, err = os.UserCacheDir()
if err != nil {
cacheBase = filepath.Join(dataDir, "cache")
}
}
return Paths{
DataDir: dataDir,
ConfigDir: filepath.Join(configBase, "domainops"),
CacheDir: filepath.Join(cacheBase, "domainops"),
Database: filepath.Join(dataDir, "domainops.db"),
Vault: filepath.Join(dataDir, "vault.json"),
Certificates: filepath.Join(dataDir, "certificates"),
Exports: filepath.Join(dataDir, "exports"),
Logs: filepath.Join(dataDir, "logs"),
}, nil
}
func (p Paths) Ensure() error {
// ConfigDir and CacheDir are reserved for future use. Create only the
// directories required by the current runtime, avoiding unrelated writes.
for _, dir := range []string{p.DataDir, p.Certificates, p.Exports, p.Logs} {
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
if err := os.Chmod(dir, 0o700); err != nil {
return err
}
}
return nil
}
+52
View File
@@ -0,0 +1,52 @@
package config
import (
"os"
"path/filepath"
"runtime"
"testing"
)
func TestResolveOverrideAndEnsure(t *testing.T) {
t.Setenv("HOME", "")
root := filepath.Join(t.TempDir(), "state")
p, err := Resolve(root)
if err != nil {
t.Fatal(err)
}
if p.Database != filepath.Join(root, "domainops.db") {
t.Fatalf("unexpected database path: %s", p.Database)
}
if p.ConfigDir != filepath.Join(root, "config", "domainops") || p.CacheDir != filepath.Join(root, "cache", "domainops") {
t.Fatalf("explicit data directory was not self-contained: config=%q cache=%q", p.ConfigDir, p.CacheDir)
}
if err := p.Ensure(); err != nil {
t.Fatal(err)
}
info, err := os.Stat(root)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0o700 {
t.Fatalf("data directory permissions = %o", info.Mode().Perm())
}
if _, err := os.Stat(p.ConfigDir); !os.IsNotExist(err) {
t.Fatalf("unused config directory was created: %v", err)
}
}
func TestResolveXDGDataWithoutHome(t *testing.T) {
if runtime.GOOS == "darwin" {
t.Skip("macOS uses its native Application Support default")
}
root := t.TempDir()
t.Setenv("HOME", "")
t.Setenv("XDG_DATA_HOME", root)
p, err := Resolve("")
if err != nil {
t.Fatal(err)
}
if p.DataDir != filepath.Join(root, "domainops") {
t.Fatalf("XDG data directory = %q", p.DataDir)
}
}
+328
View File
@@ -0,0 +1,328 @@
package domain
import (
"encoding/json"
"time"
)
const ProviderCloudflare = "cloudflare"
type CredentialKind string
const (
CredentialUserToken CredentialKind = "user_token"
CredentialAccountToken CredentialKind = "account_token"
)
type CredentialStatus string
const (
CredentialUnknown CredentialStatus = "unknown"
CredentialValid CredentialStatus = "valid"
CredentialInvalid CredentialStatus = "invalid"
)
type Credential struct {
ID string `json:"id"`
Provider string `json:"provider"`
Label string `json:"label"`
Kind CredentialKind `json:"kind"`
AccountHint string `json:"account_hint,omitempty"`
SecretRef string `json:"-"`
Status CredentialStatus `json:"status"`
Capabilities []string `json:"capabilities,omitempty"`
CreatedAt time.Time `json:"created_at"`
LastVerifiedAt *time.Time `json:"last_verified_at,omitempty"`
LastError string `json:"last_error,omitempty"`
}
type RemoteAccount struct {
ID string `json:"id"`
Provider string `json:"provider"`
ProviderID string `json:"provider_id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
LastSyncedAt *time.Time `json:"last_synced_at,omitempty"`
}
type AccountCredential struct {
AccountID string `json:"account_id"`
CredentialID string `json:"credential_id"`
Preferred bool `json:"preferred"`
}
type ZoneStatus string
const (
ZoneActive ZoneStatus = "active"
ZonePending ZoneStatus = "pending"
ZoneInitializing ZoneStatus = "initializing"
ZoneMoved ZoneStatus = "moved"
ZoneDeactivated ZoneStatus = "deactivated"
ZoneUnknown ZoneStatus = "unknown"
)
type Zone struct {
ID string `json:"id"`
Provider string `json:"provider"`
ProviderID string `json:"provider_id"`
AccountID string `json:"account_id"`
PreferredCredentialID string `json:"preferred_credential_id"`
Name string `json:"name"`
UnicodeName string `json:"unicode_name,omitempty"`
Status ZoneStatus `json:"status"`
Paused bool `json:"paused"`
Plan string `json:"plan,omitempty"`
NameServers []string `json:"name_servers,omitempty"`
ModifiedAt *time.Time `json:"modified_at,omitempty"`
LastSyncedAt *time.Time `json:"last_synced_at,omitempty"`
}
type RecordType string
const (
RecordA RecordType = "A"
RecordAAAA RecordType = "AAAA"
RecordCNAME RecordType = "CNAME"
RecordTXT RecordType = "TXT"
RecordMX RecordType = "MX"
RecordCAA RecordType = "CAA"
RecordNS RecordType = "NS"
RecordSRV RecordType = "SRV"
)
func (t RecordType) Editable() bool {
switch t {
case RecordA, RecordAAAA, RecordCNAME, RecordTXT, RecordMX, RecordCAA, RecordNS, RecordSRV:
return true
default:
return false
}
}
type DNSRecord struct {
ID string `json:"id"`
ProviderID string `json:"provider_id"`
ZoneID string `json:"zone_id"`
Type RecordType `json:"type"`
Name string `json:"name"`
UnicodeName string `json:"unicode_name,omitempty"`
Content string `json:"content,omitempty"`
Priority *uint16 `json:"priority,omitempty"`
TTL int `json:"ttl"`
Proxied bool `json:"proxied"`
Proxiable bool `json:"proxiable"`
Comment string `json:"comment,omitempty"`
Tags []string `json:"tags,omitempty"`
Managed bool `json:"managed"`
Data json.RawMessage `json:"data,omitempty"`
Raw json.RawMessage `json:"raw,omitempty"`
ModifiedAt *time.Time `json:"modified_at,omitempty"`
LastSyncedAt *time.Time `json:"last_synced_at,omitempty"`
}
type DNSMutationKind string
const (
MutationCreate DNSMutationKind = "create"
MutationPatch DNSMutationKind = "patch"
MutationReplace DNSMutationKind = "replace"
MutationDelete DNSMutationKind = "delete"
)
type DNSMutation struct {
Kind DNSMutationKind `json:"kind"`
RecordID string `json:"record_id,omitempty"`
Before *DNSRecord `json:"before,omitempty"`
After *DNSRecord `json:"after,omitempty"`
}
type EdgeTLSSettings struct {
ZoneID string `json:"zone_id"`
Mode string `json:"mode"`
AlwaysUseHTTPS bool `json:"always_use_https"`
MinimumTLS string `json:"minimum_tls"`
TLS13 bool `json:"tls_1_3"`
HasProxiedDNS bool `json:"has_proxied_dns"`
LastSyncedAt *time.Time `json:"last_synced_at,omitempty"`
}
type EdgeCertificate struct {
ID string `json:"id"`
ZoneID string `json:"zone_id"`
Type string `json:"type"`
Status string `json:"status"`
Hosts []string `json:"hosts"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
type CertificateSource string
const (
CertificateManaged CertificateSource = "managed"
CertificateImported CertificateSource = "imported_metadata"
)
type KeyAlgorithm string
const (
KeyECDSAP256 KeyAlgorithm = "EC256"
KeyRSA2048 KeyAlgorithm = "RSA2048"
)
type CertificateLineage struct {
ID string `json:"id"`
Name string `json:"name"`
ZoneID string `json:"zone_id,omitempty"`
Source CertificateSource `json:"source"`
Identifiers []string `json:"identifiers"`
KeyAlgorithm KeyAlgorithm `json:"key_algorithm"`
Profile string `json:"profile"`
ACMEAccountID string `json:"acme_account_id,omitempty"`
CurrentVersionID string `json:"current_version_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type CertificateVersion struct {
ID string `json:"id"`
LineageID string `json:"lineage_id"`
SerialNumber string `json:"serial_number"`
FingerprintSHA256 string `json:"fingerprint_sha256"`
Issuer string `json:"issuer"`
Identifiers []string `json:"identifiers"`
NotBefore time.Time `json:"not_before"`
NotAfter time.Time `json:"not_after"`
CertificatePath string `json:"certificate_path"`
ChainPath string `json:"chain_path,omitempty"`
PrivateKeyRef string `json:"-"`
RenewalWindowStart *time.Time `json:"renewal_window_start,omitempty"`
RenewalWindowEnd *time.Time `json:"renewal_window_end,omitempty"`
RevocationPendingAt *time.Time `json:"revocation_pending_at,omitempty"`
RevokedAt *time.Time `json:"revoked_at,omitempty"`
RevocationReason *uint `json:"revocation_reason,omitempty"`
ExportedAt *time.Time `json:"exported_at,omitempty"`
ExportPath string `json:"export_path,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
type CertificateCommitIntent struct {
VersionID string `json:"version_id"`
LineageID string `json:"lineage_id"`
SecretRef string `json:"-"`
ArtifactPath string `json:"artifact_path"`
CreatedAt time.Time `json:"created_at"`
}
type ACMEAccount struct {
ID string `json:"id"`
Environment string `json:"environment"`
DirectoryURL string `json:"directory_url"`
Email string `json:"email"`
Registration string `json:"registration"`
SecretRef string `json:"-"`
CreatedAt time.Time `json:"created_at"`
}
type ACMEAccountCommitIntent struct {
AccountID string `json:"account_id"`
SecretRef string `json:"-"`
CreatedAt time.Time `json:"created_at"`
}
type ObservedEndpoint struct {
ID string `json:"id"`
ZoneID string `json:"zone_id"`
Host string `json:"host"`
Port int `json:"port"`
Enabled bool `json:"enabled"`
LastCheckedAt *time.Time `json:"last_checked_at,omitempty"`
ResolvedAddresses []string `json:"resolved_addresses,omitempty"`
FingerprintSHA256 string `json:"fingerprint_sha256,omitempty"`
Issuer string `json:"issuer,omitempty"`
NotAfter *time.Time `json:"not_after,omitempty"`
ValidForHost bool `json:"valid_for_host"`
Trusted bool `json:"trusted"`
LastError string `json:"last_error,omitempty"`
}
type Severity string
const (
SeverityInfo Severity = "info"
SeverityWarning Severity = "warning"
SeverityCritical Severity = "critical"
)
type HealthIssue struct {
ID string `json:"id"`
Severity Severity `json:"severity"`
Kind string `json:"kind"`
ResourceID string `json:"resource_id"`
Title string `json:"title"`
Detail string `json:"detail"`
Action string `json:"action,omitempty"`
ObservedAt time.Time `json:"observed_at"`
}
type JobState string
const (
JobQueued JobState = "queued"
JobRunning JobState = "running"
JobWaitingForDNS JobState = "waiting_for_dns"
JobSucceeded JobState = "succeeded"
JobFailed JobState = "failed"
JobCancelled JobState = "cancelled"
)
type Job struct {
ID string `json:"id"`
Kind string `json:"kind"`
State JobState `json:"state"`
ResourceID string `json:"resource_id,omitempty"`
Progress int `json:"progress"`
Message string `json:"message,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
Error string `json:"error,omitempty"`
RetryAt *time.Time `json:"retry_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
StartedAt *time.Time `json:"started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
type ChallengeJournal struct {
ID string `json:"id"`
JobID string `json:"job_id"`
CredentialID string `json:"credential_id,omitempty"`
ZoneID string `json:"zone_id"`
RecordID string `json:"record_id,omitempty"`
FQDN string `json:"fqdn"`
ValueHash string `json:"value_hash"`
CreatedAt time.Time `json:"created_at"`
CleanedAt *time.Time `json:"cleaned_at,omitempty"`
}
type AuditEvent struct {
ID string `json:"id"`
Actor string `json:"actor"`
Action string `json:"action"`
ResourceID string `json:"resource_id,omitempty"`
Before json.RawMessage `json:"before,omitempty"`
After json.RawMessage `json:"after,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
type DashboardSnapshot struct {
GeneratedAt time.Time `json:"generated_at"`
Credentials int `json:"credentials"`
Accounts int `json:"accounts"`
Zones int `json:"zones"`
DNSRecords int `json:"dns_records"`
Certificates int `json:"certificates"`
CertificatesDue int `json:"certificates_due"`
CertificatesExpired int `json:"certificates_expired"`
ActiveJobs int `json:"active_jobs"`
Issues []HealthIssue `json:"issues"`
}
+197
View File
@@ -0,0 +1,197 @@
package health
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
type EndpointRepository interface {
ListEndpoints(context.Context) ([]domain.ObservedEndpoint, error)
SaveEndpoint(context.Context, domain.ObservedEndpoint) error
SaveHealthIssues(context.Context, string, []domain.HealthIssue) error
}
type EndpointProber interface {
Probe(context.Context, domain.ObservedEndpoint) (domain.ObservedEndpoint, error)
}
// ExpectedFingerprint returns the locally managed fingerprint expected on an
// endpoint. An empty string means no comparison is configured.
type ExpectedFingerprint func(context.Context, domain.ObservedEndpoint) (string, error)
type Checker struct {
Repository EndpointRepository
Prober EndpointProber
ExpectedFingerprint ExpectedFingerprint
Concurrency int
Interval time.Duration
Now func() time.Time
OnError func(error)
}
// RunOnce checks enabled endpoints with bounded concurrency. Individual probe
// failures become persisted endpoint issues and do not cancel other checks.
func (c *Checker) RunOnce(ctx context.Context) error {
if c == nil || c.Repository == nil {
return errors.New("health checker repository is required")
}
if c.Prober == nil {
return errors.New("health checker prober is required")
}
endpoints, err := c.Repository.ListEndpoints(ctx)
if err != nil {
return fmt.Errorf("list observed endpoints: %w", err)
}
concurrency := c.Concurrency
if concurrency <= 0 {
concurrency = 4
}
now := time.Now
if c.Now != nil {
now = c.Now
}
jobs := make(chan domain.ObservedEndpoint)
errs := make(chan error, len(endpoints)*3)
var workers sync.WaitGroup
for range concurrency {
workers.Add(1)
go func() {
defer workers.Done()
for endpoint := range jobs {
if ctx.Err() != nil {
return
}
observed, probeErr := c.Prober.Probe(ctx, endpoint)
if saveErr := c.Repository.SaveEndpoint(ctx, observed); saveErr != nil {
errs <- fmt.Errorf("save endpoint %s: %w", endpoint.ID, saveErr)
}
expected := ""
if c.ExpectedFingerprint != nil {
value, fingerprintErr := c.ExpectedFingerprint(ctx, observed)
if fingerprintErr != nil {
errs <- fmt.Errorf("expected fingerprint for %s: %w", endpoint.ID, fingerprintErr)
} else {
expected = value
}
}
issues := IssuesForObservation(observed, expected, probeErr, now().UTC())
if saveErr := c.Repository.SaveHealthIssues(ctx, endpoint.ID, issues); saveErr != nil {
errs <- fmt.Errorf("save endpoint issues %s: %w", endpoint.ID, saveErr)
}
}
}()
}
send:
for _, endpoint := range endpoints {
if !endpoint.Enabled {
continue
}
select {
case jobs <- endpoint:
case <-ctx.Done():
break send
}
}
close(jobs)
workers.Wait()
close(errs)
var combined []error
for workerErr := range errs {
combined = append(combined, workerErr)
}
if ctx.Err() != nil {
combined = append(combined, ctx.Err())
}
return errors.Join(combined...)
}
// Run checks immediately and then on every interval until cancellation.
// Transient cycle failures are reported but monitoring continues.
func (c *Checker) Run(ctx context.Context) error {
if c == nil {
return errors.New("health checker is nil")
}
interval := c.Interval
if interval <= 0 {
interval = 15 * time.Minute
}
report := func(err error) {
if err != nil && c.OnError != nil {
c.OnError(err)
}
}
report(c.RunOnce(ctx))
if ctx.Err() != nil {
return ctx.Err()
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
report(c.RunOnce(ctx))
}
}
}
func IssuesForObservation(endpoint domain.ObservedEndpoint, expectedFingerprint string, probeErr error, now time.Time) []domain.HealthIssue {
var issues []domain.HealthIssue
add := func(severity domain.Severity, kind, title, detail, action string) {
issues = append(issues, domain.HealthIssue{
ID: issueID(endpoint.ID, kind),
Severity: severity,
Kind: kind,
ResourceID: endpoint.ID,
Title: title,
Detail: detail,
Action: action,
ObservedAt: now.UTC(),
})
}
if probeErr != nil {
add(domain.SeverityCritical, "tls_probe_failed", "TLS endpoint is unreachable", probeErr.Error(), "Check DNS, firewall, port, and server TLS configuration")
return issues
}
if endpoint.NotAfter != nil && !endpoint.NotAfter.After(now) {
add(domain.SeverityCritical, "served_certificate_expired", "Served certificate is expired", "The public endpoint serves a certificate that expired at "+endpoint.NotAfter.UTC().Format(time.RFC3339), "Deploy a valid certificate immediately")
}
if !endpoint.ValidForHost {
add(domain.SeverityCritical, "served_certificate_wrong_host", "Served certificate does not cover the hostname", "The certificate SANs do not validate "+endpoint.Host, "Deploy a certificate containing this hostname")
}
if !endpoint.Trusted {
add(domain.SeverityWarning, "served_certificate_untrusted", "Served certificate chain is not publicly trusted", "The endpoint did not present a chain trusted by the configured root store", "Install the complete public certificate chain")
}
lowerExpected := strings.ToLower(expectedFingerprint)
revocationPending := strings.HasPrefix(lowerExpected, "revocation-pending:")
revokedFingerprint := strings.HasPrefix(lowerExpected, "revoked:")
expectedFingerprint = strings.TrimPrefix(lowerExpected, "revocation-pending:")
expectedFingerprint = strings.TrimPrefix(expectedFingerprint, "revoked:")
expectedFingerprint = strings.ReplaceAll(expectedFingerprint, ":", "")
observedFingerprint := strings.ToLower(strings.ReplaceAll(endpoint.FingerprintSHA256, ":", ""))
if revocationPending {
add(domain.SeverityWarning, "certificate_revocation_pending", "Certificate revocation status is unresolved", "A revocation request was recorded but its final CA result has not been reconciled locally", "Retry the revocation with the original reason before renewing or deploying this lineage")
} else if revokedFingerprint && expectedFingerprint != "" && expectedFingerprint == observedFingerprint {
add(domain.SeverityCritical, "served_certificate_revoked", "Endpoint still serves a revoked certificate", "The observed certificate was revoked by its issuing CA", "Deploy a new certificate immediately")
} else if !revokedFingerprint && expectedFingerprint != "" && observedFingerprint != "" && expectedFingerprint != observedFingerprint {
add(domain.SeverityWarning, "served_certificate_stale", "Endpoint serves a different certificate", "The observed fingerprint differs from the current locally managed certificate", "Deploy the current certificate and recheck")
}
return issues
}
func issueID(resourceID, kind string) string {
digest := sha256.Sum256([]byte(resourceID + "\x00" + kind))
return "issue_" + hex.EncodeToString(digest[:12])
}
+139
View File
@@ -0,0 +1,139 @@
package health
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
func TestIssuesForObservation(t *testing.T) {
now := time.Date(2026, 7, 11, 12, 0, 0, 0, time.UTC)
expired := now.Add(-time.Hour)
endpoint := domain.ObservedEndpoint{
ID: "endpoint", Host: "app.example.com", Port: 443,
FingerprintSHA256: "bbbb", NotAfter: &expired, ValidForHost: false, Trusted: false,
}
issues := IssuesForObservation(endpoint, "aaaa", nil, now)
want := map[string]bool{
"served_certificate_expired": false,
"served_certificate_wrong_host": false,
"served_certificate_untrusted": false,
"served_certificate_stale": false,
}
for _, issue := range issues {
if _, ok := want[issue.Kind]; ok {
want[issue.Kind] = true
}
if issue.ID == "" || issue.ResourceID != endpoint.ID || !issue.ObservedAt.Equal(now) {
t.Fatalf("invalid issue: %#v", issue)
}
}
for kind, found := range want {
if !found {
t.Errorf("missing issue %s in %#v", kind, issues)
}
}
revokedIssues := IssuesForObservation(domain.ObservedEndpoint{ID: "revoked-endpoint", Host: "example.com", FingerprintSHA256: "abcd", ValidForHost: true, Trusted: true}, "revoked:abcd", nil, now)
if len(revokedIssues) != 1 || revokedIssues[0].Kind != "served_certificate_revoked" || revokedIssues[0].Severity != domain.SeverityCritical {
t.Fatalf("revoked certificate issues = %#v", revokedIssues)
}
replacementIssues := IssuesForObservation(domain.ObservedEndpoint{ID: "replacement-endpoint", Host: "example.com", FingerprintSHA256: "ef01", ValidForHost: true, Trusted: true}, "revoked:abcd", nil, now)
for _, issue := range replacementIssues {
if issue.Kind == "served_certificate_stale" || issue.Kind == "served_certificate_revoked" {
t.Fatalf("replacement for revoked certificate was flagged against the revoked fingerprint: %#v", replacementIssues)
}
}
pendingIssues := IssuesForObservation(domain.ObservedEndpoint{ID: "pending-endpoint", Host: "example.com", FingerprintSHA256: "abcd", ValidForHost: true, Trusted: true}, "revocation-pending:abcd", nil, now)
if len(pendingIssues) != 1 || pendingIssues[0].Kind != "certificate_revocation_pending" {
t.Fatalf("pending revocation issues = %#v", pendingIssues)
}
failed := IssuesForObservation(endpoint, "", errors.New("connection refused"), now)
if len(failed) != 1 || failed[0].Kind != "tls_probe_failed" || failed[0].Severity != domain.SeverityCritical {
t.Fatalf("probe failure issues = %#v", failed)
}
}
func TestCheckerUsesBoundedConcurrencyAndPersistsEveryEndpoint(t *testing.T) {
var endpoints []domain.ObservedEndpoint
for i := 0; i < 20; i++ {
endpoints = append(endpoints, domain.ObservedEndpoint{ID: string(rune('a' + i)), ZoneID: "zone", Host: "example.com", Port: 443, Enabled: true})
}
repository := &checkerRepository{endpoints: endpoints}
prober := &boundedProber{}
checker := &Checker{Repository: repository, Prober: prober, Concurrency: 3, Now: func() time.Time { return time.Unix(100, 0).UTC() }}
if err := checker.RunOnce(context.Background()); err != nil {
t.Fatal(err)
}
if maximum := prober.maximum.Load(); maximum > 3 {
t.Fatalf("maximum concurrency = %d", maximum)
}
if got := repository.savedCount(); got != len(endpoints) {
t.Fatalf("saved endpoints = %d, want %d", got, len(endpoints))
}
}
type checkerRepository struct {
mu sync.Mutex
endpoints []domain.ObservedEndpoint
saved []domain.ObservedEndpoint
issues map[string][]domain.HealthIssue
}
func (r *checkerRepository) ListEndpoints(context.Context) ([]domain.ObservedEndpoint, error) {
return append([]domain.ObservedEndpoint(nil), r.endpoints...), nil
}
func (r *checkerRepository) SaveEndpoint(_ context.Context, endpoint domain.ObservedEndpoint) error {
r.mu.Lock()
defer r.mu.Unlock()
r.saved = append(r.saved, endpoint)
return nil
}
func (r *checkerRepository) SaveHealthIssues(_ context.Context, owner string, issues []domain.HealthIssue) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.issues == nil {
r.issues = make(map[string][]domain.HealthIssue)
}
r.issues[owner] = append([]domain.HealthIssue(nil), issues...)
return nil
}
func (r *checkerRepository) savedCount() int {
r.mu.Lock()
defer r.mu.Unlock()
return len(r.saved)
}
type boundedProber struct {
active atomic.Int32
maximum atomic.Int32
}
func (p *boundedProber) Probe(ctx context.Context, endpoint domain.ObservedEndpoint) (domain.ObservedEndpoint, error) {
active := p.active.Add(1)
for {
maximum := p.maximum.Load()
if active <= maximum || p.maximum.CompareAndSwap(maximum, active) {
break
}
}
defer p.active.Add(-1)
select {
case <-time.After(10 * time.Millisecond):
case <-ctx.Done():
return endpoint, ctx.Err()
}
now := time.Now().UTC()
future := now.Add(time.Hour)
endpoint.LastCheckedAt = &now
endpoint.NotAfter = &future
endpoint.ValidForHost = true
endpoint.Trusted = true
return endpoint, nil
}
+178
View File
@@ -0,0 +1,178 @@
// Package health performs cancellable public DNS and TLS observations without
// coupling network activity to TUI rendering.
package health
import (
"context"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"errors"
"fmt"
"net"
"slices"
"strconv"
"strings"
"time"
"crypto/tls"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
type Resolver interface {
LookupIPAddr(context.Context, string) ([]net.IPAddr, error)
}
type Dialer interface {
DialContext(context.Context, string, string) (net.Conn, error)
}
type Prober struct {
Resolver Resolver
Dialer Dialer
RootCAs *x509.CertPool
Timeout time.Duration
Now func() time.Time
}
func NewProber() *Prober {
return &Prober{
Resolver: net.DefaultResolver,
Dialer: &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second},
Timeout: 15 * time.Second,
Now: time.Now,
}
}
// Probe resolves the endpoint, tries each address, and performs a TLS handshake
// with SNI. Verification is manual so certificate identity, trust, and expiry
// metadata are still available when validation fails.
func (p *Prober) Probe(ctx context.Context, endpoint domain.ObservedEndpoint) (domain.ObservedEndpoint, error) {
result := endpoint
result.ResolvedAddresses = nil
result.FingerprintSHA256 = ""
result.Issuer = ""
result.NotAfter = nil
result.ValidForHost = false
result.Trusted = false
result.LastError = ""
now := time.Now
if p != nil && p.Now != nil {
now = p.Now
}
checkedAt := now().UTC()
result.LastCheckedAt = &checkedAt
if strings.TrimSpace(endpoint.Host) == "" {
err := errors.New("endpoint host is empty")
result.LastError = err.Error()
return result, err
}
port := endpoint.Port
if port == 0 {
port = 443
result.Port = port
}
if port < 1 || port > 65535 {
err := fmt.Errorf("endpoint port %d is outside 1..65535", port)
result.LastError = err.Error()
return result, err
}
resolver := Resolver(net.DefaultResolver)
if p != nil && p.Resolver != nil {
resolver = p.Resolver
}
lookup, err := resolver.LookupIPAddr(ctx, endpoint.Host)
if err != nil {
err = fmt.Errorf("resolve %s: %w", endpoint.Host, err)
result.LastError = err.Error()
return result, err
}
for _, address := range lookup {
if address.IP != nil {
result.ResolvedAddresses = append(result.ResolvedAddresses, address.IP.String())
}
}
slices.Sort(result.ResolvedAddresses)
result.ResolvedAddresses = slices.Compact(result.ResolvedAddresses)
if len(result.ResolvedAddresses) == 0 {
err = fmt.Errorf("resolve %s: no IP addresses returned", endpoint.Host)
result.LastError = err.Error()
return result, err
}
timeout := 15 * time.Second
if p != nil && p.Timeout > 0 {
timeout = p.Timeout
}
probeCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
dialer := Dialer(&net.Dialer{Timeout: timeout})
if p != nil && p.Dialer != nil {
dialer = p.Dialer
}
var attempts []error
for _, address := range result.ResolvedAddresses {
raw, dialErr := dialer.DialContext(probeCtx, "tcp", net.JoinHostPort(address, strconv.Itoa(port)))
if dialErr != nil {
attempts = append(attempts, fmt.Errorf("%s: %w", address, dialErr))
continue
}
connection := tls.Client(raw, &tls.Config{
ServerName: endpoint.Host,
InsecureSkipVerify: true, // Verification is performed independently below.
MinVersion: tls.VersionTLS12,
})
handshakeErr := connection.HandshakeContext(probeCtx)
if handshakeErr != nil {
_ = raw.Close()
attempts = append(attempts, fmt.Errorf("%s TLS handshake: %w", address, handshakeErr))
continue
}
state := connection.ConnectionState()
_ = connection.Close()
if len(state.PeerCertificates) == 0 {
attempts = append(attempts, fmt.Errorf("%s TLS handshake returned no peer certificate", address))
continue
}
observeCertificate(&result, endpoint.Host, state.PeerCertificates, p.rootCAs(), checkedAt)
return result, nil
}
err = fmt.Errorf("connect to %s:%d: %w", endpoint.Host, port, errors.Join(attempts...))
result.LastError = err.Error()
return result, err
}
func (p *Prober) rootCAs() *x509.CertPool {
if p == nil {
return nil
}
return p.RootCAs
}
func observeCertificate(result *domain.ObservedEndpoint, host string, peers []*x509.Certificate, roots *x509.CertPool, now time.Time) {
leaf := peers[0]
digest := sha256.Sum256(leaf.Raw)
result.FingerprintSHA256 = hex.EncodeToString(digest[:])
result.Issuer = leaf.Issuer.String()
notAfter := leaf.NotAfter.UTC()
result.NotAfter = &notAfter
result.ValidForHost = leaf.VerifyHostname(host) == nil
intermediates := x509.NewCertPool()
for _, certificate := range peers[1:] {
intermediates.AddCert(certificate)
}
options := x509.VerifyOptions{
Roots: roots,
Intermediates: intermediates,
CurrentTime: now,
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
_, trustErr := leaf.Verify(options)
result.Trusted = trustErr == nil
}
+14
View File
@@ -0,0 +1,14 @@
package identifier
import (
"crypto/rand"
"encoding/hex"
)
func New(prefix string) string {
var b [12]byte
if _, err := rand.Read(b[:]); err != nil {
panic("domainops: secure random source unavailable: " + err.Error())
}
return prefix + "_" + hex.EncodeToString(b[:])
}
+38
View File
@@ -0,0 +1,38 @@
//go:build !darwin && !linux
package lockfile
import (
"errors"
"os"
"path/filepath"
)
type Lock struct {
path string
file *os.File
}
func Acquire(path string) (*Lock, error) {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return nil, err
}
file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0o600)
if errors.Is(err, os.ErrExist) {
return nil, errors.New("DomainOps is already running for this data directory")
}
if err != nil {
return nil, err
}
return &Lock{path: path, file: file}, nil
}
func (l *Lock) Close() error {
if l == nil || l.file == nil {
return nil
}
err := l.file.Close()
_ = os.Remove(l.path)
l.file = nil
return err
}
+49
View File
@@ -0,0 +1,49 @@
//go:build darwin || linux
package lockfile
import (
"fmt"
"os"
"path/filepath"
"golang.org/x/sys/unix"
)
type Lock struct {
file *os.File
}
func Acquire(path string) (*Lock, error) {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return nil, err
}
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
if err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
_ = file.Close()
if err == unix.EWOULDBLOCK {
return nil, fmt.Errorf("DomainOps is already running for this data directory")
}
return nil, fmt.Errorf("lock DomainOps state: %w", err)
}
_ = file.Truncate(0)
_, _ = fmt.Fprintf(file, "%d\n", os.Getpid())
_ = file.Sync()
return &Lock{file: file}, nil
}
func (l *Lock) Close() error {
if l == nil || l.file == nil {
return nil
}
unlockErr := unix.Flock(int(l.file.Fd()), unix.LOCK_UN)
closeErr := l.file.Close()
l.file = nil
if unlockErr != nil {
return unlockErr
}
return closeErr
}
+128
View File
@@ -0,0 +1,128 @@
package provider
import (
"context"
"errors"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
// CredentialVerificationAuthoritative is implemented by provider errors that
// prove the configured credential itself is unusable (for example, an
// authentication rejection). Transport failures, rate limits, server errors,
// and malformed responses must not implement this contract: they say nothing
// authoritative about a credential that was previously valid.
type CredentialVerificationAuthoritative interface {
CredentialVerificationAuthoritative() bool
}
// AccessDenialAuthoritative is implemented only by provider errors that prove
// access to a specific resource is denied. It must not be implemented by rate
// limits, server failures, transport errors, or ambiguous responses.
type AccessDenialAuthoritative interface {
AccessDenialAuthoritative() bool
}
// CredentialFailureIsAuthoritative reports whether a failed verification can
// safely transition a credential to invalid. Unknown errors are deliberately
// treated as transient so a healthy credential is not disabled during an
// upstream outage.
func CredentialFailureIsAuthoritative(err error) bool {
var classified CredentialVerificationAuthoritative
return errors.As(err, &classified) && classified.CredentialVerificationAuthoritative()
}
func AccessFailureIsAuthoritative(err error) bool {
var classified AccessDenialAuthoritative
return errors.As(err, &classified) && classified.AccessDenialAuthoritative()
}
type Auth struct {
CredentialID string
Token string
Kind domain.CredentialKind
AccountID string
}
type Capabilities struct {
ZoneRead bool `json:"zone_read"`
DNSRead bool `json:"dns_read"`
DNSWrite bool `json:"dns_write"`
TLSRead bool `json:"tls_read"`
TLSWrite bool `json:"tls_write"`
Names []string `json:"names"`
}
type Verification struct {
Status domain.CredentialStatus `json:"status"`
Capabilities Capabilities `json:"capabilities"`
Accounts []domain.RemoteAccount `json:"accounts,omitempty"`
}
type PageRequest struct {
Cursor string
Page int
PerPage int
Search string
}
type ZonePage struct {
Zones []domain.Zone
NextCursor string
Page int
TotalPages int
}
type RecordPage struct {
Records []domain.DNSRecord
NextCursor string
Page int
TotalPages int
}
type CredentialVerifier interface {
VerifyCredential(context.Context, Auth) (Verification, error)
}
type ZoneInventory interface {
ListZones(context.Context, Auth, PageRequest) (ZonePage, error)
}
type DNSRecordService interface {
ListDNSRecords(context.Context, Auth, string, PageRequest) (RecordPage, error)
GetDNSRecord(context.Context, Auth, string, string) (domain.DNSRecord, error)
CreateDNSRecord(context.Context, Auth, string, domain.DNSRecord) (domain.DNSRecord, error)
PatchDNSRecord(context.Context, Auth, string, string, domain.DNSRecord) (domain.DNSRecord, error)
DeleteDNSRecord(context.Context, Auth, string, string) error
}
type DNSBatchService interface {
ApplyDNSBatch(context.Context, Auth, string, []domain.DNSMutation) ([]domain.DNSRecord, error)
}
type DNS01Solver interface {
PresentDNS01(context.Context, Auth, string, string, string, string) (string, error)
CleanupDNS01(context.Context, Auth, string, string) error
}
// DNS01Reconciler is an optional recovery capability for a provider that can
// locate a challenge after an ambiguous create response. Implementations must
// match the exact owner, job marker, and value hash and reject ambiguity.
type DNS01Reconciler interface {
ReconcileDNS01(context.Context, Auth, string, string, string, string) (recordID string, found bool, err error)
}
type EdgeTLSService interface {
GetEdgeTLSSettings(context.Context, Auth, string) (domain.EdgeTLSSettings, error)
UpdateEdgeTLSSettings(context.Context, Auth, string, domain.EdgeTLSSettings, domain.EdgeTLSSettings) (domain.EdgeTLSSettings, error)
ListEdgeCertificates(context.Context, Auth, string, PageRequest) ([]domain.EdgeCertificate, error)
}
type CloudProvider interface {
CredentialVerifier
ZoneInventory
DNSRecordService
DNSBatchService
DNS01Solver
EdgeTLSService
}
+295
View File
@@ -0,0 +1,295 @@
// Package cloudflare implements DomainOps' provider contracts against the
// documented Cloudflare v4 REST API.
package cloudflare
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
const (
defaultBaseURL = "https://api.cloudflare.com/client/v4/"
defaultUserAgent = "DomainOps/1"
defaultRequestLimit = int64(16 << 20)
)
// HTTPDoer is the portion of http.Client used by Client. It is deliberately
// small so callers can inject tracing, rate limiting, or a deterministic test
// transport without changing provider code.
type HTTPDoer interface {
Do(*http.Request) (*http.Response, error)
}
// Options customizes a Client. BaseURL and HTTPClient are principally useful
// for integration tests and trusted Cloudflare-compatible gateways.
type Options struct {
BaseURL string
HTTPClient HTTPDoer
UserAgent string
Now func() time.Time
}
// Client implements provider.CloudProvider.
type Client struct {
baseURL string
httpClient HTTPDoer
userAgent string
now func() time.Time
}
var _ provider.CloudProvider = (*Client)(nil)
// New returns a production Cloudflare client.
func New() *Client {
c, err := NewWithOptions(Options{})
if err != nil {
// All defaults are compile-time constants, so this can only indicate a
// programming error in this package.
panic(err)
}
return c
}
// NewWithOptions returns a Cloudflare client with injectable HTTP behavior.
func NewWithOptions(opts Options) (*Client, error) {
base := strings.TrimSpace(opts.BaseURL)
if base == "" {
base = defaultBaseURL
}
u, err := url.Parse(base)
if err != nil {
return nil, fmt.Errorf("cloudflare: invalid base URL: %w", err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return nil, fmt.Errorf("cloudflare: base URL must use http or https")
}
if u.Host == "" {
return nil, fmt.Errorf("cloudflare: base URL must include a host")
}
if u.User != nil {
return nil, fmt.Errorf("cloudflare: base URL cannot include user information")
}
if u.RawQuery != "" || u.Fragment != "" {
return nil, fmt.Errorf("cloudflare: base URL cannot include a query or fragment")
}
if !strings.HasSuffix(u.Path, "/") {
u.Path += "/"
}
doer := opts.HTTPClient
if doer == nil {
doer = &http.Client{Timeout: 30 * time.Second}
}
userAgent := strings.TrimSpace(opts.UserAgent)
if userAgent == "" {
userAgent = defaultUserAgent
}
now := opts.Now
if now == nil {
now = time.Now
}
return &Client{
baseURL: u.String(),
httpClient: doer,
userAgent: userAgent,
now: now,
}, nil
}
type responseEnvelope struct {
Success *bool `json:"success"`
Errors []apiMessage `json:"errors"`
Messages []apiMessage `json:"messages"`
Result json.RawMessage `json:"result"`
ResultInfo resultInfo `json:"result_info"`
}
type apiMessage struct {
Code int `json:"code"`
Message string `json:"message"`
DocumentationURL string `json:"documentation_url"`
Source messageSource `json:"source"`
ErrorChain []apiMessage `json:"error_chain"`
}
type messageSource struct {
Pointer string `json:"pointer"`
}
type resultInfo struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
Count int `json:"count"`
TotalCount int `json:"total_count"`
TotalPages int `json:"total_pages"`
Cursors struct {
Before string `json:"before"`
After string `json:"after"`
} `json:"cursors"`
}
func (c *Client) do(
ctx context.Context,
auth provider.Auth,
method string,
path string,
query url.Values,
body any,
) (json.RawMessage, resultInfo, error) {
if err := validateAuth(auth); err != nil {
return nil, resultInfo{}, err
}
endpoint := c.baseURL + strings.TrimPrefix(path, "/")
if len(query) > 0 {
endpoint += "?" + query.Encode()
}
var requestBody io.Reader
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: encode request: %w", err)
}
requestBody = bytes.NewReader(encoded)
}
req, err := http.NewRequestWithContext(ctx, method, endpoint, requestBody)
if err != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: create request: %w", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(auth.Token))
req.Header.Set("User-Agent", c.userAgent)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: %s %s: %w", method, path, err)
}
defer resp.Body.Close()
limited := io.LimitReader(resp.Body, defaultRequestLimit+1)
payload, err := io.ReadAll(limited)
if err != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: read response: %w", err)
}
if int64(len(payload)) > defaultRequestLimit {
return nil, resultInfo{}, fmt.Errorf("cloudflare: response exceeded %d bytes", defaultRequestLimit)
}
var env responseEnvelope
decodeErr := json.Unmarshal(payload, &env)
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
apiErr := newAPIError(method, path, resp, env.Errors, env.Messages)
if decodeErr != nil || len(payload) == 0 {
apiErr.Message = http.StatusText(resp.StatusCode)
}
if resp.StatusCode == http.StatusTooManyRequests {
return nil, resultInfo{}, newRateLimitError(apiErr, resp.Header, c.now())
}
return nil, resultInfo{}, apiErr
}
if decodeErr != nil {
return nil, resultInfo{}, fmt.Errorf("cloudflare: decode %s %s response: %w", method, path, decodeErr)
}
if env.Success == nil {
return nil, resultInfo{}, &ResponseError{
Resource: method + " " + path + " envelope",
Err: fmt.Errorf("required success field is missing or null"),
}
}
if !*env.Success {
return nil, resultInfo{}, newAPIError(method, path, resp, env.Errors, env.Messages)
}
return cloneRaw(env.Result), env.ResultInfo, nil
}
func validateAuth(auth provider.Auth) error {
if strings.TrimSpace(auth.Token) == "" {
return &ValidationError{Field: "token", Message: "API token is required"}
}
switch auth.Kind {
case domain.CredentialUserToken:
return nil
case domain.CredentialAccountToken:
if strings.TrimSpace(auth.AccountID) == "" {
return &ValidationError{Field: "account_id", Message: "account-owned tokens require an account ID"}
}
return nil
default:
return &ValidationError{Field: "kind", Message: "only scoped user and account API tokens are supported"}
}
}
func apiPath(segments ...string) (string, error) {
escaped := make([]string, len(segments))
for i, segment := range segments {
if strings.TrimSpace(segment) == "" {
return "", &ValidationError{Field: "identifier", Message: "Cloudflare identifier cannot be empty"}
}
escaped[i] = url.PathEscape(segment)
}
return strings.Join(escaped, "/"), nil
}
func paginationQuery(req provider.PageRequest, defaultPerPage, maxPerPage int) (url.Values, int) {
perPage := req.PerPage
if perPage <= 0 {
perPage = defaultPerPage
}
if perPage > maxPerPage {
perPage = maxPerPage
}
page := req.Page
if page <= 0 {
page = 1
}
q := url.Values{
"page": {strconv.Itoa(page)},
"per_page": {strconv.Itoa(perPage)},
}
if req.Cursor != "" {
if cursorPage, err := strconv.Atoi(req.Cursor); err == nil && cursorPage > 0 {
page = cursorPage
q.Set("page", strconv.Itoa(page))
} else {
q.Set("cursor", req.Cursor)
}
}
return q, page
}
func nextCursor(info resultInfo, page, resultCount, perPage int) string {
if info.Cursors.After != "" {
return info.Cursors.After
}
if info.TotalPages > page {
return strconv.Itoa(page + 1)
}
if info.TotalPages == 0 && perPage > 0 && resultCount == perPage {
return strconv.Itoa(page + 1)
}
return ""
}
func cloneRaw(raw json.RawMessage) json.RawMessage {
if len(raw) == 0 {
return nil
}
return append(json.RawMessage(nil), raw...)
}
@@ -0,0 +1,409 @@
package cloudflare
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
var fixedNow = time.Date(2026, time.July, 11, 9, 30, 0, 0, time.UTC)
func testAuth() provider.Auth {
return provider.Auth{
CredentialID: "cred-1",
Token: "test-secret-token",
Kind: domain.CredentialUserToken,
}
}
func newTestClient(t *testing.T, handler http.HandlerFunc) *Client {
t.Helper()
client, err := NewWithOptions(Options{
BaseURL: "https://api.cloudflare.test/client/v4",
HTTPClient: handlerDoer{handler: handler},
UserAgent: "DomainOps-test/1",
Now: func() time.Time { return fixedNow },
})
if err != nil {
t.Fatalf("NewWithOptions: %v", err)
}
return client
}
type handlerDoer struct{ handler http.Handler }
func (d handlerDoer) Do(request *http.Request) (*http.Response, error) {
recorder := httptest.NewRecorder()
d.handler.ServeHTTP(recorder, request)
return recorder.Result(), nil
}
func writeResult(t *testing.T, w http.ResponseWriter, result any, info any) {
t.Helper()
w.Header().Set("Content-Type", "application/json")
response := map[string]any{
"success": true,
"errors": []any{},
"messages": []any{},
"result": result,
}
if info != nil {
response["result_info"] = info
}
if err := json.NewEncoder(w).Encode(response); err != nil {
t.Errorf("encode response: %v", err)
}
}
func verifyRequestHeaders(t *testing.T, r *http.Request) {
t.Helper()
if got := r.Header.Get("Authorization"); got != "Bearer test-secret-token" {
t.Errorf("Authorization = %q", got)
}
if got := r.Header.Get("User-Agent"); got != "DomainOps-test/1" {
t.Errorf("User-Agent = %q", got)
}
if got := r.Header.Get("Accept"); got != "application/json" {
t.Errorf("Accept = %q", got)
}
}
func TestNewWithOptionsRejectsInvalidBaseURL(t *testing.T) {
t.Parallel()
for _, baseURL := range []string{"ftp://api.example.test", "https:///missing-host", "https://example.test/?bad=1", "https://user:pass@example.test"} {
if _, err := NewWithOptions(Options{BaseURL: baseURL}); err == nil {
t.Errorf("NewWithOptions(%q) unexpectedly succeeded", baseURL)
}
}
}
func TestDNSNameConversionPreservesServiceAndWildcardLabels(t *testing.T) {
t.Parallel()
for input, want := range map[string]string{
"*.bücher.example.": "*.xn--bcher-kva.example",
"_acme-challenge.bücher.example.": "_acme-challenge.xn--bcher-kva.example",
} {
got, err := toASCIIName(input)
if err != nil {
t.Errorf("toASCIIName(%q): %v", input, err)
continue
}
if got != want {
t.Errorf("toASCIIName(%q) = %q, want %q", input, got, want)
}
}
}
func TestVerifyCredentialUserTokenAndCapabilityProbes(t *testing.T) {
t.Parallel()
var calls atomic.Int32
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
verifyRequestHeaders(t, r)
switch r.URL.Path {
case "/client/v4/user/tokens/verify":
writeResult(t, w, map[string]any{"id": "token-1", "status": "active"}, nil)
case "/client/v4/accounts":
writeResult(t, w, []any{
map[string]any{"id": "acct-1", "name": "Production", "created_on": "2024-01-02T03:04:05Z"},
map[string]any{"id": "acct-2", "name": "Labs"},
}, map[string]any{"page": 1, "per_page": 50, "total_pages": 1})
case "/client/v4/zones":
if got := r.URL.Query().Get("per_page"); got != "50" {
t.Errorf("zones per_page = %q", got)
}
writeResult(t, w, []any{map[string]any{
"id": "zone-1", "name": "example.com", "status": "active",
"account": map[string]any{"id": "acct-1", "name": "Production"},
}}, map[string]any{"page": 1, "total_pages": 1})
case "/client/v4/zones/zone-1/dns_records":
writeResult(t, w, []any{}, map[string]any{"page": 1, "total_pages": 1})
case "/client/v4/zones/zone-1/settings/ssl":
writeResult(t, w, map[string]any{"id": "ssl", "value": "strict"}, nil)
default:
http.NotFound(w, r)
}
})
verification, err := client.VerifyCredential(context.Background(), testAuth())
if err != nil {
t.Fatalf("VerifyCredential: %v", err)
}
if verification.Status != domain.CredentialValid {
t.Fatalf("status = %q", verification.Status)
}
capabilities := verification.Capabilities
if !capabilities.ZoneRead || !capabilities.DNSRead || capabilities.DNSWrite || !capabilities.TLSRead || capabilities.TLSWrite {
t.Errorf("capabilities = %+v", capabilities)
}
if got, want := strings.Join(capabilities.Names, ","), "dns:read,tls:read,zone:read"; got != want {
t.Errorf("capability names = %q, want %q", got, want)
}
if len(verification.Accounts) != 2 || verification.Accounts[0].ProviderID != "acct-1" {
t.Fatalf("accounts = %+v", verification.Accounts)
}
if verification.Accounts[0].LastSyncedAt == nil || !verification.Accounts[0].LastSyncedAt.Equal(fixedNow) {
t.Errorf("account sync timestamp = %v", verification.Accounts[0].LastSyncedAt)
}
if got := calls.Load(); got != 5 {
t.Errorf("request count = %d, want 5", got)
}
}
func TestVerifyCredentialAccountTokenUsesAccountNamespace(t *testing.T) {
t.Parallel()
auth := testAuth()
auth.Kind = domain.CredentialAccountToken
auth.AccountID = "account-owned"
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/client/v4/accounts/account-owned/tokens/verify":
writeResult(t, w, map[string]any{"id": "token-2", "status": "active"}, nil)
case "/client/v4/accounts/account-owned":
writeResult(t, w, map[string]any{"id": "account-owned", "name": "Owned account"}, nil)
case "/client/v4/zones":
if got := r.URL.Query().Get("account.id"); got != "account-owned" {
t.Errorf("account.id = %q", got)
}
writeResult(t, w, []any{}, map[string]any{"page": 1, "total_pages": 1})
default:
http.NotFound(w, r)
}
})
verification, err := client.VerifyCredential(context.Background(), auth)
if err != nil {
t.Fatalf("VerifyCredential: %v", err)
}
if verification.Status != domain.CredentialValid || len(verification.Accounts) != 1 {
t.Fatalf("verification = %+v", verification)
}
if !verification.Capabilities.ZoneRead || verification.Capabilities.DNSRead {
t.Errorf("capabilities = %+v", verification.Capabilities)
}
}
func TestVerifyCredentialInactiveAndRejectsUnsupportedAuth(t *testing.T) {
t.Parallel()
var requests atomic.Int32
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
writeResult(t, w, map[string]any{"id": "token", "status": "expired"}, nil)
})
verification, err := client.VerifyCredential(context.Background(), testAuth())
if err != nil {
t.Fatalf("expired token: %v", err)
}
if verification.Status != domain.CredentialInvalid || requests.Load() != 1 {
t.Fatalf("verification = %+v, requests = %d", verification, requests.Load())
}
bad := testAuth()
bad.Kind = domain.CredentialKind("global_api_key")
_, err = client.VerifyCredential(context.Background(), bad)
var validation *ValidationError
if !errors.As(err, &validation) || requests.Load() != 1 {
t.Fatalf("unsupported auth error = %v, requests = %d", err, requests.Load())
}
}
func TestListZonesPaginationAndMapping(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/client/v4/zones" {
http.NotFound(w, r)
return
}
if got := r.URL.Query().Get("page"); got != "2" {
t.Errorf("page = %q", got)
}
if got := r.URL.Query().Get("name"); got != "example.com" {
t.Errorf("name = %q", got)
}
writeResult(t, w, []any{map[string]any{
"id": "zone-2", "name": "xn--bcher-kva.example", "status": "mystery", "paused": true,
"modified_on": "2026-01-02T03:04:05.123Z",
"account": map[string]any{"id": "acct", "name": "Account"},
"plan": map[string]any{"name": "Pro"}, "name_servers": []string{"ada.ns.cloudflare.com"},
}}, map[string]any{"page": 2, "per_page": 1, "total_pages": 3})
})
page, err := client.ListZones(context.Background(), testAuth(), provider.PageRequest{Cursor: "2", PerPage: 1, Search: "example.com"})
if err != nil {
t.Fatalf("ListZones: %v", err)
}
if page.Page != 2 || page.NextCursor != "3" || page.TotalPages != 3 {
t.Errorf("page metadata = %+v", page)
}
if len(page.Zones) != 1 {
t.Fatalf("zones = %+v", page.Zones)
}
zone := page.Zones[0]
if zone.ID != "zone-2" || zone.ProviderID != "zone-2" || zone.AccountID != "acct" || zone.Status != domain.ZoneUnknown || zone.Plan != "Pro" || !zone.Paused {
t.Errorf("mapped zone = %+v", zone)
}
if zone.UnicodeName != "bücher.example" {
t.Errorf("unicode name = %q", zone.UnicodeName)
}
}
func TestStructuredAPIErrorsAndRateLimits(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", "7")
w.Header().Set("CF-Ray", "ray-test")
w.WriteHeader(http.StatusTooManyRequests)
_ = json.NewEncoder(w).Encode(map[string]any{
"success": false,
"errors": []any{map[string]any{
"code": 1015, "message": "rate limit exceeded",
"source": map[string]any{"pointer": "/zones"},
}},
})
})
_, err := client.ListZones(context.Background(), testAuth(), provider.PageRequest{})
if !errors.Is(err, ErrRateLimited) {
t.Fatalf("error = %v", err)
}
var rateLimit *RateLimitError
if !errors.As(err, &rateLimit) {
t.Fatalf("not RateLimitError: %T", err)
}
if rateLimit.RetryAfter != 7*time.Second || !rateLimit.RetryAt.Equal(fixedNow.Add(7*time.Second)) {
t.Errorf("rate metadata = %+v", rateLimit)
}
var apiErr *APIError
if !errors.As(err, &apiErr) || apiErr.Code != 1015 || apiErr.RequestID != "ray-test" || apiErr.Details[0].Pointer != "/zones" {
t.Errorf("API error = %+v", apiErr)
}
if strings.Contains(err.Error(), testAuth().Token) {
t.Error("error exposed API token")
}
}
func TestSuccessfulHTTPEnvelopeRejectionIsDefinitive(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"success": false,
"errors": []any{map[string]any{
"code": 1004, "message": "DNS validation failed",
}},
})
})
_, err := client.ListZones(context.Background(), testAuth(), provider.PageRequest{})
var apiErr *APIError
if !errors.As(err, &apiErr) {
t.Fatalf("error = %T %v, want *APIError", err, err)
}
if apiErr.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want %d", apiErr.StatusCode, http.StatusOK)
}
if !apiErr.MutationOutcomeDefinitive() {
t.Fatal("HTTP 200 success:false rejection must be definitive")
}
}
func TestSuccessfulHTTPEnvelopeRequiresExplicitSuccess(t *testing.T) {
t.Parallel()
tests := []struct {
name string
body map[string]any
}{
{
name: "missing",
body: map[string]any{"result": []any{}},
},
{
name: "null",
body: map[string]any{"success": nil, "result": []any{}},
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) {
if err := json.NewEncoder(w).Encode(test.body); err != nil {
t.Errorf("encode response: %v", err)
}
})
_, err := client.ListZones(context.Background(), testAuth(), provider.PageRequest{})
var responseErr *ResponseError
if !errors.As(err, &responseErr) {
t.Fatalf("error = %T %v, want *ResponseError", err, err)
}
var definitive interface {
MutationOutcomeDefinitive() bool
}
if errors.As(err, &definitive) && definitive.MutationOutcomeDefinitive() {
t.Fatal("missing or null success must leave a mutation outcome ambiguous")
}
})
}
}
func TestCredentialVerificationErrorClassification(t *testing.T) {
t.Parallel()
tests := []struct {
name string
err error
want bool
}{
{name: "local invalid auth", err: &ValidationError{Field: "auth.kind", Message: "unsupported"}, want: true},
{name: "unauthorized", err: &APIError{StatusCode: http.StatusUnauthorized}, want: true},
{name: "forbidden", err: &APIError{StatusCode: http.StatusForbidden}, want: true},
{name: "rate limited", err: newRateLimitError(&APIError{StatusCode: http.StatusTooManyRequests}, http.Header{}, fixedNow), want: false},
{name: "server failure", err: &APIError{StatusCode: http.StatusBadGateway}, want: false},
{name: "ambiguous response", err: &ResponseError{Resource: "token verification", Err: errors.New("malformed")}, want: false},
{name: "network failure", err: errors.New("connection reset"), want: false},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
if got := provider.CredentialFailureIsAuthoritative(test.err); got != test.want {
t.Fatalf("CredentialFailureIsAuthoritative(%T) = %v, want %v", test.err, got, test.want)
}
})
}
}
func TestZoneAccessDenialClassification(t *testing.T) {
t.Parallel()
tests := []struct {
name string
err error
want bool
}{
{name: "unauthorized", err: &APIError{StatusCode: http.StatusUnauthorized}, want: true},
{name: "forbidden", err: &APIError{StatusCode: http.StatusForbidden}, want: true},
{name: "rate limited", err: newRateLimitError(&APIError{StatusCode: http.StatusTooManyRequests}, http.Header{}, fixedNow), want: false},
{name: "server failure", err: &APIError{StatusCode: http.StatusServiceUnavailable}, want: false},
{name: "ambiguous response", err: &ResponseError{Resource: "DNS records", Err: errors.New("malformed")}, want: false},
{name: "network failure", err: errors.New("connection reset"), want: false},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
if got := provider.AccessFailureIsAuthoritative(test.err); got != test.want {
t.Fatalf("AccessFailureIsAuthoritative(%T) = %v, want %v", test.err, got, test.want)
}
})
}
}
+389
View File
@@ -0,0 +1,389 @@
package cloudflare
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
// ListDNSRecords lists one record page. Every provider response is retained in
// DNSRecord.Raw so record types introduced by Cloudflare remain visible and can
// be round-tripped through DomainOps storage without lossy decoding.
func (c *Client) ListDNSRecords(ctx context.Context, auth provider.Auth, zoneID string, request provider.PageRequest) (provider.RecordPage, error) {
path, err := apiPath("zones", zoneID, "dns_records")
if err != nil {
return provider.RecordPage{}, err
}
query, page := paginationQuery(request, 100, 5000)
if search := strings.TrimSpace(request.Search); search != "" {
query.Set("search", search)
}
raw, info, err := c.do(ctx, auth, http.MethodGet, path, query, nil)
if err != nil {
return provider.RecordPage{}, err
}
records, err := c.mapRecordArray(raw, zoneID)
if err != nil {
return provider.RecordPage{}, err
}
return provider.RecordPage{
Records: records,
NextCursor: nextCursor(info, page, len(records), queryPerPage(request, 100, 5000)),
Page: page,
TotalPages: info.TotalPages,
}, nil
}
// GetDNSRecord retrieves one record by its exact Cloudflare identifier.
func (c *Client) GetDNSRecord(ctx context.Context, auth provider.Auth, zoneID, recordID string) (domain.DNSRecord, error) {
path, err := apiPath("zones", zoneID, "dns_records", recordID)
if err != nil {
return domain.DNSRecord{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodGet, path, nil, nil)
if err != nil {
return domain.DNSRecord{}, err
}
return mapRecord(raw, zoneID, c.now().UTC())
}
// CreateDNSRecord creates one editable provider-neutral record.
func (c *Client) CreateDNSRecord(ctx context.Context, auth provider.Auth, zoneID string, record domain.DNSRecord) (domain.DNSRecord, error) {
payload, err := makeRecordPayload(record)
if err != nil {
return domain.DNSRecord{}, err
}
path, err := apiPath("zones", zoneID, "dns_records")
if err != nil {
return domain.DNSRecord{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodPost, path, nil, payload)
if err != nil {
return domain.DNSRecord{}, err
}
return mapRecord(raw, zoneID, c.now().UTC())
}
// PatchDNSRecord updates one record without replacing provider-managed fields.
func (c *Client) PatchDNSRecord(ctx context.Context, auth provider.Auth, zoneID, recordID string, record domain.DNSRecord) (domain.DNSRecord, error) {
payload, err := makeRecordPayload(record)
if err != nil {
return domain.DNSRecord{}, err
}
path, err := apiPath("zones", zoneID, "dns_records", recordID)
if err != nil {
return domain.DNSRecord{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodPatch, path, nil, payload)
if err != nil {
return domain.DNSRecord{}, err
}
return mapRecord(raw, zoneID, c.now().UTC())
}
// DeleteDNSRecord permanently removes the exact record identifier.
func (c *Client) DeleteDNSRecord(ctx context.Context, auth provider.Auth, zoneID, recordID string) error {
path, err := apiPath("zones", zoneID, "dns_records", recordID)
if err != nil {
return err
}
_, _, err = c.do(ctx, auth, http.MethodDelete, path, nil, nil)
return err
}
type dnsBatchPayload struct {
Deletes []map[string]any `json:"deletes,omitempty"`
Patches []map[string]any `json:"patches,omitempty"`
Puts []map[string]any `json:"puts,omitempty"`
Posts []map[string]any `json:"posts,omitempty"`
}
type dnsBatchResult struct {
Deletes []json.RawMessage `json:"deletes"`
Patches []json.RawMessage `json:"patches"`
Puts []json.RawMessage `json:"puts"`
Posts []json.RawMessage `json:"posts"`
}
// ApplyDNSBatch sends a zone-scoped Cloudflare batch. Results follow
// Cloudflare's documented execution order: deletes, patches, puts, then posts.
func (c *Client) ApplyDNSBatch(ctx context.Context, auth provider.Auth, zoneID string, mutations []domain.DNSMutation) ([]domain.DNSRecord, error) {
if len(mutations) == 0 {
return []domain.DNSRecord{}, nil
}
payload := dnsBatchPayload{}
for index, mutation := range mutations {
switch mutation.Kind {
case domain.MutationCreate:
if mutation.After == nil {
return nil, mutationError(index, "create requires an after record")
}
record, err := makeRecordPayload(*mutation.After)
if err != nil {
return nil, fmt.Errorf("cloudflare: batch mutation %d: %w", index, err)
}
payload.Posts = append(payload.Posts, record)
case domain.MutationPatch, domain.MutationReplace:
if mutation.After == nil {
return nil, mutationError(index, "update requires an after record")
}
id := mutationRecordID(mutation)
if id == "" {
return nil, mutationError(index, "update requires a record ID")
}
record, err := makeRecordPayload(*mutation.After)
if err != nil {
return nil, fmt.Errorf("cloudflare: batch mutation %d: %w", index, err)
}
record["id"] = id
if mutation.Kind == domain.MutationPatch {
payload.Patches = append(payload.Patches, record)
} else {
payload.Puts = append(payload.Puts, record)
}
case domain.MutationDelete:
id := mutationRecordID(mutation)
if id == "" {
return nil, mutationError(index, "delete requires a record ID")
}
payload.Deletes = append(payload.Deletes, map[string]any{"id": id})
default:
return nil, mutationError(index, "unknown mutation kind "+string(mutation.Kind))
}
}
path, err := apiPath("zones", zoneID, "dns_records", "batch")
if err != nil {
return nil, err
}
raw, _, err := c.do(ctx, auth, http.MethodPost, path, nil, payload)
if err != nil {
return nil, err
}
var batch dnsBatchResult
if err := json.Unmarshal(raw, &batch); err != nil {
return nil, &ResponseError{Resource: "DNS batch", Err: err}
}
ordered := make([]json.RawMessage, 0, len(batch.Deletes)+len(batch.Patches)+len(batch.Puts)+len(batch.Posts))
ordered = append(ordered, batch.Deletes...)
ordered = append(ordered, batch.Patches...)
ordered = append(ordered, batch.Puts...)
ordered = append(ordered, batch.Posts...)
return c.mapRecordWires(ordered, zoneID)
}
// PresentDNS01 creates a single TXT challenge and returns the exact Cloudflare
// ID. The job identifier is recorded only as a non-secret provider comment.
func (c *Client) PresentDNS01(ctx context.Context, auth provider.Auth, zoneID, fqdn, value, jobID string) (string, error) {
comment := "DomainOps ACME DNS-01"
if jobID = strings.TrimSpace(jobID); jobID != "" {
comment += " job=" + jobID
}
// Cloudflare DNS comments are bounded; trimming affects only diagnostics,
// never the challenge owner or value.
if len(comment) > 100 {
comment = comment[:100]
}
record, err := c.CreateDNSRecord(ctx, auth, zoneID, domain.DNSRecord{
ZoneID: zoneID,
Type: domain.RecordTXT,
Name: fqdn,
Content: value,
TTL: 60,
Comment: comment,
})
if err != nil {
return "", err
}
id := record.ProviderID
if id == "" {
id = record.ID
}
if id == "" {
return "", &ResponseError{Resource: "DNS-01 create", Err: errors.New("response omitted record ID")}
}
return id, nil
}
// CleanupDNS01 deletes only the exact record ID returned by PresentDNS01. It
// never searches by owner name or TXT value, avoiding removal of concurrent
// ACME challenges.
func (c *Client) CleanupDNS01(ctx context.Context, auth provider.Auth, zoneID, recordID string) error {
err := c.DeleteDNSRecord(ctx, auth, zoneID, recordID)
if errors.Is(err, ErrNotFound) {
return nil
}
return err
}
// ReconcileDNS01 locates a challenge after an ambiguous create response. The
// job marker is diagnostic rather than secret; the plaintext TXT value is
// compared only through its journaled SHA-256 digest.
func (c *Client) ReconcileDNS01(ctx context.Context, auth provider.Auth, zoneID, fqdn, valueHash, jobID string) (string, bool, error) {
owner, err := toASCIIName(fqdn)
if err != nil {
return "", false, err
}
request := provider.PageRequest{Page: 1, PerPage: 100, Search: owner}
var matches []string
for {
page, listErr := c.ListDNSRecords(ctx, auth, zoneID, request)
if listErr != nil {
return "", false, listErr
}
for _, record := range page.Records {
if record.Type != domain.RecordTXT || !strings.EqualFold(strings.TrimSuffix(record.Name, "."), owner) || !commentContainsJob(record.Comment, jobID) {
continue
}
digest := sha256.Sum256([]byte(record.Content))
if !strings.EqualFold(hex.EncodeToString(digest[:]), strings.TrimSpace(valueHash)) {
continue
}
id := record.ProviderID
if id == "" {
id = record.ID
}
if id != "" {
matches = append(matches, id)
}
}
if page.NextCursor == "" {
break
}
request.Cursor = page.NextCursor
if page.Page > 0 {
request.Page = page.Page
}
}
if len(matches) > 1 {
return "", false, fmt.Errorf("cloudflare: DNS-01 recovery matched %d records for job %s", len(matches), jobID)
}
if len(matches) == 0 {
return "", false, nil
}
return matches[0], true, nil
}
func commentContainsJob(comment, jobID string) bool {
want := "job=" + strings.TrimSpace(jobID)
if want == "job=" {
return false
}
for _, field := range strings.Fields(comment) {
if field == want {
return true
}
}
return false
}
func makeRecordPayload(record domain.DNSRecord) (map[string]any, error) {
if record.Managed {
return nil, &ValidationError{Field: "record.managed", Message: "Cloudflare-managed records are read-only"}
}
recordType := domain.RecordType(strings.ToUpper(string(record.Type)))
if !recordType.Editable() {
return nil, fmt.Errorf("%w: %s", ErrUnsupportedRecordType, recordType)
}
name, err := toASCIIName(record.Name)
if err != nil {
return nil, err
}
if record.TTL < 0 {
return nil, &ValidationError{Field: "record.ttl", Message: "TTL cannot be negative"}
}
ttl := record.TTL
if ttl == 0 {
ttl = 1
}
payload := map[string]any{
"type": string(recordType),
"name": name,
"ttl": ttl,
"comment": record.Comment,
"tags": append([]string(nil), record.Tags...),
}
structured := recordType == domain.RecordCAA || recordType == domain.RecordSRV
hasData := len(record.Data) > 0 && string(record.Data) != "null"
if !structured || !hasData {
payload["content"] = record.Content
}
if record.Priority != nil {
payload["priority"] = *record.Priority
}
if structured && hasData {
if !json.Valid(record.Data) {
return nil, &ValidationError{Field: "record.data", Message: "must contain valid JSON"}
}
payload["data"] = cloneRaw(record.Data)
}
if recordType == domain.RecordA || recordType == domain.RecordAAAA || recordType == domain.RecordCNAME {
payload["proxied"] = record.Proxied
}
if settings := rawRecordField(record.Raw, "settings"); len(settings) > 0 && string(settings) != "null" {
payload["settings"] = settings
}
return payload, nil
}
func rawRecordField(raw json.RawMessage, field string) json.RawMessage {
if len(raw) == 0 {
return nil
}
var values map[string]json.RawMessage
if json.Unmarshal(raw, &values) != nil {
return nil
}
return cloneRaw(values[field])
}
func mutationRecordID(mutation domain.DNSMutation) string {
if mutation.RecordID != "" {
return mutation.RecordID
}
for _, record := range []*domain.DNSRecord{mutation.After, mutation.Before} {
if record == nil {
continue
}
if record.ProviderID != "" {
return record.ProviderID
}
if record.ID != "" {
return record.ID
}
}
return ""
}
func mutationError(index int, message string) error {
return &ValidationError{Field: fmt.Sprintf("mutations[%d]", index), Message: message}
}
func (c *Client) mapRecordArray(raw json.RawMessage, zoneID string) ([]domain.DNSRecord, error) {
var wires []json.RawMessage
if err := json.Unmarshal(raw, &wires); err != nil {
return nil, &ResponseError{Resource: "DNS records", Err: err}
}
return c.mapRecordWires(wires, zoneID)
}
func (c *Client) mapRecordWires(wires []json.RawMessage, zoneID string) ([]domain.DNSRecord, error) {
syncedAt := c.now().UTC()
records := make([]domain.DNSRecord, 0, len(wires))
for _, wire := range wires {
record, err := mapRecord(wire, zoneID, syncedAt)
if err != nil {
return nil, err
}
records = append(records, record)
}
return records, nil
}
+305
View File
@@ -0,0 +1,305 @@
package cloudflare
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"strings"
"sync"
"testing"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
func TestListDNSRecordsPreservesUnknownFields(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/client/v4/zones/zone-1/dns_records" || r.Method != http.MethodGet {
http.NotFound(w, r)
return
}
if got := r.URL.Query().Get("search"); got != "api" {
t.Errorf("search = %q", got)
}
writeResult(t, w, []any{
map[string]any{
"id": "record-a", "type": "A", "name": "api.example.com", "content": "192.0.2.10",
"ttl": 300, "proxied": true, "proxiable": true, "priority": 10,
"comment": "primary", "tags": []string{"owner:ops"},
"modified_on": "2026-07-01T12:00:00Z",
},
map[string]any{
"id": "record-new", "type": "HTTPS", "name": "example.com", "content": ". alpn=h2",
"ttl": 1, "locked": true,
"meta": map[string]any{"managed_by_apps": true},
"data": map[string]any{"priority": 1, "target": "."},
"provider_new_field": map[string]any{"future": true},
},
}, map[string]any{"page": 1, "per_page": 2, "total_pages": 2})
})
page, err := client.ListDNSRecords(context.Background(), testAuth(), "zone-1", provider.PageRequest{PerPage: 2, Search: "api"})
if err != nil {
t.Fatalf("ListDNSRecords: %v", err)
}
if page.NextCursor != "2" || len(page.Records) != 2 {
t.Fatalf("page = %+v", page)
}
first := page.Records[0]
if first.ProviderID != "record-a" || first.Priority == nil || *first.Priority != 10 || !first.Proxied || !first.Proxiable {
t.Errorf("first record = %+v", first)
}
unknown := page.Records[1]
if unknown.Type != domain.RecordType("HTTPS") || unknown.Type.Editable() || !unknown.Managed {
t.Errorf("unknown record = %+v", unknown)
}
if !strings.Contains(string(unknown.Raw), "provider_new_field") || !strings.Contains(string(unknown.Data), "target") {
t.Errorf("raw/data not preserved: raw=%s data=%s", unknown.Raw, unknown.Data)
}
if unknown.LastSyncedAt == nil || !unknown.LastSyncedAt.Equal(fixedNow) {
t.Errorf("sync time = %v", unknown.LastSyncedAt)
}
}
func TestDNSRecordCRUDAndPayloadMapping(t *testing.T) {
t.Parallel()
var mu sync.Mutex
methods := make([]string, 0, 4)
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
methods = append(methods, r.Method+" "+r.URL.Path)
mu.Unlock()
switch {
case r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records/record-1":
writeResult(t, w, map[string]any{"id": "record-1", "type": "A", "name": "www.example.com", "content": "192.0.2.1", "ttl": 1}, nil)
case r.Method == http.MethodPost && r.URL.Path == "/client/v4/zones/zone-1/dns_records":
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode create: %v", err)
}
if body["name"] != "xn--bcher-kva.example" || body["type"] != "A" || body["ttl"] != float64(1) || body["proxied"] != true {
t.Errorf("create body = %#v", body)
}
writeResult(t, w, map[string]any{"id": "record-2", "type": "A", "name": body["name"], "content": body["content"], "ttl": 1, "proxied": true, "proxiable": true}, nil)
case r.Method == http.MethodPatch && r.URL.Path == "/client/v4/zones/zone-1/dns_records/record-2":
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode patch: %v", err)
}
if body["content"] != "192.0.2.22" || body["proxied"] != false || body["comment"] != "updated" {
t.Errorf("patch body = %#v", body)
}
writeResult(t, w, map[string]any{"id": "record-2", "type": "A", "name": body["name"], "content": body["content"], "ttl": 300, "proxied": false, "comment": "updated"}, nil)
case r.Method == http.MethodDelete && r.URL.Path == "/client/v4/zones/zone-1/dns_records/record-2":
writeResult(t, w, map[string]any{"id": "record-2"}, nil)
default:
http.NotFound(w, r)
}
})
got, err := client.GetDNSRecord(context.Background(), testAuth(), "zone-1", "record-1")
if err != nil || got.Content != "192.0.2.1" {
t.Fatalf("GetDNSRecord = %+v, %v", got, err)
}
created, err := client.CreateDNSRecord(context.Background(), testAuth(), "zone-1", domain.DNSRecord{
Type: domain.RecordA, Name: "bücher.example", Content: "192.0.2.2", Proxied: true,
})
if err != nil || created.ProviderID != "record-2" || created.UnicodeName != "bücher.example" {
t.Fatalf("CreateDNSRecord = %+v, %v", created, err)
}
patched, err := client.PatchDNSRecord(context.Background(), testAuth(), "zone-1", "record-2", domain.DNSRecord{
Type: domain.RecordA, Name: "xn--bcher-kva.example", Content: "192.0.2.22", TTL: 300, Comment: "updated",
})
if err != nil || patched.Content != "192.0.2.22" || patched.Proxied {
t.Fatalf("PatchDNSRecord = %+v, %v", patched, err)
}
if err := client.DeleteDNSRecord(context.Background(), testAuth(), "zone-1", "record-2"); err != nil {
t.Fatalf("DeleteDNSRecord: %v", err)
}
mu.Lock()
defer mu.Unlock()
if len(methods) != 4 {
t.Errorf("methods = %v", methods)
}
}
func TestDNSBatchUsesCloudflareOperationBuckets(t *testing.T) {
t.Parallel()
priority := uint16(20)
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/client/v4/zones/zone-1/dns_records/batch" {
http.NotFound(w, r)
return
}
var body struct {
Deletes []map[string]any `json:"deletes"`
Patches []map[string]any `json:"patches"`
Puts []map[string]any `json:"puts"`
Posts []map[string]any `json:"posts"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("decode batch: %v", err)
}
if len(body.Deletes) != 1 || body.Deletes[0]["id"] != "delete-id" ||
len(body.Patches) != 1 || body.Patches[0]["id"] != "patch-id" ||
len(body.Puts) != 1 || body.Puts[0]["id"] != "put-id" || len(body.Posts) != 1 {
t.Errorf("batch body = %#v", body)
}
writeResult(t, w, map[string]any{
"deletes": []any{map[string]any{"id": "delete-id"}},
"patches": []any{map[string]any{"id": "patch-id", "type": "A", "name": "patch.example.com", "content": "192.0.2.20", "ttl": 60}},
"puts": []any{map[string]any{"id": "put-id", "type": "MX", "name": "example.com", "content": "mail.example.com", "priority": 20, "ttl": 300}},
"posts": []any{map[string]any{"id": "post-id", "type": "TXT", "name": "new.example.com", "content": "hello", "ttl": 60}},
}, nil)
})
mutations := []domain.DNSMutation{
{Kind: domain.MutationCreate, After: &domain.DNSRecord{Type: domain.RecordTXT, Name: "new.example.com", Content: "hello", TTL: 60}},
{Kind: domain.MutationDelete, RecordID: "delete-id"},
{Kind: domain.MutationReplace, RecordID: "put-id", After: &domain.DNSRecord{Type: domain.RecordMX, Name: "example.com", Content: "mail.example.com", Priority: &priority, TTL: 300}},
{Kind: domain.MutationPatch, RecordID: "patch-id", After: &domain.DNSRecord{Type: domain.RecordA, Name: "patch.example.com", Content: "192.0.2.20", TTL: 60}},
}
records, err := client.ApplyDNSBatch(context.Background(), testAuth(), "zone-1", mutations)
if err != nil {
t.Fatalf("ApplyDNSBatch: %v", err)
}
if len(records) != 4 {
t.Fatalf("records = %+v", records)
}
got := []string{records[0].ID, records[1].ID, records[2].ID, records[3].ID}
want := []string{"delete-id", "patch-id", "put-id", "post-id"}
for i := range want {
if got[i] != want[i] {
t.Errorf("result order = %v, want %v", got, want)
break
}
}
}
func TestDNS01CleanupDeletesOnlyReturnedRecordID(t *testing.T) {
t.Parallel()
var calls []string
var mu sync.Mutex
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
calls = append(calls, r.Method+" "+r.URL.Path)
mu.Unlock()
switch {
case r.Method == http.MethodPost && r.URL.Path == "/client/v4/zones/zone-1/dns_records":
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("decode challenge: %v", err)
}
if body["type"] != "TXT" || body["name"] != "_acme-challenge.example.com" || body["content"] != "challenge-value" {
t.Errorf("challenge body = %#v", body)
}
if !strings.Contains(body["comment"].(string), "job-42") {
t.Errorf("challenge comment = %q", body["comment"])
}
writeResult(t, w, map[string]any{
"id": "exact-created-id", "type": "TXT", "name": body["name"], "content": body["content"], "ttl": 60,
}, nil)
case r.Method == http.MethodDelete && r.URL.Path == "/client/v4/zones/zone-1/dns_records/exact-created-id":
writeResult(t, w, map[string]any{"id": "exact-created-id"}, nil)
default:
http.NotFound(w, r)
}
})
recordID, err := client.PresentDNS01(context.Background(), testAuth(), "zone-1", "_acme-challenge.example.com.", "challenge-value", "job-42")
if err != nil || recordID != "exact-created-id" {
t.Fatalf("PresentDNS01 = %q, %v", recordID, err)
}
if err := client.CleanupDNS01(context.Background(), testAuth(), "zone-1", recordID); err != nil {
t.Fatalf("CleanupDNS01: %v", err)
}
mu.Lock()
defer mu.Unlock()
if len(calls) != 2 || strings.Contains(strings.Join(calls, " "), "GET") {
t.Errorf("challenge calls = %v", calls)
}
}
func TestDNS01RecoveryMatchesJobAndValueAndCleanupIsIdempotent(t *testing.T) {
t.Parallel()
value := "challenge-value"
digest := sha256.Sum256([]byte(value))
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records":
if r.URL.Query().Get("search") != "_acme-challenge.example.com" {
t.Errorf("recovery search = %q", r.URL.Query().Get("search"))
}
writeResult(t, w, []any{
map[string]any{"id": "other", "type": "TXT", "name": "_acme-challenge.example.com", "content": value, "comment": "DomainOps ACME DNS-01 job=another"},
map[string]any{"id": "recovered", "type": "TXT", "name": "_acme-challenge.example.com", "content": value, "comment": "DomainOps ACME DNS-01 job=job-42"},
}, map[string]any{"page": 1, "total_pages": 1})
case r.Method == http.MethodDelete && r.URL.Path == "/client/v4/zones/zone-1/dns_records/recovered":
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "errors": []any{map[string]any{"code": 81044, "message": "record does not exist"}}, "result": nil})
default:
http.NotFound(w, r)
}
})
recordID, found, err := client.ReconcileDNS01(context.Background(), testAuth(), "zone-1", "_acme-challenge.example.com.", hex.EncodeToString(digest[:]), "job-42")
if err != nil || !found || recordID != "recovered" {
t.Fatalf("ReconcileDNS01 = %q, %v, %v", recordID, found, err)
}
if err := client.CleanupDNS01(context.Background(), testAuth(), "zone-1", recordID); err != nil {
t.Fatalf("idempotent cleanup: %v", err)
}
}
func TestRejectsReadOnlyRecordsBeforeNetwork(t *testing.T) {
t.Parallel()
var called bool
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
http.Error(w, "unexpected", http.StatusInternalServerError)
})
_, err := client.CreateDNSRecord(context.Background(), testAuth(), "zone", domain.DNSRecord{Type: domain.RecordType("HTTPS"), Name: "example.com"})
if !errors.Is(err, ErrUnsupportedRecordType) {
t.Errorf("unknown type error = %v", err)
}
_, err = client.PatchDNSRecord(context.Background(), testAuth(), "zone", "record", domain.DNSRecord{Type: domain.RecordA, Name: "example.com", Managed: true})
var validation *ValidationError
if !errors.As(err, &validation) {
t.Errorf("managed record error = %v", err)
}
if called {
t.Error("read-only validation contacted Cloudflare")
}
}
func TestStructuredRecordPayloadSelection(t *testing.T) {
t.Parallel()
caaData := json.RawMessage(`{"flags":0,"tag":"issue","value":"letsencrypt.org"}`)
payload, err := makeRecordPayload(domain.DNSRecord{Type: domain.RecordCAA, Name: "example.com", Content: "ignored", Data: caaData})
if err != nil {
t.Fatal(err)
}
if _, ok := payload["content"]; ok || payload["data"] == nil {
t.Fatalf("structured CAA payload = %#v", payload)
}
payload, err = makeRecordPayload(domain.DNSRecord{Type: domain.RecordCAA, Name: "example.com", Content: `0 issue "letsencrypt.org"`, Data: json.RawMessage("null")})
if err != nil {
t.Fatal(err)
}
if payload["content"] == nil || payload["data"] != nil {
t.Fatalf("CAA content fallback payload = %#v", payload)
}
payload, err = makeRecordPayload(domain.DNSRecord{Type: domain.RecordA, Name: "example.com", Content: "192.0.2.1", Data: caaData})
if err != nil {
t.Fatal(err)
}
if payload["content"] != "192.0.2.1" || payload["data"] != nil {
t.Fatalf("unstructured A payload = %#v", payload)
}
}
+224
View File
@@ -0,0 +1,224 @@
package cloudflare
import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
var (
ErrUnauthorized = errors.New("cloudflare: unauthorized")
ErrForbidden = errors.New("cloudflare: forbidden")
ErrNotFound = errors.New("cloudflare: resource not found")
ErrConflict = errors.New("cloudflare: conflict")
ErrRateLimited = errors.New("cloudflare: rate limited")
ErrUnsupportedRecordType = errors.New("cloudflare: unsupported writable DNS record type")
)
// ValidationError reports an invalid local request without contacting
// Cloudflare. It intentionally never includes secret material.
type ValidationError struct {
Field string
Message string
}
// ResponseError reports a successful HTTP response whose Cloudflare envelope
// or result does not match the documented schema. It usually indicates an
// upstream API change and leaves a mutation's outcome ambiguous.
type ResponseError struct {
Resource string
Err error
}
func (e *ResponseError) Error() string {
return fmt.Sprintf("cloudflare: decode %s response: %v", e.Resource, e.Err)
}
func (e *ResponseError) Unwrap() error { return e.Err }
func (e *ValidationError) Error() string {
if e.Field == "" {
return "cloudflare: " + e.Message
}
return fmt.Sprintf("cloudflare: invalid %s: %s", e.Field, e.Message)
}
func (e *ValidationError) MutationOutcomeDefinitive() bool { return true }
func (e *ValidationError) MutationNotAttempted() bool { return true }
func (e *ValidationError) CredentialVerificationAuthoritative() bool {
return true
}
// ErrorDetail is one structured error returned by the Cloudflare API.
type ErrorDetail struct {
Code int
Message string
Pointer string
DocumentationURL string
}
// APIError is a redacted, structured Cloudflare API failure.
type APIError struct {
Method string
Path string
StatusCode int
Code int
Message string
Details []ErrorDetail
RequestID string
}
func (e *APIError) Error() string {
message := strings.TrimSpace(e.Message)
if message == "" {
message = http.StatusText(e.StatusCode)
}
if e.Code != 0 {
return fmt.Sprintf("cloudflare API %s %s failed (%d, code %d): %s", e.Method, e.Path, e.StatusCode, e.Code, message)
}
return fmt.Sprintf("cloudflare API %s %s failed (%d): %s", e.Method, e.Path, e.StatusCode, message)
}
func (e *APIError) Is(target error) bool {
switch target {
case ErrUnauthorized:
return e.StatusCode == http.StatusUnauthorized
case ErrForbidden:
return e.StatusCode == http.StatusForbidden
case ErrNotFound:
return e.StatusCode == http.StatusNotFound
case ErrConflict:
return e.StatusCode == http.StatusConflict
default:
return false
}
}
// MutationOutcomeDefinitive distinguishes a provider rejection from a lost or
// ambiguous response. APIError is also returned for a successful HTTP response
// whose Cloudflare envelope explicitly reports success:false. Server errors can
// occur after processing began and remain ambiguous.
func (e *APIError) MutationOutcomeDefinitive() bool {
return e.StatusCode > 0 && e.StatusCode < http.StatusInternalServerError
}
// CredentialVerificationAuthoritative only classifies authentication and
// authorization rejections. In particular, 429 and 5xx responses must leave a
// previously valid credential valid, because they describe provider health or
// throttling rather than the token's state.
func (e *APIError) CredentialVerificationAuthoritative() bool {
return e.StatusCode == http.StatusUnauthorized || e.StatusCode == http.StatusForbidden
}
func (e *APIError) AccessDenialAuthoritative() bool {
return e.StatusCode == http.StatusUnauthorized || e.StatusCode == http.StatusForbidden
}
type mutationNotAttemptedError struct{ err error }
func (e *mutationNotAttemptedError) Error() string { return e.err.Error() }
func (e *mutationNotAttemptedError) Unwrap() error { return e.err }
func (e *mutationNotAttemptedError) MutationNotAttempted() bool { return true }
func markMutationNotAttempted(err error) error {
if err == nil {
return nil
}
return &mutationNotAttemptedError{err: err}
}
// RateLimitError includes Cloudflare's requested retry time where available.
type RateLimitError struct {
APIError *APIError
RetryAfter time.Duration
RetryAt time.Time
}
func (e *RateLimitError) Error() string {
if e.RetryAfter > 0 {
return fmt.Sprintf("%s; retry after %s", e.APIError.Error(), e.RetryAfter)
}
return e.APIError.Error()
}
func (e *RateLimitError) Unwrap() error { return e.APIError }
func (e *RateLimitError) Is(target error) bool {
return target == ErrRateLimited || errors.Is(e.APIError, target)
}
func newAPIError(method, path string, resp *http.Response, errorsList, messages []apiMessage) *APIError {
details := flattenMessages(errorsList)
if len(details) == 0 {
details = flattenMessages(messages)
}
result := &APIError{
Method: method,
Path: path,
StatusCode: resp.StatusCode,
RequestID: resp.Header.Get("CF-Ray"),
Details: details,
}
if len(details) > 0 {
result.Code = details[0].Code
result.Message = details[0].Message
}
return result
}
func flattenMessages(messages []apiMessage) []ErrorDetail {
var result []ErrorDetail
var appendMessage func(apiMessage)
appendMessage = func(message apiMessage) {
result = append(result, ErrorDetail{
Code: message.Code,
Message: message.Message,
Pointer: message.Source.Pointer,
DocumentationURL: message.DocumentationURL,
})
for _, child := range message.ErrorChain {
appendMessage(child)
}
}
for _, message := range messages {
appendMessage(message)
}
return result
}
func newRateLimitError(apiErr *APIError, header http.Header, now time.Time) *RateLimitError {
retryAt, retryAfter := parseRetryAfter(header.Get("Retry-After"), now)
if retryAfter == 0 {
if unix, err := strconv.ParseInt(header.Get("X-RateLimit-Reset"), 10, 64); err == nil && unix > 0 {
retryAt = time.Unix(unix, 0)
retryAfter = retryAt.Sub(now)
if retryAfter < 0 {
retryAfter = 0
}
}
}
return &RateLimitError{APIError: apiErr, RetryAfter: retryAfter, RetryAt: retryAt}
}
func parseRetryAfter(value string, now time.Time) (time.Time, time.Duration) {
value = strings.TrimSpace(value)
if value == "" {
return time.Time{}, 0
}
if seconds, err := strconv.ParseInt(value, 10, 64); err == nil && seconds >= 0 {
delay := time.Duration(seconds) * time.Second
return now.Add(delay), delay
}
when, err := http.ParseTime(value)
if err != nil {
return time.Time{}, 0
}
delay := when.Sub(now)
if delay < 0 {
delay = 0
}
return when, delay
}
+220
View File
@@ -0,0 +1,220 @@
package cloudflare
import (
"encoding/json"
"fmt"
"strings"
"time"
"unicode/utf8"
"github.com/MeghdadFadaee/domainops/internal/domain"
"golang.org/x/net/idna"
)
type accountWire struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedOn string `json:"created_on"`
}
func mapAccount(w accountWire) domain.RemoteAccount {
return domain.RemoteAccount{
ID: w.ID,
Provider: domain.ProviderCloudflare,
ProviderID: w.ID,
Name: w.Name,
CreatedAt: parseTimeValue(w.CreatedOn),
}
}
type zoneWire struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Paused bool `json:"paused"`
NameServers []string `json:"name_servers"`
ModifiedOn string `json:"modified_on"`
Account accountWire `json:"account"`
Plan struct {
Name string `json:"name"`
} `json:"plan"`
}
func mapZone(w zoneWire, credentialID string, syncedAt time.Time) domain.Zone {
modified := optionalTime(w.ModifiedOn)
synced := syncedAt
return domain.Zone{
ID: w.ID,
Provider: domain.ProviderCloudflare,
ProviderID: w.ID,
AccountID: w.Account.ID,
PreferredCredentialID: credentialID,
Name: w.Name,
UnicodeName: toUnicodeName(w.Name),
Status: mapZoneStatus(w.Status),
Paused: w.Paused,
Plan: w.Plan.Name,
NameServers: append([]string(nil), w.NameServers...),
ModifiedAt: modified,
LastSyncedAt: &synced,
}
}
func mapZoneStatus(status string) domain.ZoneStatus {
switch strings.ToLower(status) {
case string(domain.ZoneActive):
return domain.ZoneActive
case string(domain.ZonePending):
return domain.ZonePending
case string(domain.ZoneInitializing):
return domain.ZoneInitializing
case string(domain.ZoneMoved):
return domain.ZoneMoved
case string(domain.ZoneDeactivated):
return domain.ZoneDeactivated
default:
return domain.ZoneUnknown
}
}
type recordWire struct {
ID string `json:"id"`
Type string `json:"type"`
Name string `json:"name"`
Content string `json:"content"`
Priority json.Number `json:"priority"`
TTL int `json:"ttl"`
Proxied bool `json:"proxied"`
Proxiable bool `json:"proxiable"`
Comment string `json:"comment"`
Tags []string `json:"tags"`
Locked bool `json:"locked"`
Data json.RawMessage `json:"data"`
Meta json.RawMessage `json:"meta"`
ModifiedOn string `json:"modified_on"`
}
func mapRecord(raw json.RawMessage, zoneID string, syncedAt time.Time) (domain.DNSRecord, error) {
var w recordWire
decoder := json.NewDecoder(strings.NewReader(string(raw)))
decoder.UseNumber()
if err := decoder.Decode(&w); err != nil {
return domain.DNSRecord{}, fmt.Errorf("cloudflare: decode DNS record: %w", err)
}
priority := parsePriority(w.Priority)
modified := optionalTime(w.ModifiedOn)
synced := syncedAt
return domain.DNSRecord{
ID: w.ID,
ProviderID: w.ID,
ZoneID: zoneID,
Type: domain.RecordType(strings.ToUpper(w.Type)),
Name: w.Name,
UnicodeName: toUnicodeName(w.Name),
Content: w.Content,
Priority: priority,
TTL: w.TTL,
Proxied: w.Proxied,
Proxiable: w.Proxiable,
Comment: w.Comment,
Tags: append([]string(nil), w.Tags...),
Managed: w.Locked || metaManaged(w.Meta),
Data: cloneRaw(w.Data),
Raw: cloneRaw(raw),
ModifiedAt: modified,
LastSyncedAt: &synced,
}, nil
}
func parsePriority(number json.Number) *uint16 {
if number == "" {
return nil
}
value, err := number.Int64()
if err != nil || value < 0 || value > 65535 {
return nil
}
priority := uint16(value)
return &priority
}
func metaManaged(raw json.RawMessage) bool {
if len(raw) == 0 || string(raw) == "null" {
return false
}
var values map[string]any
if json.Unmarshal(raw, &values) != nil {
return false
}
for _, key := range []string{"auto_added", "managed_by_apps", "managed_by_argo_tunnel", "managed_by_tunnel"} {
if value, ok := values[key].(bool); ok && value {
return true
}
}
return false
}
func parseTimeValue(value string) time.Time {
parsed, _ := time.Parse(time.RFC3339Nano, value)
return parsed
}
func optionalTime(value string) *time.Time {
parsed := parseTimeValue(value)
if parsed.IsZero() {
return nil
}
return &parsed
}
func toASCIIName(name string) (string, error) {
name = strings.TrimSpace(strings.TrimSuffix(name, "."))
if name == "" {
return "", &ValidationError{Field: "record.name", Message: "name is required"}
}
if isASCII(name) {
return strings.ToLower(name), nil
}
labels := strings.Split(name, ".")
for i, label := range labels {
if label == "" || label == "*" || strings.HasPrefix(label, "_") {
continue
}
encoded, err := idna.Lookup.ToASCII(label)
if err != nil {
return "", &ValidationError{Field: "record.name", Message: err.Error()}
}
labels[i] = encoded
}
return strings.ToLower(strings.Join(labels, ".")), nil
}
func toUnicodeName(name string) string {
if !strings.Contains(strings.ToLower(name), "xn--") {
return ""
}
labels := strings.Split(name, ".")
changed := false
for i, label := range labels {
decoded, err := idna.Lookup.ToUnicode(label)
if err == nil && decoded != label {
labels[i] = decoded
changed = true
}
}
if !changed {
return ""
}
return strings.Join(labels, ".")
}
func isASCII(value string) bool {
for len(value) > 0 {
r, size := utf8.DecodeRuneInString(value)
if r > 127 {
return false
}
value = value[size:]
}
return true
}
+324
View File
@@ -0,0 +1,324 @@
package cloudflare
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
const (
settingSSL = "ssl"
settingAlwaysHTTPS = "always_use_https"
settingMinimumTLS = "min_tls_version"
settingTLS13 = "tls_1_3"
)
type zoneSettingWire struct {
ID string `json:"id"`
Value json.RawMessage `json:"value"`
Editable bool `json:"editable"`
}
// GetEdgeTLSSettings reads the four intentionally supported Cloudflare zone
// controls and independently determines whether the zone has proxied DNS.
func (c *Client) GetEdgeTLSSettings(ctx context.Context, auth provider.Auth, zoneID string) (domain.EdgeTLSSettings, error) {
mode, err := c.getZoneSetting(ctx, auth, zoneID, settingSSL)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: read SSL mode: %w", err)
}
alwaysHTTPS, err := c.getZoneSetting(ctx, auth, zoneID, settingAlwaysHTTPS)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: read Always Use HTTPS: %w", err)
}
minimumTLS, err := c.getZoneSetting(ctx, auth, zoneID, settingMinimumTLS)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: read minimum TLS: %w", err)
}
tls13, err := c.getZoneSetting(ctx, auth, zoneID, settingTLS13)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: read TLS 1.3: %w", err)
}
hasProxiedDNS, err := c.hasProxiedDNS(ctx, auth, zoneID)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: inspect proxied DNS: %w", err)
}
syncedAt := c.now().UTC()
return domain.EdgeTLSSettings{
ZoneID: zoneID,
Mode: settingString(mode),
AlwaysUseHTTPS: settingEnabled(alwaysHTTPS),
MinimumTLS: settingString(minimumTLS),
TLS13: settingEnabled(tls13),
HasProxiedDNS: hasProxiedDNS,
LastSyncedAt: &syncedAt,
}, nil
}
// UpdateEdgeTLSSettings applies the complete provider-neutral settings model.
// Cloudflare exposes these as separate endpoints, so the current exact values
// are read first and only changed settings are patched. A failure names the
// setting that did not apply; callers can immediately refresh to reconcile
// partial state.
func (c *Client) UpdateEdgeTLSSettings(ctx context.Context, auth provider.Auth, zoneID string, baseline, settings domain.EdgeTLSSettings) (domain.EdgeTLSSettings, error) {
mode := strings.ToLower(strings.TrimSpace(settings.Mode))
if !oneOf(mode, "off", "flexible", "full", "strict", "origin_pull") {
return domain.EdgeTLSSettings{}, &ValidationError{Field: "tls.mode", Message: "must be off, flexible, full, strict, or origin_pull"}
}
minimumTLS := strings.TrimSpace(settings.MinimumTLS)
if !oneOf(minimumTLS, "1.0", "1.1", "1.2", "1.3") {
return domain.EdgeTLSSettings{}, &ValidationError{Field: "tls.minimum_tls", Message: "must be 1.0, 1.1, 1.2, or 1.3"}
}
desired := []struct {
id string
baselineValue string
value string
changed bool
}{
{id: settingSSL, baselineValue: strings.ToLower(strings.TrimSpace(baseline.Mode)), value: mode, changed: !strings.EqualFold(strings.TrimSpace(baseline.Mode), mode)},
{id: settingAlwaysHTTPS, baselineValue: onOff(baseline.AlwaysUseHTTPS), value: onOff(settings.AlwaysUseHTTPS), changed: baseline.AlwaysUseHTTPS != settings.AlwaysUseHTTPS},
{id: settingMinimumTLS, baselineValue: strings.TrimSpace(baseline.MinimumTLS), value: minimumTLS, changed: strings.TrimSpace(baseline.MinimumTLS) != minimumTLS},
{id: settingTLS13, baselineValue: onOff(baseline.TLS13), value: onOff(settings.TLS13), changed: baseline.TLS13 != settings.TLS13},
}
effective := make(map[string]zoneSettingWire, len(desired))
for _, setting := range desired {
current, err := c.getZoneSetting(ctx, auth, zoneID, setting.id)
if err != nil {
return domain.EdgeTLSSettings{}, markMutationNotAttempted(fmt.Errorf("cloudflare: read zone setting %s before update: %w", setting.id, err))
}
effective[setting.id] = current
}
// Validate every requested field against the caller's displayed baseline
// before applying the first patch. Unrelated concurrent provider changes are
// preserved; a concurrent change to a requested field fails closed.
for _, update := range desired {
if !update.changed {
continue
}
if !edgeTLSSettingMatches(update.id, effective[update.id], baseline, update.baselineValue) {
return domain.EdgeTLSSettings{}, &ValidationError{
Field: "tls." + update.id,
Message: "changed remotely; refresh before retrying",
}
}
}
for _, update := range desired {
if !update.changed {
continue
}
updated, err := c.patchZoneSetting(ctx, auth, zoneID, update.id, update.value)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: update zone setting %s: %w", update.id, err)
}
effective[update.id] = updated
}
hasProxiedDNS, err := c.hasProxiedDNS(ctx, auth, zoneID)
if err != nil {
return domain.EdgeTLSSettings{}, fmt.Errorf("cloudflare: inspect proxied DNS after update: %w", err)
}
syncedAt := c.now().UTC()
return domain.EdgeTLSSettings{
ZoneID: zoneID,
Mode: settingString(effective[settingSSL]),
AlwaysUseHTTPS: settingEnabled(effective[settingAlwaysHTTPS]),
MinimumTLS: settingString(effective[settingMinimumTLS]),
TLS13: settingEnabled(effective[settingTLS13]),
HasProxiedDNS: hasProxiedDNS,
LastSyncedAt: &syncedAt,
}, nil
}
func edgeTLSSettingMatches(settingID string, current zoneSettingWire, desired domain.EdgeTLSSettings, desiredValue string) bool {
if settingID == settingTLS13 {
// TLS 1.3's provider-neutral model intentionally collapses Cloudflare's
// "on" and "zrt" modes. Preserve either enabled mode when the caller
// continues to request TLS 1.3 instead of silently disabling 0-RTT.
currentValue := strings.ToLower(strings.TrimSpace(settingString(current)))
if desired.TLS13 {
return currentValue == "on" || currentValue == "zrt"
}
return currentValue == "off"
}
return strings.EqualFold(strings.TrimSpace(settingString(current)), strings.TrimSpace(desiredValue))
}
func (c *Client) getZoneSetting(ctx context.Context, auth provider.Auth, zoneID, settingID string) (zoneSettingWire, error) {
path, err := apiPath("zones", zoneID, "settings", settingID)
if err != nil {
return zoneSettingWire{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodGet, path, nil, nil)
if err != nil {
return zoneSettingWire{}, err
}
var setting zoneSettingWire
if err := json.Unmarshal(raw, &setting); err != nil {
return zoneSettingWire{}, &ResponseError{Resource: "zone setting " + settingID, Err: err}
}
return setting, nil
}
func (c *Client) patchZoneSetting(ctx context.Context, auth provider.Auth, zoneID, settingID, value string) (zoneSettingWire, error) {
path, err := apiPath("zones", zoneID, "settings", settingID)
if err != nil {
return zoneSettingWire{}, err
}
raw, _, err := c.do(ctx, auth, http.MethodPatch, path, nil, map[string]string{"value": value})
if err != nil {
return zoneSettingWire{}, err
}
var setting zoneSettingWire
if err := json.Unmarshal(raw, &setting); err != nil {
return zoneSettingWire{}, &ResponseError{Resource: "zone setting " + settingID, Err: err}
}
return setting, nil
}
func (c *Client) hasProxiedDNS(ctx context.Context, auth provider.Auth, zoneID string) (bool, error) {
path, err := apiPath("zones", zoneID, "dns_records")
if err != nil {
return false, err
}
query := url.Values{"page": {"1"}, "per_page": {"1"}, "proxied": {"true"}}
raw, _, err := c.do(ctx, auth, http.MethodGet, path, query, nil)
if err != nil {
return false, err
}
var records []json.RawMessage
if err := json.Unmarshal(raw, &records); err != nil {
return false, &ResponseError{Resource: "proxied DNS records", Err: err}
}
return len(records) > 0, nil
}
func settingString(setting zoneSettingWire) string {
var value string
_ = json.Unmarshal(setting.Value, &value)
return value
}
func settingEnabled(setting zoneSettingWire) bool {
switch strings.ToLower(settingString(setting)) {
case "on", "true", "zrt":
return true
default:
return false
}
}
func oneOf(value string, allowed ...string) bool {
for _, candidate := range allowed {
if value == candidate {
return true
}
}
return false
}
func onOff(enabled bool) string {
if enabled {
return "on"
}
return "off"
}
type certificatePackWire struct {
ID string `json:"id"`
Type string `json:"type"`
Status string `json:"status"`
Hosts []string `json:"hosts"`
ExpiresOn string `json:"expires_on"`
Certificates []struct {
ID string `json:"id"`
Status string `json:"status"`
Hosts []string `json:"hosts"`
ExpiresOn string `json:"expires_on"`
} `json:"certificates"`
}
// ListEdgeCertificates inventories Cloudflare certificate packs. Expiry is the
// earliest certificate expiry in a pack, which is the conservative operational
// value for dashboard warnings.
func (c *Client) ListEdgeCertificates(ctx context.Context, auth provider.Auth, zoneID string, request provider.PageRequest) ([]domain.EdgeCertificate, error) {
path, err := apiPath("zones", zoneID, "ssl", "certificate_packs")
if err != nil {
return nil, err
}
query, _ := paginationQuery(request, 50, 50)
query.Set("status", "all")
raw, _, err := c.do(ctx, auth, http.MethodGet, path, query, nil)
if err != nil {
return nil, err
}
var wires []certificatePackWire
if err := json.Unmarshal(raw, &wires); err != nil {
return nil, &ResponseError{Resource: "edge certificates", Err: err}
}
search := strings.ToLower(strings.TrimSpace(request.Search))
certificates := make([]domain.EdgeCertificate, 0, len(wires))
for _, wire := range wires {
certificate := mapCertificatePack(wire, zoneID)
if search != "" && !certificateMatches(certificate, search) {
continue
}
certificates = append(certificates, certificate)
}
return certificates, nil
}
func mapCertificatePack(wire certificatePackWire, zoneID string) domain.EdgeCertificate {
hosts := append([]string(nil), wire.Hosts...)
seenHosts := make(map[string]struct{}, len(hosts))
for _, host := range hosts {
seenHosts[host] = struct{}{}
}
var expiry *time.Time
considerExpiry := func(value string) {
candidate := optionalTime(value)
if candidate != nil && (expiry == nil || candidate.Before(*expiry)) {
expiry = candidate
}
}
considerExpiry(wire.ExpiresOn)
for _, child := range wire.Certificates {
considerExpiry(child.ExpiresOn)
for _, host := range child.Hosts {
if _, exists := seenHosts[host]; exists {
continue
}
seenHosts[host] = struct{}{}
hosts = append(hosts, host)
}
}
return domain.EdgeCertificate{
ID: wire.ID,
ZoneID: zoneID,
Type: wire.Type,
Status: wire.Status,
Hosts: hosts,
ExpiresAt: expiry,
}
}
func certificateMatches(certificate domain.EdgeCertificate, search string) bool {
if strings.Contains(strings.ToLower(certificate.ID), search) ||
strings.Contains(strings.ToLower(certificate.Type), search) ||
strings.Contains(strings.ToLower(certificate.Status), search) {
return true
}
for _, host := range certificate.Hosts {
if strings.Contains(strings.ToLower(host), search) {
return true
}
}
return false
}
+364
View File
@@ -0,0 +1,364 @@
package cloudflare
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
func TestUpdateEdgeTLSSettingsMarksPreflightReadFailureNotAttempted(t *testing.T) {
t.Parallel()
var patches atomic.Int32
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPatch {
patches.Add(1)
}
http.Error(w, "temporary provider failure", http.StatusBadGateway)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true}
desired := baseline
desired.Mode = "full"
_, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, desired)
if err == nil {
t.Fatal("preflight read failure unexpectedly succeeded")
}
var marker interface{ MutationNotAttempted() bool }
if !errors.As(err, &marker) || !marker.MutationNotAttempted() {
t.Fatalf("preflight error lacks MutationNotAttempted marker: %T %v", err, err)
}
if patches.Load() != 0 {
t.Fatalf("patch count = %d, want 0", patches.Load())
}
}
func TestGetEdgeTLSSettings(t *testing.T) {
t.Parallel()
values := map[string]string{
"ssl": "strict",
"always_use_https": "on",
"min_tls_version": "1.2",
"tls_1_3": "zrt",
}
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
value, ok := values[id]
if !ok {
http.NotFound(w, r)
return
}
writeResult(t, w, map[string]any{"id": id, "value": value, "editable": true}, nil)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
if r.URL.Query().Get("proxied") != "true" || r.URL.Query().Get("per_page") != "1" {
t.Errorf("proxied query = %v", r.URL.Query())
}
writeResult(t, w, []any{map[string]any{"id": "proxied-record"}}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
settings, err := client.GetEdgeTLSSettings(context.Background(), testAuth(), "zone-1")
if err != nil {
t.Fatalf("GetEdgeTLSSettings: %v", err)
}
if settings.Mode != "strict" || !settings.AlwaysUseHTTPS || settings.MinimumTLS != "1.2" || !settings.TLS13 || !settings.HasProxiedDNS {
t.Errorf("settings = %+v", settings)
}
if settings.LastSyncedAt == nil || !settings.LastSyncedAt.Equal(fixedNow) {
t.Errorf("sync time = %v", settings.LastSyncedAt)
}
}
func TestUpdateEdgeTLSSettings(t *testing.T) {
t.Parallel()
var mu sync.Mutex
updated := make(map[string]string)
current := map[string]string{
"ssl": "flexible",
"always_use_https": "off",
"min_tls_version": "1.2",
"tls_1_3": "on",
}
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
value, ok := current[id]
if !ok {
http.NotFound(w, r)
return
}
writeResult(t, w, map[string]any{"id": id, "value": value, "editable": true}, nil)
return
}
if r.Method == http.MethodPatch && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
var body map[string]string
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode setting: %v", err)
}
mu.Lock()
updated[id] = body["value"]
current[id] = body["value"]
mu.Unlock()
writeResult(t, w, map[string]any{"id": id, "value": body["value"], "editable": true}, nil)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
writeResult(t, w, []any{}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "flexible", AlwaysUseHTTPS: false, MinimumTLS: "1.2", TLS13: true}
settings, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, domain.EdgeTLSSettings{
Mode: "full", AlwaysUseHTTPS: true, MinimumTLS: "1.3", TLS13: false,
})
if err != nil {
t.Fatalf("UpdateEdgeTLSSettings: %v", err)
}
if settings.Mode != "full" || !settings.AlwaysUseHTTPS || settings.MinimumTLS != "1.3" || settings.TLS13 || settings.HasProxiedDNS {
t.Errorf("effective settings = %+v", settings)
}
mu.Lock()
defer mu.Unlock()
want := map[string]string{
"ssl": "full", "always_use_https": "on", "min_tls_version": "1.3", "tls_1_3": "off",
}
for id, value := range want {
if updated[id] != value {
t.Errorf("updated[%s] = %q, want %q", id, updated[id], value)
}
}
}
func TestUpdateEdgeTLSSettingsNoOpPreservesZRT(t *testing.T) {
t.Parallel()
current := map[string]string{
"ssl": "strict",
"always_use_https": "on",
"min_tls_version": "1.2",
"tls_1_3": "zrt",
}
patches := 0
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
writeResult(t, w, map[string]any{"id": id, "value": current[id], "editable": true}, nil)
return
}
if r.Method == http.MethodPatch && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
patches++
http.Error(w, "unexpected patch", http.StatusInternalServerError)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
writeResult(t, w, []any{}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true}
settings, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, domain.EdgeTLSSettings{
Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true,
})
if err != nil {
t.Fatalf("UpdateEdgeTLSSettings: %v", err)
}
if patches != 0 {
t.Fatalf("patch count = %d, want 0", patches)
}
if settings.Mode != "strict" || !settings.AlwaysUseHTTPS || settings.MinimumTLS != "1.2" || !settings.TLS13 {
t.Errorf("effective settings = %+v", settings)
}
}
func TestUpdateEdgeTLSSettingsEnablesTLS13FromOff(t *testing.T) {
t.Parallel()
current := map[string]string{
"ssl": "strict",
"always_use_https": "on",
"min_tls_version": "1.2",
"tls_1_3": "off",
}
updated := make(map[string]string)
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
writeResult(t, w, map[string]any{"id": id, "value": current[id], "editable": true}, nil)
return
}
if r.Method == http.MethodPatch && len(r.URL.Path) > len(prefix) && r.URL.Path[:len(prefix)] == prefix {
id := r.URL.Path[len(prefix):]
var body map[string]string
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode setting: %v", err)
}
updated[id] = body["value"]
writeResult(t, w, map[string]any{"id": id, "value": body["value"], "editable": true}, nil)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
writeResult(t, w, []any{}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: false}
settings, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, domain.EdgeTLSSettings{
Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true,
})
if err != nil {
t.Fatalf("UpdateEdgeTLSSettings: %v", err)
}
if len(updated) != 1 || updated[settingTLS13] != "on" {
t.Fatalf("updated = %v, want only tls_1_3=on", updated)
}
if !settings.TLS13 {
t.Errorf("effective settings = %+v", settings)
}
}
func TestUpdateEdgeTLSSettingsPreservesUnrelatedConcurrentChange(t *testing.T) {
t.Parallel()
current := map[string]string{
"ssl": "strict", "always_use_https": "on", "min_tls_version": "1.2", "tls_1_3": "zrt",
}
updated := make(map[string]string)
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, prefix) {
id := strings.TrimPrefix(r.URL.Path, prefix)
writeResult(t, w, map[string]any{"id": id, "value": current[id], "editable": true}, nil)
return
}
if r.Method == http.MethodPatch && strings.HasPrefix(r.URL.Path, prefix) {
id := strings.TrimPrefix(r.URL.Path, prefix)
var body map[string]string
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
}
updated[id] = body["value"]
current[id] = body["value"]
writeResult(t, w, map[string]any{"id": id, "value": body["value"], "editable": true}, nil)
return
}
if r.Method == http.MethodGet && r.URL.Path == "/client/v4/zones/zone-1/dns_records" {
writeResult(t, w, []any{}, map[string]any{"page": 1})
return
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", AlwaysUseHTTPS: false, MinimumTLS: "1.2", TLS13: true}
desired := baseline
desired.Mode = "full"
settings, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, desired)
if err != nil {
t.Fatal(err)
}
if len(updated) != 1 || updated[settingSSL] != "full" {
t.Fatalf("patches = %#v, want only ssl=full", updated)
}
if !settings.AlwaysUseHTTPS || !settings.TLS13 {
t.Fatalf("unrelated concurrent state was clobbered: %#v", settings)
}
}
func TestUpdateEdgeTLSSettingsRejectsConcurrentChangeToRequestedFieldBeforePatching(t *testing.T) {
t.Parallel()
current := map[string]string{
"ssl": "flexible", "always_use_https": "off", "min_tls_version": "1.2", "tls_1_3": "on",
}
patches := 0
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
const prefix = "/client/v4/zones/zone-1/settings/"
if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, prefix) {
id := strings.TrimPrefix(r.URL.Path, prefix)
writeResult(t, w, map[string]any{"id": id, "value": current[id], "editable": true}, nil)
return
}
if r.Method == http.MethodPatch {
patches++
}
http.NotFound(w, r)
})
baseline := domain.EdgeTLSSettings{Mode: "strict", MinimumTLS: "1.2", TLS13: true}
desired := baseline
desired.Mode = "full"
_, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone-1", baseline, desired)
if err == nil || !strings.Contains(err.Error(), "changed remotely") || patches != 0 {
t.Fatalf("concurrent field error = %v, patches=%d", err, patches)
}
}
func TestUpdateEdgeTLSSettingsValidatesBeforeNetwork(t *testing.T) {
t.Parallel()
called := false
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
http.Error(w, "unexpected", http.StatusInternalServerError)
})
_, err := client.UpdateEdgeTLSSettings(context.Background(), testAuth(), "zone", domain.EdgeTLSSettings{}, domain.EdgeTLSSettings{Mode: "unsafe", MinimumTLS: "1.2"})
if err == nil || called {
t.Fatalf("error = %v, called = %v", err, called)
}
}
func TestListEdgeCertificatesUsesEarliestPackExpiry(t *testing.T) {
t.Parallel()
client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/client/v4/zones/zone-1/ssl/certificate_packs" {
http.NotFound(w, r)
return
}
if r.URL.Query().Get("status") != "all" || r.URL.Query().Get("page") != "2" {
t.Errorf("certificate query = %v", r.URL.Query())
}
writeResult(t, w, []any{
map[string]any{
"id": "pack-1", "type": "universal", "status": "active", "hosts": []string{"example.com"},
"certificates": []any{
map[string]any{"id": "rsa", "hosts": []string{"example.com", "*.example.com"}, "status": "active", "expires_on": "2026-10-01T00:00:00Z"},
map[string]any{"id": "ecdsa", "hosts": []string{"example.com"}, "status": "active", "expires_on": "2026-09-01T00:00:00Z"},
},
},
map[string]any{"id": "pack-other", "type": "advanced", "status": "active", "hosts": []string{"other.test"}},
}, map[string]any{"page": 2, "total_pages": 2})
})
certificates, err := client.ListEdgeCertificates(context.Background(), testAuth(), "zone-1", provider.PageRequest{Page: 2, PerPage: 10, Search: "example"})
if err != nil {
t.Fatalf("ListEdgeCertificates: %v", err)
}
if len(certificates) != 1 {
t.Fatalf("certificates = %+v", certificates)
}
certificate := certificates[0]
wantExpiry := time.Date(2026, time.September, 1, 0, 0, 0, 0, time.UTC)
if certificate.ID != "pack-1" || certificate.ExpiresAt == nil || !certificate.ExpiresAt.Equal(wantExpiry) {
t.Errorf("certificate = %+v", certificate)
}
if len(certificate.Hosts) != 2 || certificate.Hosts[1] != "*.example.com" {
t.Errorf("hosts = %v", certificate.Hosts)
}
}
+177
View File
@@ -0,0 +1,177 @@
package cloudflare
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
type tokenVerificationWire struct {
ID string `json:"id"`
Status string `json:"status"`
}
// VerifyCredential verifies the correct token namespace, discovers accessible
// accounts, and performs real zone/DNS/settings reads. Cloudflare's verification
// response does not expose effective permission groups, so read probes never
// claim write access. DomainOps records write capability only after a real write
// succeeds and Cloudflare remains authoritative for every mutation.
func (c *Client) VerifyCredential(ctx context.Context, auth provider.Auth) (provider.Verification, error) {
verification := provider.Verification{Status: domain.CredentialInvalid}
if err := validateAuth(auth); err != nil {
return verification, err
}
verifyPath := "user/tokens/verify"
if auth.Kind == domain.CredentialAccountToken {
var err error
verifyPath, err = apiPath("accounts", auth.AccountID, "tokens", "verify")
if err != nil {
return verification, err
}
}
raw, _, err := c.do(ctx, auth, http.MethodGet, verifyPath, nil, nil)
if err != nil {
return verification, err
}
var token tokenVerificationWire
if err := json.Unmarshal(raw, &token); err != nil {
return verification, &ResponseError{Resource: "token verification", Err: err}
}
if !strings.EqualFold(token.Status, "active") {
return verification, nil
}
verification.Status = domain.CredentialValid
syncedAt := c.now().UTC()
accounts, err := c.discoverAccounts(ctx, auth)
if err != nil {
var apiErr *APIError
if !errors.As(err, &apiErr) || apiErr.StatusCode >= http.StatusInternalServerError || apiErr.StatusCode == http.StatusTooManyRequests {
return verification, fmt.Errorf("cloudflare: discover accounts: %w", err)
}
// Some Cloudflare bearer tokens cannot use the legacy account listing
// endpoints. Zone results remain the source of truth for discovery.
accounts = nil
}
zones, _, _, zoneErr := c.listZones(ctx, auth, provider.PageRequest{Page: 1, PerPage: 50})
if zoneErr == nil {
verification.Capabilities.ZoneRead = true
accounts = mergeAccounts(accounts, accountsFromZones(zones, syncedAt))
} else if !errors.Is(zoneErr, ErrForbidden) {
return verification, fmt.Errorf("cloudflare: probe zone access: %w", zoneErr)
}
if len(accounts) == 0 && auth.AccountID != "" {
lastSynced := syncedAt
accounts = []domain.RemoteAccount{{
ID: auth.AccountID,
Provider: domain.ProviderCloudflare,
ProviderID: auth.AccountID,
Name: auth.AccountID,
LastSyncedAt: &lastSynced,
}}
}
verification.Accounts = accounts
if len(zones) > 0 {
zoneID := zones[0].ID
if err := c.probeDNSAccess(ctx, auth, zoneID); err == nil {
verification.Capabilities.DNSRead = true
} else if !errors.Is(err, ErrForbidden) {
return verification, fmt.Errorf("cloudflare: probe DNS access: %w", err)
}
if err := c.probeTLSAccess(ctx, auth, zoneID); err == nil {
verification.Capabilities.TLSRead = true
} else if !errors.Is(err, ErrForbidden) {
return verification, fmt.Errorf("cloudflare: probe TLS access: %w", err)
}
}
sortCapabilityNames(&verification.Capabilities)
return verification, nil
}
func (c *Client) discoverAccounts(ctx context.Context, auth provider.Auth) ([]domain.RemoteAccount, error) {
syncedAt := c.now().UTC()
if auth.AccountID != "" {
path, err := apiPath("accounts", auth.AccountID)
if err != nil {
return nil, err
}
raw, _, err := c.do(ctx, auth, http.MethodGet, path, nil, nil)
if errors.Is(err, ErrForbidden) {
return nil, nil
}
if err != nil {
return nil, err
}
var wire accountWire
if err := json.Unmarshal(raw, &wire); err != nil {
return nil, &ResponseError{Resource: "account", Err: err}
}
account := mapAccount(wire)
account.LastSyncedAt = &syncedAt
return []domain.RemoteAccount{account}, nil
}
const maxPages = 100
var accounts []domain.RemoteAccount
for page := 1; page <= maxPages; page++ {
query := url.Values{
"page": {strconv.Itoa(page)},
"per_page": {"50"},
}
raw, info, err := c.do(ctx, auth, http.MethodGet, "accounts", query, nil)
if errors.Is(err, ErrForbidden) {
return accounts, nil
}
if err != nil {
return nil, err
}
var wires []accountWire
if err := json.Unmarshal(raw, &wires); err != nil {
return nil, &ResponseError{Resource: "accounts", Err: err}
}
for _, wire := range wires {
account := mapAccount(wire)
account.LastSyncedAt = &syncedAt
accounts = append(accounts, account)
}
if info.TotalPages > 0 {
if page >= info.TotalPages {
return accounts, nil
}
} else if len(wires) < 50 {
return accounts, nil
}
}
return nil, &ResponseError{Resource: "accounts", Err: errors.New("pagination exceeded 100 pages")}
}
func (c *Client) probeDNSAccess(ctx context.Context, auth provider.Auth, zoneID string) error {
path, err := apiPath("zones", zoneID, "dns_records")
if err != nil {
return err
}
_, _, err = c.do(ctx, auth, http.MethodGet, path, url.Values{"page": {"1"}, "per_page": {"1"}}, nil)
return err
}
func (c *Client) probeTLSAccess(ctx context.Context, auth provider.Auth, zoneID string) error {
path, err := apiPath("zones", zoneID, "settings", "ssl")
if err != nil {
return err
}
_, _, err = c.do(ctx, auth, http.MethodGet, path, nil, nil)
return err
}
+138
View File
@@ -0,0 +1,138 @@
package cloudflare
import (
"context"
"encoding/json"
"net/http"
"sort"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/provider"
)
// ListZones lists one Cloudflare zone page and preserves the provider's stable
// zone and account identifiers for reconciliation.
func (c *Client) ListZones(ctx context.Context, auth provider.Auth, request provider.PageRequest) (provider.ZonePage, error) {
wires, info, page, err := c.listZones(ctx, auth, request)
if err != nil {
return provider.ZonePage{}, err
}
syncedAt := c.now().UTC()
zones := make([]domain.Zone, 0, len(wires))
for _, wire := range wires {
zones = append(zones, mapZone(wire, auth.CredentialID, syncedAt))
}
return provider.ZonePage{
Zones: zones,
NextCursor: nextCursor(info, page, len(zones), queryPerPage(request, 50, 50)),
Page: page,
TotalPages: info.TotalPages,
}, nil
}
func (c *Client) listZones(ctx context.Context, auth provider.Auth, request provider.PageRequest) ([]zoneWire, resultInfo, int, error) {
query, page := paginationQuery(request, 50, 50)
if auth.AccountID != "" {
query.Set("account.id", auth.AccountID)
}
if search := strings.TrimSpace(request.Search); search != "" {
ascii, err := toASCIIName(search)
if err != nil {
return nil, resultInfo{}, 0, err
}
query.Set("name", ascii)
}
raw, info, err := c.do(ctx, auth, http.MethodGet, "zones", query, nil)
if err != nil {
return nil, resultInfo{}, 0, err
}
var zones []zoneWire
if err := json.Unmarshal(raw, &zones); err != nil {
return nil, resultInfo{}, 0, &ResponseError{Resource: "zones", Err: err}
}
return zones, info, page, nil
}
func queryPerPage(request provider.PageRequest, defaultValue, maximum int) int {
value := request.PerPage
if value <= 0 {
value = defaultValue
}
if value > maximum {
value = maximum
}
return value
}
func accountsFromZones(zones []zoneWire, syncedAt time.Time) []domain.RemoteAccount {
seen := make(map[string]struct{})
accounts := make([]domain.RemoteAccount, 0)
for _, zone := range zones {
if zone.Account.ID == "" {
continue
}
if _, ok := seen[zone.Account.ID]; ok {
continue
}
seen[zone.Account.ID] = struct{}{}
account := mapAccount(zone.Account)
timestamp := syncedAt
account.LastSyncedAt = &timestamp
accounts = append(accounts, account)
}
return accounts
}
func mergeAccounts(groups ...[]domain.RemoteAccount) []domain.RemoteAccount {
byID := make(map[string]domain.RemoteAccount)
order := make([]string, 0)
for _, group := range groups {
for _, account := range group {
if account.ProviderID == "" {
continue
}
if current, found := byID[account.ProviderID]; found {
if current.Name == "" && account.Name != "" {
current.Name = account.Name
}
if current.CreatedAt.IsZero() && !account.CreatedAt.IsZero() {
current.CreatedAt = account.CreatedAt
}
if account.LastSyncedAt != nil {
current.LastSyncedAt = account.LastSyncedAt
}
byID[account.ProviderID] = current
continue
}
byID[account.ProviderID] = account
order = append(order, account.ProviderID)
}
}
result := make([]domain.RemoteAccount, 0, len(order))
for _, id := range order {
result = append(result, byID[id])
}
return result
}
func sortCapabilityNames(capabilities *provider.Capabilities) {
capabilities.Names = capabilities.Names[:0]
if capabilities.ZoneRead {
capabilities.Names = append(capabilities.Names, "zone:read")
}
if capabilities.DNSRead {
capabilities.Names = append(capabilities.Names, "dns:read")
}
if capabilities.DNSWrite {
capabilities.Names = append(capabilities.Names, "dns:write")
}
if capabilities.TLSRead {
capabilities.Names = append(capabilities.Names, "tls:read")
}
if capabilities.TLSWrite {
capabilities.Names = append(capabilities.Names, "tls:write")
}
sort.Strings(capabilities.Names)
}
+637
View File
@@ -0,0 +1,637 @@
// Package secrets provides DomainOps' encrypted local secret store.
package secrets
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"github.com/MeghdadFadaee/domainops/internal/identifier"
"github.com/MeghdadFadaee/domainops/internal/store"
"github.com/zalando/go-keyring"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/chacha20poly1305"
)
const (
vaultVersion = 1
keySize = chacha20poly1305.KeySize
saltSize = 16
directoryMode = 0o700
fileMode = 0o600
defaultArgonTime = uint32(3)
defaultArgonMemory = uint32(64 * 1024)
defaultArgonThreads = uint8(4)
)
var (
// ErrLocked means the vault must be unlocked before accessing secrets.
ErrLocked = errors.New("secrets: vault is locked")
// ErrSecretNotFound means no secret exists for the supplied reference.
ErrSecretNotFound = errors.New("secrets: secret not found")
// ErrPassphraseRequired means no passphrase or usable keyring key was supplied.
ErrPassphraseRequired = errors.New("secrets: passphrase required")
// ErrInvalidPassphrase means the passphrase could not unwrap the vault key.
ErrInvalidPassphrase = errors.New("secrets: invalid passphrase")
// ErrCorruptVault means the encrypted vault envelope failed validation or authentication.
ErrCorruptVault = errors.New("secrets: corrupt vault")
)
const (
wrappedKeyAAD = "domainops/vault/v1/wrapped-key"
dataAAD = "domainops/vault/v1/data"
)
type kdfEnvelope struct {
Name string `json:"name"`
Salt string `json:"salt"`
Time uint32 `json:"time"`
Memory uint32 `json:"memory_kib"`
Threads uint8 `json:"threads"`
}
type cipherEnvelope struct {
Nonce string `json:"nonce"`
Ciphertext string `json:"ciphertext"`
}
type diskEnvelope struct {
Version int `json:"version"`
KDF kdfEnvelope `json:"kdf"`
WrappedKey cipherEnvelope `json:"wrapped_key"`
Data cipherEnvelope `json:"data"`
}
type vaultPayload struct {
Entries map[string][]byte `json:"entries"`
}
// Vault encrypts all values using a random XChaCha20-Poly1305 data key. The
// passphrase-derived Argon2id key encrypts only that data key.
type Vault struct {
mu sync.RWMutex
path string
service string
account string
envelope diskEnvelope
dataKey []byte
entries map[string][]byte
// writeEnvelopeOverride is a package-private durability fault-injection
// seam. Production vaults leave it nil.
writeEnvelopeOverride func(diskEnvelope) error
}
var _ store.SecretStore = (*Vault)(nil)
// New opens vaultPath. A blank keyringService disables keyring integration,
// which is useful on deliberately headless systems. Existing vaults are
// opportunistically auto-unlocked when a valid data key is available in the
// configured OS keyring; every keyring failure is non-fatal.
func New(vaultPath, keyringService, keyringAccount string) (*Vault, error) {
if strings.TrimSpace(vaultPath) == "" {
return nil, errors.New("secrets: vault path is empty")
}
absolute, err := filepath.Abs(vaultPath)
if err != nil {
return nil, fmt.Errorf("secrets: resolve vault path: %w", err)
}
dir := filepath.Dir(absolute)
if err := os.MkdirAll(dir, directoryMode); err != nil {
return nil, fmt.Errorf("secrets: create vault directory: %w", err)
}
if err := os.Chmod(dir, directoryMode); err != nil {
return nil, fmt.Errorf("secrets: secure vault directory: %w", err)
}
if info, err := os.Lstat(absolute); err == nil {
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
return nil, errors.New("secrets: vault path is not a regular file")
}
if err := os.Chmod(absolute, fileMode); err != nil {
return nil, fmt.Errorf("secrets: secure vault file: %w", err)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("secrets: inspect vault file: %w", err)
}
if keyringService != "" && keyringAccount == "" {
digest := sha256.Sum256([]byte(absolute))
keyringAccount = fmt.Sprintf("vault-%x", digest[:8])
}
vault := &Vault{
path: absolute,
service: keyringService,
account: keyringAccount,
}
if keyringService != "" {
vault.tryAutoUnlock()
}
return vault, nil
}
// NewDefault enables OS-keyring auto-unlock under the DomainOps service name.
func NewDefault(vaultPath string) (*Vault, error) {
return New(vaultPath, "domainops", "")
}
// Locked reports whether secret values are unavailable.
func (v *Vault) Locked() bool {
v.mu.RLock()
defer v.mu.RUnlock()
return len(v.dataKey) != keySize
}
// Unlock initializes a missing vault on first use, or decrypts an existing
// vault. An empty passphrase only attempts OS-keyring unlock.
func (v *Vault) Unlock(ctx context.Context, passphrase []byte) error {
if err := ctx.Err(); err != nil {
return err
}
v.mu.Lock()
defer v.mu.Unlock()
if len(v.dataKey) == keySize {
return nil
}
envelope, err := v.readEnvelope()
if errors.Is(err, os.ErrNotExist) {
if len(passphrase) == 0 {
return ErrPassphraseRequired
}
return v.initializeLocked(ctx, passphrase)
}
if err != nil {
return err
}
var dataKey []byte
if len(passphrase) == 0 {
dataKey, err = v.keyFromKeyring()
if err != nil {
return ErrPassphraseRequired
}
} else {
dataKey, err = unwrapDataKey(envelope, passphrase)
if err != nil {
return err
}
}
defer func() {
if v.dataKey == nil {
wipe(dataKey)
}
}()
if err := ctx.Err(); err != nil {
return err
}
entries, err := decryptEntries(envelope, dataKey)
if err != nil {
return err
}
v.envelope = envelope
v.dataKey = dataKey
v.entries = entries
if len(passphrase) != 0 {
v.saveKeyringKey(dataKey)
}
return nil
}
// Lock removes decrypted material from memory.
func (v *Vault) Lock() {
v.mu.Lock()
defer v.mu.Unlock()
wipe(v.dataKey)
for key, value := range v.entries {
wipe(value)
delete(v.entries, key)
}
v.dataKey = nil
v.entries = nil
v.envelope = diskEnvelope{}
}
// Put stores a copy of value and returns its stable reference. An empty
// reference generates a cryptographically random one.
func (v *Vault) Put(ctx context.Context, reference string, value []byte) (string, error) {
if err := ctx.Err(); err != nil {
return "", err
}
v.mu.Lock()
defer v.mu.Unlock()
if len(v.dataKey) != keySize {
return "", ErrLocked
}
if reference == "" {
reference = identifier.New("secret")
}
next := cloneEntries(v.entries)
next[reference] = append([]byte(nil), value...)
if err := v.persistEntriesLocked(next); err != nil {
var committed *committedEnvelopeError
if errors.As(err, &committed) {
wipeEntries(v.entries)
v.entries = next
return reference, err
}
wipeEntries(next)
return "", err
}
wipeEntries(v.entries)
v.entries = next
return reference, nil
}
// Get returns a copy of the secret value.
func (v *Vault) Get(ctx context.Context, reference string) ([]byte, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
v.mu.RLock()
defer v.mu.RUnlock()
if len(v.dataKey) != keySize {
return nil, ErrLocked
}
value, ok := v.entries[reference]
if !ok {
return nil, ErrSecretNotFound
}
return append([]byte(nil), value...), nil
}
// Delete removes a secret. Deleting an unknown reference is idempotent.
func (v *Vault) Delete(ctx context.Context, reference string) error {
if err := ctx.Err(); err != nil {
return err
}
v.mu.Lock()
defer v.mu.Unlock()
if len(v.dataKey) != keySize {
return ErrLocked
}
if _, ok := v.entries[reference]; !ok {
// Also acts as a durability retry after a prior delete committed its
// rename but reported a directory-sync error.
return syncVaultDirectory(filepath.Dir(v.path))
}
next := cloneEntries(v.entries)
wipe(next[reference])
delete(next, reference)
if err := v.persistEntriesLocked(next); err != nil {
var committed *committedEnvelopeError
if errors.As(err, &committed) {
wipeEntries(v.entries)
v.entries = next
return err
}
wipeEntries(next)
return err
}
wipeEntries(v.entries)
v.entries = next
return nil
}
func (v *Vault) initializeLocked(ctx context.Context, passphrase []byte) error {
dataKey := make([]byte, keySize)
if _, err := rand.Read(dataKey); err != nil {
return fmt.Errorf("secrets: generate vault key: %w", err)
}
defer func() {
if v.dataKey == nil {
wipe(dataKey)
}
}()
salt := make([]byte, saltSize)
if _, err := rand.Read(salt); err != nil {
return fmt.Errorf("secrets: generate KDF salt: %w", err)
}
envelope := diskEnvelope{
Version: vaultVersion,
KDF: kdfEnvelope{
Name: "argon2id", Salt: base64.RawStdEncoding.EncodeToString(salt),
Time: defaultArgonTime, Memory: defaultArgonMemory, Threads: defaultArgonThreads,
},
}
wrappingKey := argon2.IDKey(passphrase, salt, envelope.KDF.Time, envelope.KDF.Memory, envelope.KDF.Threads, keySize)
wipe(salt)
defer wipe(wrappingKey)
wrapped, err := encrypt(wrappingKey, dataKey, []byte(wrappedKeyAAD))
if err != nil {
return fmt.Errorf("secrets: wrap vault key: %w", err)
}
envelope.WrappedKey = wrapped
entries := make(map[string][]byte)
payload, err := encryptPayload(dataKey, entries)
if err != nil {
return err
}
envelope.Data = payload
if err := ctx.Err(); err != nil {
return err
}
if err := v.writeEnvelope(envelope); err != nil {
return err
}
v.envelope = envelope
v.dataKey = dataKey
v.entries = entries
v.saveKeyringKey(dataKey)
return nil
}
func unwrapDataKey(envelope diskEnvelope, passphrase []byte) ([]byte, error) {
salt, err := validateEnvelope(envelope)
if err != nil {
return nil, err
}
defer wipe(salt)
wrappingKey := argon2.IDKey(passphrase, salt, envelope.KDF.Time, envelope.KDF.Memory, envelope.KDF.Threads, keySize)
defer wipe(wrappingKey)
dataKey, err := decrypt(wrappingKey, envelope.WrappedKey, []byte(wrappedKeyAAD))
if err != nil || len(dataKey) != keySize {
wipe(dataKey)
return nil, ErrInvalidPassphrase
}
return dataKey, nil
}
func validateEnvelope(envelope diskEnvelope) ([]byte, error) {
if envelope.Version != vaultVersion || envelope.KDF.Name != "argon2id" {
return nil, ErrCorruptVault
}
if envelope.KDF.Time < 1 || envelope.KDF.Time > 10 ||
envelope.KDF.Memory < 8*1024 || envelope.KDF.Memory > 1024*1024 ||
envelope.KDF.Threads < 1 || envelope.KDF.Threads > 64 {
return nil, ErrCorruptVault
}
salt, err := base64.RawStdEncoding.DecodeString(envelope.KDF.Salt)
if err != nil || len(salt) < 16 || len(salt) > 64 {
wipe(salt)
return nil, ErrCorruptVault
}
return salt, nil
}
func encryptPayload(dataKey []byte, entries map[string][]byte) (cipherEnvelope, error) {
plain, err := json.Marshal(vaultPayload{Entries: entries})
if err != nil {
return cipherEnvelope{}, fmt.Errorf("secrets: encode vault payload: %w", err)
}
defer wipe(plain)
result, err := encrypt(dataKey, plain, []byte(dataAAD))
if err != nil {
return cipherEnvelope{}, fmt.Errorf("secrets: encrypt vault payload: %w", err)
}
return result, nil
}
func decryptEntries(envelope diskEnvelope, dataKey []byte) (map[string][]byte, error) {
salt, err := validateEnvelope(envelope)
if err != nil {
return nil, err
}
wipe(salt)
plain, err := decrypt(dataKey, envelope.Data, []byte(dataAAD))
if err != nil {
return nil, ErrCorruptVault
}
defer wipe(plain)
var payload vaultPayload
if err := json.Unmarshal(plain, &payload); err != nil {
return nil, ErrCorruptVault
}
if payload.Entries == nil {
payload.Entries = make(map[string][]byte)
}
return payload.Entries, nil
}
func encrypt(key, plaintext, additionalData []byte) (cipherEnvelope, error) {
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return cipherEnvelope{}, err
}
nonce := make([]byte, aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return cipherEnvelope{}, err
}
ciphertext := aead.Seal(nil, nonce, plaintext, additionalData)
return cipherEnvelope{
Nonce: base64.RawStdEncoding.EncodeToString(nonce),
Ciphertext: base64.RawStdEncoding.EncodeToString(ciphertext),
}, nil
}
func decrypt(key []byte, encrypted cipherEnvelope, additionalData []byte) ([]byte, error) {
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
}
nonce, err := base64.RawStdEncoding.DecodeString(encrypted.Nonce)
if err != nil || len(nonce) != aead.NonceSize() {
return nil, ErrCorruptVault
}
ciphertext, err := base64.RawStdEncoding.DecodeString(encrypted.Ciphertext)
if err != nil || len(ciphertext) < aead.Overhead() {
return nil, ErrCorruptVault
}
return aead.Open(nil, nonce, ciphertext, additionalData)
}
func (v *Vault) persistEntriesLocked(entries map[string][]byte) error {
encrypted, err := encryptPayload(v.dataKey, entries)
if err != nil {
return err
}
next := v.envelope
next.Data = encrypted
writeEnvelope := v.writeEnvelope
if v.writeEnvelopeOverride != nil {
writeEnvelope = v.writeEnvelopeOverride
}
if err := writeEnvelope(next); err != nil {
var committed *committedEnvelopeError
if errors.As(err, &committed) {
v.envelope = next
}
return err
}
v.envelope = next
return nil
}
// CommittedWriteError means the atomic rename changed the live vault path, but
// a following permission or directory-durability check failed. Put returns the
// committed reference alongside this error so callers can persist metadata or
// explicitly compensate it instead of leaking an untracked secret.
type CommittedWriteError struct{ err error }
func (e *CommittedWriteError) Error() string { return e.err.Error() }
func (e *CommittedWriteError) Unwrap() error { return e.err }
func IsCommittedWriteError(err error) bool {
var committed *CommittedWriteError
return errors.As(err, &committed)
}
type committedEnvelopeError = CommittedWriteError
func (v *Vault) readEnvelope() (diskEnvelope, error) {
var envelope diskEnvelope
info, err := os.Lstat(v.path)
if err != nil {
return envelope, err
}
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
return envelope, ErrCorruptVault
}
body, err := os.ReadFile(v.path)
if err != nil {
return envelope, fmt.Errorf("secrets: read vault: %w", err)
}
if err := json.Unmarshal(body, &envelope); err != nil {
return envelope, ErrCorruptVault
}
salt, err := validateEnvelope(envelope)
if err != nil {
return envelope, err
}
wipe(salt)
return envelope, nil
}
func (v *Vault) writeEnvelope(envelope diskEnvelope) error {
body, err := json.MarshalIndent(envelope, "", " ")
if err != nil {
return fmt.Errorf("secrets: encode vault envelope: %w", err)
}
body = append(body, '\n')
dir := filepath.Dir(v.path)
temporary, err := os.CreateTemp(dir, ".vault-*")
if err != nil {
return fmt.Errorf("secrets: create temporary vault: %w", err)
}
temporaryPath := temporary.Name()
remove := true
defer func() {
_ = temporary.Close()
if remove {
_ = os.Remove(temporaryPath)
}
}()
if err := temporary.Chmod(fileMode); err != nil {
return fmt.Errorf("secrets: secure temporary vault: %w", err)
}
if _, err := temporary.Write(body); err != nil {
return fmt.Errorf("secrets: write temporary vault: %w", err)
}
if err := temporary.Sync(); err != nil {
return fmt.Errorf("secrets: sync temporary vault: %w", err)
}
if err := temporary.Close(); err != nil {
return fmt.Errorf("secrets: close temporary vault: %w", err)
}
directory, err := os.Open(dir)
if err != nil {
return fmt.Errorf("secrets: open vault directory before replace: %w", err)
}
defer directory.Close()
if err := os.Rename(temporaryPath, v.path); err != nil {
return fmt.Errorf("secrets: replace vault: %w", err)
}
remove = false
if err := directory.Sync(); err != nil {
return &committedEnvelopeError{err: fmt.Errorf("secrets: sync vault directory: %w", err)}
}
return nil
}
func syncVaultDirectory(path string) error {
directory, err := os.Open(path)
if err != nil {
return fmt.Errorf("secrets: open vault directory: %w", err)
}
defer directory.Close()
if err := directory.Sync(); err != nil {
return fmt.Errorf("secrets: sync vault directory: %w", err)
}
return nil
}
func (v *Vault) tryAutoUnlock() {
v.mu.Lock()
defer v.mu.Unlock()
envelope, err := v.readEnvelope()
if err != nil {
return
}
dataKey, err := v.keyFromKeyring()
if err != nil {
return
}
entries, err := decryptEntries(envelope, dataKey)
if err != nil {
wipe(dataKey)
return
}
v.envelope = envelope
v.dataKey = dataKey
v.entries = entries
}
func (v *Vault) keyFromKeyring() ([]byte, error) {
if v.service == "" {
return nil, keyring.ErrNotFound
}
encoded, err := keyring.Get(v.service, v.account)
if err != nil {
return nil, err
}
dataKey, err := base64.RawStdEncoding.DecodeString(encoded)
if err != nil || len(dataKey) != keySize {
wipe(dataKey)
return nil, errors.New("invalid keyring vault key")
}
return dataKey, nil
}
func (v *Vault) saveKeyringKey(dataKey []byte) {
if v.service == "" {
return
}
// Keyring support is an optimization only; headless Linux and unavailable
// keyrings always continue to use the passphrase path.
_ = keyring.Set(v.service, v.account, base64.RawStdEncoding.EncodeToString(dataKey))
}
func cloneEntries(source map[string][]byte) map[string][]byte {
result := make(map[string][]byte, len(source))
for key, value := range source {
result[key] = append([]byte(nil), value...)
}
return result
}
func wipeEntries(entries map[string][]byte) {
for key, value := range entries {
wipe(value)
delete(entries, key)
}
}
func wipe(value []byte) {
for i := range value {
value[i] = 0
}
}
+189
View File
@@ -0,0 +1,189 @@
package secrets
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
)
func TestVaultRoundTripLockAndWrongPassword(t *testing.T) {
path := filepath.Join(t.TempDir(), "state", "vault.json")
vault, err := New(path, "", "")
if err != nil {
t.Fatal(err)
}
if !vault.Locked() {
t.Fatal("new vault should start locked")
}
password := []byte("correct horse battery staple")
if err := vault.Unlock(context.Background(), password); err != nil {
t.Fatal(err)
}
first, err := vault.Put(context.Background(), "", []byte("token-one"))
if err != nil {
t.Fatal(err)
}
second, err := vault.Put(context.Background(), "", []byte("token-two"))
if err != nil {
t.Fatal(err)
}
if first == second || first == "" || second == "" {
t.Fatalf("secret references must be unique: %q %q", first, second)
}
value, err := vault.Get(context.Background(), first)
if err != nil || string(value) != "token-one" {
t.Fatalf("get first secret = %q, %v", value, err)
}
vault.Lock()
if _, err := vault.Get(context.Background(), first); !errors.Is(err, ErrLocked) {
t.Fatalf("locked Get error = %v", err)
}
if err := vault.Unlock(context.Background(), []byte("definitely wrong")); !errors.Is(err, ErrInvalidPassphrase) {
t.Fatalf("wrong password error = %v", err)
}
if err := vault.Unlock(context.Background(), password); err != nil {
t.Fatal(err)
}
value, err = vault.Get(context.Background(), second)
if err != nil || string(value) != "token-two" {
t.Fatalf("persisted second secret = %q, %v", value, err)
}
if err := vault.Delete(context.Background(), first); err != nil {
t.Fatal(err)
}
if _, err := vault.Get(context.Background(), first); !errors.Is(err, ErrSecretNotFound) {
t.Fatalf("deleted secret error = %v", err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0o600 {
t.Fatalf("vault mode = %o", info.Mode().Perm())
}
parent, err := os.Stat(filepath.Dir(path))
if err != nil {
t.Fatal(err)
}
if parent.Mode().Perm() != 0o700 {
t.Fatalf("vault parent mode = %o", parent.Mode().Perm())
}
}
func TestVaultRejectsTamperingAndSymlinks(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "vault.json")
vault, err := New(path, "", "")
if err != nil {
t.Fatal(err)
}
password := []byte("a long test password")
if err := vault.Unlock(context.Background(), password); err != nil {
t.Fatal(err)
}
if _, err := vault.Put(context.Background(), "ref", []byte("secret")); err != nil {
t.Fatal(err)
}
vault.Lock()
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
for i := len(body) / 2; i < len(body); i++ {
if body[i] >= 'A' && body[i] <= 'Z' {
body[i] = 'a'
break
}
}
if err := os.WriteFile(path, body, 0o600); err != nil {
t.Fatal(err)
}
tampered, err := New(path, "", "")
if err != nil {
t.Fatal(err)
}
if err := tampered.Unlock(context.Background(), password); err == nil {
t.Fatal("tampered vault unexpectedly unlocked")
}
target := filepath.Join(root, "target")
if err := os.WriteFile(target, []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "link")
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
if _, err := New(link, "", ""); err == nil {
t.Fatal("symlink vault unexpectedly accepted")
}
}
func TestVaultHonorsCancelledContext(t *testing.T) {
vault, err := New(filepath.Join(t.TempDir(), "vault.json"), "", "")
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := vault.Unlock(ctx, []byte("long enough password")); !errors.Is(err, context.Canceled) {
t.Fatalf("Unlock error = %v", err)
}
}
func TestVaultTracksPostRenamePutAndDeleteOutcomes(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "vault.json")
vault, err := New(path, "", "")
if err != nil {
t.Fatal(err)
}
password := []byte("long durability password")
if err := vault.Unlock(ctx, password); err != nil {
t.Fatal(err)
}
injectCommittedError := func(envelope diskEnvelope) error {
if err := vault.writeEnvelope(envelope); err != nil {
return err
}
return &committedEnvelopeError{err: errors.New("injected directory sync failure")}
}
vault.writeEnvelopeOverride = injectCommittedError
reference, err := vault.Put(ctx, "committed-ref", []byte("secret"))
if reference != "committed-ref" || err == nil {
t.Fatalf("post-rename Put = ref:%q err:%v", reference, err)
}
if value, getErr := vault.Get(ctx, reference); getErr != nil || string(value) != "secret" {
t.Fatalf("in-memory committed Put = %q, %v", value, getErr)
}
vault.writeEnvelopeOverride = nil
vault.Lock()
if err := vault.Unlock(ctx, password); err != nil {
t.Fatal(err)
}
if value, getErr := vault.Get(ctx, reference); getErr != nil || string(value) != "secret" {
t.Fatalf("on-disk committed Put = %q, %v", value, getErr)
}
vault.writeEnvelopeOverride = injectCommittedError
if err := vault.Delete(ctx, reference); err == nil {
t.Fatal("post-rename Delete did not report durability failure")
}
if _, getErr := vault.Get(ctx, reference); !errors.Is(getErr, ErrSecretNotFound) {
t.Fatalf("in-memory committed Delete = %v", getErr)
}
if err := vault.Delete(ctx, reference); err != nil {
t.Fatalf("idempotent delete did not retry directory durability: %v", err)
}
vault.writeEnvelopeOverride = nil
vault.Lock()
if err := vault.Unlock(ctx, password); err != nil {
t.Fatal(err)
}
if _, getErr := vault.Get(ctx, reference); !errors.Is(getErr, ErrSecretNotFound) {
t.Fatalf("on-disk committed Delete = %v", getErr)
}
}
+88
View File
@@ -0,0 +1,88 @@
package store
import (
"context"
"errors"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
// ErrACMEAccountConflict means an ACME environment already has an account.
// Account registration is insert-only because replacing the account ID would
// strand certificate lineages and leave the previous account key unreferenced.
var ErrACMEAccountConflict = errors.New("store: ACME account environment already registered")
type Repository interface {
Close() error
Migrate(context.Context) error
SaveCredential(context.Context, domain.Credential) error
ListCredentials(context.Context) ([]domain.Credential, error)
GetCredential(context.Context, string) (domain.Credential, error)
DeleteCredential(context.Context, string) error
SaveCredentialZoneCapability(context.Context, string, string, string, time.Time) error
HasCredentialZoneCapability(context.Context, string, string, string) (bool, error)
GetCredentialZoneCapability(context.Context, string, string, string) (time.Time, bool, error)
InvalidateCredentialZoneCapability(context.Context, string, string, string) error
SaveAccounts(context.Context, []domain.RemoteAccount, []domain.AccountCredential) error
ListAccounts(context.Context) ([]domain.RemoteAccount, error)
SaveZones(context.Context, []domain.Zone) error
ListZones(context.Context) ([]domain.Zone, error)
GetZone(context.Context, string) (domain.Zone, error)
ReplaceDNSRecords(context.Context, string, []domain.DNSRecord, time.Time) error
ListDNSRecords(context.Context, string) ([]domain.DNSRecord, error)
SaveDNSRecord(context.Context, domain.DNSRecord) error
DeleteDNSRecord(context.Context, string) error
SaveTLSSettings(context.Context, domain.EdgeTLSSettings) error
GetTLSSettings(context.Context, string) (domain.EdgeTLSSettings, error)
SaveACMEAccount(context.Context, domain.ACMEAccount) error
CommitACMEAccount(context.Context, domain.ACMEAccount) error
GetACMEAccountByEnvironment(context.Context, string) (domain.ACMEAccount, error)
SaveACMEAccountCommitIntent(context.Context, domain.ACMEAccountCommitIntent) error
ListACMEAccountCommitIntents(context.Context) ([]domain.ACMEAccountCommitIntent, error)
DeleteACMEAccountCommitIntent(context.Context, string) error
SaveCertificateLineage(context.Context, domain.CertificateLineage) error
SaveCertificateVersion(context.Context, domain.CertificateVersion) error
CommitCertificateVersion(context.Context, domain.CertificateLineage, domain.CertificateVersion) error
SaveCertificateCommitIntent(context.Context, domain.CertificateCommitIntent) error
ListCertificateCommitIntents(context.Context) ([]domain.CertificateCommitIntent, error)
DeleteCertificateCommitIntent(context.Context, string) error
ListCertificateLineages(context.Context) ([]domain.CertificateLineage, error)
ListCertificateVersions(context.Context, string) ([]domain.CertificateVersion, error)
GetCertificateLineage(context.Context, string) (domain.CertificateLineage, error)
SaveEndpoint(context.Context, domain.ObservedEndpoint) error
ListEndpoints(context.Context) ([]domain.ObservedEndpoint, error)
SaveHealthIssues(context.Context, string, []domain.HealthIssue) error
ListHealthIssues(context.Context) ([]domain.HealthIssue, error)
SaveJob(context.Context, domain.Job) error
GetJob(context.Context, string) (domain.Job, error)
ListJobs(context.Context, int) ([]domain.Job, error)
ListRecoverableJobs(context.Context) ([]domain.Job, error)
ReconcileInterruptedJobs(context.Context, time.Time) (int64, error)
SaveChallenge(context.Context, domain.ChallengeJournal) error
ListOpenChallenges(context.Context) ([]domain.ChallengeJournal, error)
MarkChallengeCleaned(context.Context, string, time.Time) error
AppendAudit(context.Context, domain.AuditEvent) error
ListAudit(context.Context, int) ([]domain.AuditEvent, error)
Dashboard(context.Context, time.Time) (domain.DashboardSnapshot, error)
}
type SecretStore interface {
// Put may return a non-empty reference together with an error when an
// atomic secret-file replacement committed but its final durability check
// failed. Callers must compensate that reference before abandoning metadata.
Put(context.Context, string, []byte) (string, error)
Get(context.Context, string) ([]byte, error)
Delete(context.Context, string) error
Locked() bool
Unlock(context.Context, []byte) error
Lock()
}
+412
View File
@@ -0,0 +1,412 @@
package sqlite
import (
"context"
"database/sql"
"fmt"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/store"
)
func (r *Repository) SaveACMEAccount(ctx context.Context, value domain.ACMEAccount) error {
return saveACMEAccount(ctx, r.db, value)
}
func saveACMEAccount(ctx context.Context, executor sqlExecutor, value domain.ACMEAccount) error {
_, err := executor.ExecContext(ctx, `INSERT INTO acme_accounts (
id, environment, directory_url, email, registration, secret_ref, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(environment) DO UPDATE SET id=excluded.id,
directory_url=excluded.directory_url, email=excluded.email,
registration=excluded.registration, secret_ref=excluded.secret_ref,
created_at=excluded.created_at`, value.ID, value.Environment,
value.DirectoryURL, value.Email, value.Registration, value.SecretRef,
encodeTime(value.CreatedAt))
if err != nil {
return fmt.Errorf("sqlite: save ACME account: %w", err)
}
return nil
}
func insertACMEAccount(ctx context.Context, executor sqlExecutor, value domain.ACMEAccount) error {
result, err := executor.ExecContext(ctx, `INSERT INTO acme_accounts (
id, environment, directory_url, email, registration, secret_ref, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(environment) DO NOTHING`, value.ID, value.Environment,
value.DirectoryURL, value.Email, value.Registration, value.SecretRef,
encodeTime(value.CreatedAt))
if err != nil {
return fmt.Errorf("sqlite: insert ACME account: %w", err)
}
inserted, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("sqlite: inspect ACME account insert: %w", err)
}
if inserted != 1 {
return fmt.Errorf("sqlite: %w: %s", store.ErrACMEAccountConflict, value.Environment)
}
return nil
}
// CommitACMEAccount installs account metadata and closes its secret intent in
// one FULL-synchronous SQLite transaction.
func (r *Repository) CommitACMEAccount(ctx context.Context, value domain.ACMEAccount) error {
if value.ID == "" || value.Environment == "" || value.SecretRef == "" {
return fmt.Errorf("sqlite: invalid ACME account commit")
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("sqlite: begin ACME account commit: %w", err)
}
defer func() { _ = tx.Rollback() }()
if err := insertACMEAccount(ctx, tx, value); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "DELETE FROM acme_account_commit_journal WHERE account_id = ?", value.ID); err != nil {
return fmt.Errorf("sqlite: complete ACME account commit intent: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("sqlite: commit ACME account: %w", err)
}
return nil
}
func (r *Repository) SaveACMEAccountCommitIntent(ctx context.Context, intent domain.ACMEAccountCommitIntent) error {
if intent.AccountID == "" || intent.SecretRef == "" || intent.CreatedAt.IsZero() {
return fmt.Errorf("sqlite: invalid ACME account commit intent")
}
_, err := r.db.ExecContext(ctx, `INSERT INTO acme_account_commit_journal (account_id, secret_ref, created_at)
VALUES (?, ?, ?)
ON CONFLICT(account_id) DO UPDATE SET secret_ref=excluded.secret_ref, created_at=excluded.created_at`,
intent.AccountID, intent.SecretRef, encodeTime(intent.CreatedAt))
if err != nil {
return fmt.Errorf("sqlite: save ACME account commit intent: %w", err)
}
return nil
}
func (r *Repository) ListACMEAccountCommitIntents(ctx context.Context) ([]domain.ACMEAccountCommitIntent, error) {
rows, err := r.db.QueryContext(ctx, `SELECT account_id, secret_ref, created_at
FROM acme_account_commit_journal ORDER BY created_at, account_id`)
if err != nil {
return nil, fmt.Errorf("sqlite: list ACME account commit intents: %w", err)
}
defer rows.Close()
var intents []domain.ACMEAccountCommitIntent
for rows.Next() {
var intent domain.ACMEAccountCommitIntent
var created string
if err := rows.Scan(&intent.AccountID, &intent.SecretRef, &created); err != nil {
return nil, fmt.Errorf("sqlite: scan ACME account commit intent: %w", err)
}
intent.CreatedAt, err = decodeTime(created)
if err != nil {
return nil, fmt.Errorf("sqlite: decode ACME account commit intent: %w", err)
}
intents = append(intents, intent)
}
return intents, rows.Err()
}
func (r *Repository) DeleteACMEAccountCommitIntent(ctx context.Context, accountID string) error {
if _, err := r.db.ExecContext(ctx, "DELETE FROM acme_account_commit_journal WHERE account_id = ?", accountID); err != nil {
return fmt.Errorf("sqlite: delete ACME account commit intent: %w", err)
}
return nil
}
func (r *Repository) GetACMEAccountByEnvironment(ctx context.Context, environment string) (domain.ACMEAccount, error) {
var value domain.ACMEAccount
var created string
err := r.db.QueryRowContext(ctx, `SELECT id, environment, directory_url, email,
registration, secret_ref, created_at FROM acme_accounts WHERE environment = ?`, environment).
Scan(&value.ID, &value.Environment, &value.DirectoryURL, &value.Email,
&value.Registration, &value.SecretRef, &created)
if err != nil {
return value, fmt.Errorf("sqlite: get ACME account: %w", err)
}
if value.CreatedAt, err = decodeTime(created); err != nil {
return value, fmt.Errorf("sqlite: decode ACME account: %w", err)
}
return value, nil
}
func (r *Repository) SaveCertificateLineage(ctx context.Context, value domain.CertificateLineage) error {
return saveCertificateLineage(ctx, r.db, value)
}
type sqlExecutor interface {
ExecContext(context.Context, string, ...any) (sql.Result, error)
}
func saveCertificateLineage(ctx context.Context, executor sqlExecutor, value domain.CertificateLineage) error {
identifiers, err := encodeJSON(value.Identifiers)
if err != nil {
return fmt.Errorf("sqlite: encode lineage identifiers: %w", err)
}
_, err = executor.ExecContext(ctx, `INSERT INTO certificate_lineages (
id, name, zone_id, source, identifiers_json, key_algorithm, profile,
acme_account_id, current_version_id, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET name=excluded.name, zone_id=excluded.zone_id,
source=excluded.source, identifiers_json=excluded.identifiers_json,
key_algorithm=excluded.key_algorithm, profile=excluded.profile,
acme_account_id=excluded.acme_account_id,
current_version_id=excluded.current_version_id, created_at=excluded.created_at,
updated_at=excluded.updated_at`, value.ID, value.Name, value.ZoneID,
string(value.Source), identifiers, string(value.KeyAlgorithm), value.Profile,
value.ACMEAccountID, value.CurrentVersionID, encodeTime(value.CreatedAt),
encodeTime(value.UpdatedAt))
if err != nil {
return fmt.Errorf("sqlite: save certificate lineage: %w", err)
}
return nil
}
const lineageColumns = `id, name, zone_id, source, identifiers_json, key_algorithm,
profile, acme_account_id, current_version_id, created_at, updated_at`
func scanLineage(scanner interface{ Scan(...any) error }) (domain.CertificateLineage, error) {
var value domain.CertificateLineage
var source, identifiers, algorithm, created, updated string
if err := scanner.Scan(&value.ID, &value.Name, &value.ZoneID, &source,
&identifiers, &algorithm, &value.Profile, &value.ACMEAccountID,
&value.CurrentVersionID, &created, &updated); err != nil {
return value, err
}
value.Source = domain.CertificateSource(source)
value.KeyAlgorithm = domain.KeyAlgorithm(algorithm)
if err := decodeJSON(identifiers, &value.Identifiers); err != nil {
return value, err
}
var err error
if value.CreatedAt, err = decodeTime(created); err != nil {
return value, err
}
if value.UpdatedAt, err = decodeTime(updated); err != nil {
return value, err
}
return value, nil
}
func (r *Repository) ListCertificateLineages(ctx context.Context) ([]domain.CertificateLineage, error) {
rows, err := r.db.QueryContext(ctx, "SELECT "+lineageColumns+" FROM certificate_lineages ORDER BY name COLLATE NOCASE, id")
if err != nil {
return nil, fmt.Errorf("sqlite: list certificate lineages: %w", err)
}
defer rows.Close()
values := make([]domain.CertificateLineage, 0)
for rows.Next() {
value, err := scanLineage(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan certificate lineage: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) GetCertificateLineage(ctx context.Context, id string) (domain.CertificateLineage, error) {
value, err := scanLineage(r.db.QueryRowContext(ctx, "SELECT "+lineageColumns+" FROM certificate_lineages WHERE id = ?", id))
if err != nil {
return value, fmt.Errorf("sqlite: get certificate lineage: %w", err)
}
return value, nil
}
func (r *Repository) SaveCertificateVersion(ctx context.Context, value domain.CertificateVersion) error {
return saveCertificateVersion(ctx, r.db, value)
}
func (r *Repository) SaveCertificateCommitIntent(ctx context.Context, value domain.CertificateCommitIntent) error {
if value.VersionID == "" || value.LineageID == "" || value.ArtifactPath == "" {
return fmt.Errorf("sqlite: invalid certificate commit intent")
}
_, err := r.db.ExecContext(ctx, `INSERT INTO certificate_commit_journal (
version_id, lineage_id, secret_ref, artifact_path, created_at
) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(version_id) DO UPDATE SET lineage_id=excluded.lineage_id,
secret_ref=excluded.secret_ref, artifact_path=excluded.artifact_path,
created_at=excluded.created_at`, value.VersionID, value.LineageID,
value.SecretRef, value.ArtifactPath, encodeTime(value.CreatedAt))
if err != nil {
return fmt.Errorf("sqlite: save certificate commit intent: %w", err)
}
return nil
}
func (r *Repository) ListCertificateCommitIntents(ctx context.Context) ([]domain.CertificateCommitIntent, error) {
rows, err := r.db.QueryContext(ctx, `SELECT version_id, lineage_id, secret_ref,
artifact_path, created_at FROM certificate_commit_journal ORDER BY created_at, version_id`)
if err != nil {
return nil, fmt.Errorf("sqlite: list certificate commit intents: %w", err)
}
defer rows.Close()
var values []domain.CertificateCommitIntent
for rows.Next() {
var value domain.CertificateCommitIntent
var created string
if err := rows.Scan(&value.VersionID, &value.LineageID, &value.SecretRef, &value.ArtifactPath, &created); err != nil {
return nil, fmt.Errorf("sqlite: scan certificate commit intent: %w", err)
}
value.CreatedAt, err = decodeTime(created)
if err != nil {
return nil, fmt.Errorf("sqlite: decode certificate commit intent: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) DeleteCertificateCommitIntent(ctx context.Context, versionID string) error {
if _, err := r.db.ExecContext(ctx, "DELETE FROM certificate_commit_journal WHERE version_id = ?", versionID); err != nil {
return fmt.Errorf("sqlite: delete certificate commit intent: %w", err)
}
return nil
}
func saveCertificateVersion(ctx context.Context, executor sqlExecutor, value domain.CertificateVersion) error {
identifiers, err := encodeJSON(value.Identifiers)
if err != nil {
return fmt.Errorf("sqlite: encode certificate identifiers: %w", err)
}
_, err = executor.ExecContext(ctx, `INSERT INTO certificate_versions (
id, lineage_id, serial_number, fingerprint_sha256, issuer, identifiers_json,
not_before, not_after, certificate_path, chain_path, private_key_ref,
renewal_window_start, renewal_window_end, revocation_pending_at, revoked_at,
revocation_reason, exported_at, export_path, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET lineage_id=excluded.lineage_id,
serial_number=excluded.serial_number, fingerprint_sha256=excluded.fingerprint_sha256,
issuer=excluded.issuer, identifiers_json=excluded.identifiers_json,
not_before=excluded.not_before, not_after=excluded.not_after,
certificate_path=excluded.certificate_path, chain_path=excluded.chain_path,
private_key_ref=excluded.private_key_ref,
renewal_window_start=excluded.renewal_window_start,
renewal_window_end=excluded.renewal_window_end,
revocation_pending_at=excluded.revocation_pending_at, revoked_at=excluded.revoked_at,
revocation_reason=excluded.revocation_reason, exported_at=excluded.exported_at,
export_path=excluded.export_path, created_at=excluded.created_at`,
value.ID, value.LineageID, value.SerialNumber, value.FingerprintSHA256,
value.Issuer, identifiers, encodeTime(value.NotBefore), encodeTime(value.NotAfter),
value.CertificatePath, value.ChainPath, value.PrivateKeyRef,
encodeOptionalTime(value.RenewalWindowStart), encodeOptionalTime(value.RenewalWindowEnd),
encodeOptionalTime(value.RevocationPendingAt), encodeOptionalTime(value.RevokedAt), optionalUint(value.RevocationReason),
encodeOptionalTime(value.ExportedAt), value.ExportPath, encodeTime(value.CreatedAt))
if err != nil {
return fmt.Errorf("sqlite: save certificate version: %w", err)
}
return nil
}
// CommitCertificateVersion installs a version row and advances its lineage in
// one SQLite transaction. Filesystem activation happens only after this method
// succeeds, so `current` can never point at an untracked version.
func (r *Repository) CommitCertificateVersion(ctx context.Context, lineage domain.CertificateLineage, version domain.CertificateVersion) error {
if lineage.ID == "" || version.ID == "" || version.LineageID != lineage.ID || lineage.CurrentVersionID != version.ID {
return fmt.Errorf("sqlite: invalid certificate lineage/version commit")
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("sqlite: begin certificate commit: %w", err)
}
defer func() { _ = tx.Rollback() }()
activeVersionID := lineage.CurrentVersionID
lineage.CurrentVersionID = ""
if err := saveCertificateLineage(ctx, tx, lineage); err != nil {
return err
}
if err := saveCertificateVersion(ctx, tx, version); err != nil {
return err
}
lineage.CurrentVersionID = activeVersionID
if err := saveCertificateLineage(ctx, tx, lineage); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "DELETE FROM certificate_commit_journal WHERE version_id = ?", version.ID); err != nil {
return fmt.Errorf("sqlite: complete certificate commit intent: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("sqlite: commit certificate version: %w", err)
}
return nil
}
const versionColumns = `id, lineage_id, serial_number, fingerprint_sha256, issuer,
identifiers_json, not_before, not_after, certificate_path, chain_path,
private_key_ref, renewal_window_start, renewal_window_end, revocation_pending_at,
revoked_at, revocation_reason, exported_at,
export_path, created_at`
func scanVersion(scanner interface{ Scan(...any) error }) (domain.CertificateVersion, error) {
var value domain.CertificateVersion
var identifiers, notBefore, notAfter, created string
var renewalStart, renewalEnd, revocationPending, revoked, exported sql.NullString
var revocationReason sql.NullInt64
if err := scanner.Scan(&value.ID, &value.LineageID, &value.SerialNumber,
&value.FingerprintSHA256, &value.Issuer, &identifiers, &notBefore, &notAfter,
&value.CertificatePath, &value.ChainPath, &value.PrivateKeyRef, &renewalStart,
&renewalEnd, &revocationPending, &revoked, &revocationReason, &exported, &value.ExportPath, &created); err != nil {
return value, err
}
if err := decodeJSON(identifiers, &value.Identifiers); err != nil {
return value, err
}
var err error
if value.NotBefore, err = decodeTime(notBefore); err != nil {
return value, err
}
if value.NotAfter, err = decodeTime(notAfter); err != nil {
return value, err
}
if value.CreatedAt, err = decodeTime(created); err != nil {
return value, err
}
if value.RenewalWindowStart, err = decodeOptionalTime(renewalStart); err != nil {
return value, err
}
if value.RenewalWindowEnd, err = decodeOptionalTime(renewalEnd); err != nil {
return value, err
}
if value.RevocationPendingAt, err = decodeOptionalTime(revocationPending); err != nil {
return value, err
}
if value.RevokedAt, err = decodeOptionalTime(revoked); err != nil {
return value, err
}
if revocationReason.Valid {
reason := uint(revocationReason.Int64)
value.RevocationReason = &reason
}
if value.ExportedAt, err = decodeOptionalTime(exported); err != nil {
return value, err
}
return value, nil
}
func optionalUint(value *uint) any {
if value == nil {
return nil
}
return int64(*value)
}
func (r *Repository) ListCertificateVersions(ctx context.Context, lineageID string) ([]domain.CertificateVersion, error) {
rows, err := r.db.QueryContext(ctx, "SELECT "+versionColumns+` FROM certificate_versions
WHERE lineage_id = ? ORDER BY created_at DESC, id`, lineageID)
if err != nil {
return nil, fmt.Errorf("sqlite: list certificate versions: %w", err)
}
defer rows.Close()
values := make([]domain.CertificateVersion, 0)
for rows.Next() {
value, err := scanVersion(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan certificate version: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
+70
View File
@@ -0,0 +1,70 @@
package sqlite
import (
"database/sql"
"encoding/json"
"fmt"
"time"
)
func encodeTime(t time.Time) string {
return t.UTC().Format(time.RFC3339Nano)
}
func encodeOptionalTime(t *time.Time) any {
if t == nil {
return nil
}
return encodeTime(*t)
}
func decodeTime(raw string) (time.Time, error) {
t, err := time.Parse(time.RFC3339Nano, raw)
if err != nil {
return time.Time{}, fmt.Errorf("decode time %q: %w", raw, err)
}
return t, nil
}
func decodeOptionalTime(raw sql.NullString) (*time.Time, error) {
if !raw.Valid {
return nil, nil
}
t, err := decodeTime(raw.String)
if err != nil {
return nil, err
}
return &t, nil
}
func encodeJSON(value any) (string, error) {
b, err := json.Marshal(value)
if err != nil {
return "", err
}
return string(b), nil
}
func decodeJSON(raw string, target any) error {
if raw == "" {
raw = "null"
}
if err := json.Unmarshal([]byte(raw), target); err != nil {
return fmt.Errorf("decode JSON: %w", err)
}
return nil
}
func rawOrNil(raw []byte) any {
if len(raw) == 0 {
return nil
}
return raw
}
func copyRaw(raw []byte) []byte {
if len(raw) == 0 {
return nil
}
return append([]byte(nil), raw...)
}
+174
View File
@@ -0,0 +1,174 @@
package sqlite
import (
"context"
"database/sql"
"fmt"
"math"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
type sqlExecer interface {
ExecContext(context.Context, string, ...any) (sql.Result, error)
}
func saveDNSRecord(ctx context.Context, exec sqlExecer, value domain.DNSRecord) error {
tags, err := encodeJSON(value.Tags)
if err != nil {
return fmt.Errorf("encode tags: %w", err)
}
var priority any
if value.Priority != nil {
priority = int64(*value.Priority)
}
_, err = exec.ExecContext(ctx, `INSERT INTO dns_records (
id, provider_id, zone_id, type, name, unicode_name, content, priority,
ttl, proxied, proxiable, comment, tags_json, managed, data_json, raw_json,
modified_at, last_synced_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET provider_id=excluded.provider_id,
zone_id=excluded.zone_id, type=excluded.type, name=excluded.name,
unicode_name=excluded.unicode_name, content=excluded.content,
priority=excluded.priority, ttl=excluded.ttl, proxied=excluded.proxied,
proxiable=excluded.proxiable, comment=excluded.comment, tags_json=excluded.tags_json,
managed=excluded.managed, data_json=excluded.data_json, raw_json=excluded.raw_json,
modified_at=excluded.modified_at, last_synced_at=excluded.last_synced_at`,
value.ID, value.ProviderID, value.ZoneID, string(value.Type), value.Name,
value.UnicodeName, value.Content, priority, value.TTL, value.Proxied,
value.Proxiable, value.Comment, tags, value.Managed, rawOrNil(value.Data),
rawOrNil(value.Raw), encodeOptionalTime(value.ModifiedAt), encodeOptionalTime(value.LastSyncedAt))
return err
}
func (r *Repository) ReplaceDNSRecords(ctx context.Context, zoneID string, values []domain.DNSRecord, syncedAt time.Time) error {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("sqlite: begin DNS replacement: %w", err)
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "DELETE FROM dns_records WHERE zone_id = ?", zoneID); err != nil {
return fmt.Errorf("sqlite: clear DNS records: %w", err)
}
for _, value := range values {
if value.ZoneID != zoneID {
return fmt.Errorf("sqlite: DNS record %s belongs to zone %s, expected %s", value.ID, value.ZoneID, zoneID)
}
value.LastSyncedAt = &syncedAt
if err := saveDNSRecord(ctx, tx, value); err != nil {
return fmt.Errorf("sqlite: replace DNS record %s: %w", value.ID, err)
}
}
if _, err := tx.ExecContext(ctx, `INSERT INTO zone_dns_sync(zone_id, synced_at) VALUES (?, ?)
ON CONFLICT(zone_id) DO UPDATE SET synced_at=excluded.synced_at`, zoneID, encodeTime(syncedAt)); err != nil {
return fmt.Errorf("sqlite: save DNS sync time: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("sqlite: commit DNS replacement: %w", err)
}
return nil
}
const dnsColumns = `id, provider_id, zone_id, type, name, unicode_name, content,
priority, ttl, proxied, proxiable, comment, tags_json, managed, data_json,
raw_json, modified_at, last_synced_at`
func scanDNSRecord(scanner interface{ Scan(...any) error }) (domain.DNSRecord, error) {
var value domain.DNSRecord
var recordType, tags string
var priority sql.NullInt64
var data, raw []byte
var modified, synced sql.NullString
if err := scanner.Scan(&value.ID, &value.ProviderID, &value.ZoneID, &recordType,
&value.Name, &value.UnicodeName, &value.Content, &priority, &value.TTL,
&value.Proxied, &value.Proxiable, &value.Comment, &tags, &value.Managed,
&data, &raw, &modified, &synced); err != nil {
return value, err
}
value.Type = domain.RecordType(recordType)
if priority.Valid {
if priority.Int64 < 0 || priority.Int64 > math.MaxUint16 {
return value, fmt.Errorf("invalid DNS priority %d", priority.Int64)
}
converted := uint16(priority.Int64)
value.Priority = &converted
}
if err := decodeJSON(tags, &value.Tags); err != nil {
return value, err
}
value.Data = copyRaw(data)
value.Raw = copyRaw(raw)
var err error
if value.ModifiedAt, err = decodeOptionalTime(modified); err != nil {
return value, err
}
if value.LastSyncedAt, err = decodeOptionalTime(synced); err != nil {
return value, err
}
return value, nil
}
func (r *Repository) ListDNSRecords(ctx context.Context, zoneID string) ([]domain.DNSRecord, error) {
rows, err := r.db.QueryContext(ctx, "SELECT "+dnsColumns+` FROM dns_records
WHERE zone_id = ? ORDER BY name COLLATE NOCASE, type, id`, zoneID)
if err != nil {
return nil, fmt.Errorf("sqlite: list DNS records: %w", err)
}
defer rows.Close()
values := make([]domain.DNSRecord, 0)
for rows.Next() {
value, err := scanDNSRecord(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan DNS record: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) SaveDNSRecord(ctx context.Context, value domain.DNSRecord) error {
if err := saveDNSRecord(ctx, r.db, value); err != nil {
return fmt.Errorf("sqlite: save DNS record: %w", err)
}
return nil
}
func (r *Repository) DeleteDNSRecord(ctx context.Context, id string) error {
if _, err := r.db.ExecContext(ctx, "DELETE FROM dns_records WHERE id = ?", id); err != nil {
return fmt.Errorf("sqlite: delete DNS record: %w", err)
}
return nil
}
func (r *Repository) SaveTLSSettings(ctx context.Context, value domain.EdgeTLSSettings) error {
_, err := r.db.ExecContext(ctx, `INSERT INTO tls_settings (
zone_id, mode, always_use_https, minimum_tls, tls_1_3, has_proxied_dns, last_synced_at
) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(zone_id) DO UPDATE SET mode=excluded.mode,
always_use_https=excluded.always_use_https, minimum_tls=excluded.minimum_tls,
tls_1_3=excluded.tls_1_3, has_proxied_dns=excluded.has_proxied_dns,
last_synced_at=excluded.last_synced_at`, value.ZoneID, value.Mode,
value.AlwaysUseHTTPS, value.MinimumTLS, value.TLS13, value.HasProxiedDNS,
encodeOptionalTime(value.LastSyncedAt))
if err != nil {
return fmt.Errorf("sqlite: save TLS settings: %w", err)
}
return nil
}
func (r *Repository) GetTLSSettings(ctx context.Context, zoneID string) (domain.EdgeTLSSettings, error) {
var value domain.EdgeTLSSettings
var synced sql.NullString
err := r.db.QueryRowContext(ctx, `SELECT zone_id, mode, always_use_https, minimum_tls,
tls_1_3, has_proxied_dns, last_synced_at FROM tls_settings WHERE zone_id = ?`, zoneID).
Scan(&value.ZoneID, &value.Mode, &value.AlwaysUseHTTPS, &value.MinimumTLS,
&value.TLS13, &value.HasProxiedDNS, &synced)
if err != nil {
return value, fmt.Errorf("sqlite: get TLS settings: %w", err)
}
if value.LastSyncedAt, err = decodeOptionalTime(synced); err != nil {
return value, fmt.Errorf("sqlite: decode TLS settings: %w", err)
}
return value, nil
}
+316
View File
@@ -0,0 +1,316 @@
package sqlite
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
func (r *Repository) SaveCredential(ctx context.Context, value domain.Credential) error {
capabilities, err := encodeJSON(value.Capabilities)
if err != nil {
return fmt.Errorf("sqlite: encode credential capabilities: %w", err)
}
_, err = r.db.ExecContext(ctx, `INSERT INTO credentials (
id, provider, label, kind, account_hint, secret_ref, status, capabilities_json,
created_at, last_verified_at, last_error
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
provider=excluded.provider, label=excluded.label, kind=excluded.kind,
account_hint=excluded.account_hint, secret_ref=excluded.secret_ref,
status=excluded.status, capabilities_json=excluded.capabilities_json,
created_at=excluded.created_at, last_verified_at=excluded.last_verified_at,
last_error=excluded.last_error`,
value.ID, value.Provider, value.Label, string(value.Kind), value.AccountHint,
value.SecretRef, string(value.Status), capabilities, encodeTime(value.CreatedAt),
encodeOptionalTime(value.LastVerifiedAt), value.LastError)
if err != nil {
return fmt.Errorf("sqlite: save credential: %w", err)
}
return nil
}
func scanCredential(scanner interface{ Scan(...any) error }) (domain.Credential, error) {
var value domain.Credential
var kind, status, capabilities, created string
var verified sql.NullString
if err := scanner.Scan(&value.ID, &value.Provider, &value.Label, &kind, &value.AccountHint,
&value.SecretRef, &status, &capabilities, &created, &verified, &value.LastError); err != nil {
return value, err
}
value.Kind = domain.CredentialKind(kind)
value.Status = domain.CredentialStatus(status)
if err := decodeJSON(capabilities, &value.Capabilities); err != nil {
return value, err
}
var err error
if value.CreatedAt, err = decodeTime(created); err != nil {
return value, err
}
if value.LastVerifiedAt, err = decodeOptionalTime(verified); err != nil {
return value, err
}
return value, nil
}
const credentialColumns = `id, provider, label, kind, account_hint, secret_ref, status,
capabilities_json, created_at, last_verified_at, last_error`
func (r *Repository) ListCredentials(ctx context.Context) ([]domain.Credential, error) {
rows, err := r.db.QueryContext(ctx, "SELECT "+credentialColumns+" FROM credentials ORDER BY label COLLATE NOCASE, id")
if err != nil {
return nil, fmt.Errorf("sqlite: list credentials: %w", err)
}
defer rows.Close()
values := make([]domain.Credential, 0)
for rows.Next() {
value, err := scanCredential(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan credential: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) GetCredential(ctx context.Context, id string) (domain.Credential, error) {
value, err := scanCredential(r.db.QueryRowContext(ctx, "SELECT "+credentialColumns+" FROM credentials WHERE id = ?", id))
if err != nil {
return value, fmt.Errorf("sqlite: get credential: %w", err)
}
return value, nil
}
func (r *Repository) DeleteCredential(ctx context.Context, id string) error {
if _, err := r.db.ExecContext(ctx, "DELETE FROM credentials WHERE id = ?", id); err != nil {
return fmt.Errorf("sqlite: delete credential: %w", err)
}
return nil
}
func (r *Repository) SaveCredentialZoneCapability(ctx context.Context, credentialID, zoneID, capability string, observedAt time.Time) error {
_, err := r.db.ExecContext(ctx, `INSERT INTO credential_zone_capabilities (
credential_id, zone_id, capability, observed_at
) VALUES (?, ?, ?, ?)
ON CONFLICT(credential_id, zone_id, capability) DO UPDATE SET observed_at=excluded.observed_at`,
credentialID, zoneID, capability, encodeTime(observedAt))
if err != nil {
return fmt.Errorf("sqlite: save credential zone capability: %w", err)
}
return nil
}
func (r *Repository) HasCredentialZoneCapability(ctx context.Context, credentialID, zoneID, capability string) (bool, error) {
var exists bool
err := r.db.QueryRowContext(ctx, `SELECT EXISTS (
SELECT 1 FROM credential_zone_capabilities
WHERE credential_id = ? AND zone_id = ? AND capability = ?
)`, credentialID, zoneID, capability).Scan(&exists)
if err != nil {
return false, fmt.Errorf("sqlite: get credential zone capability: %w", err)
}
return exists, nil
}
func (r *Repository) GetCredentialZoneCapability(ctx context.Context, credentialID, zoneID, capability string) (time.Time, bool, error) {
var observedRaw string
err := r.db.QueryRowContext(ctx, `SELECT observed_at FROM credential_zone_capabilities
WHERE credential_id = ? AND zone_id = ? AND capability = ?`, credentialID, zoneID, capability).Scan(&observedRaw)
if errors.Is(err, sql.ErrNoRows) {
return time.Time{}, false, nil
}
if err != nil {
return time.Time{}, false, fmt.Errorf("sqlite: get credential zone capability observation: %w", err)
}
observedAt, err := decodeTime(observedRaw)
if err != nil {
return time.Time{}, false, fmt.Errorf("sqlite: decode credential zone capability observation: %w", err)
}
return observedAt, true, nil
}
// InvalidateCredentialZoneCapability atomically removes exact per-zone
// authority and detaches the credential if it currently owns that route. The
// transaction prevents a crash between those two fail-closed state changes.
func (r *Repository) InvalidateCredentialZoneCapability(ctx context.Context, credentialID, zoneID, capability string) error {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("sqlite: begin credential zone capability invalidation: %w", err)
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `DELETE FROM credential_zone_capabilities
WHERE credential_id = ? AND zone_id = ? AND capability = ?`, credentialID, zoneID, capability); err != nil {
return fmt.Errorf("sqlite: delete credential zone capability: %w", err)
}
if capability == "dns:read" {
if _, err := tx.ExecContext(ctx, `UPDATE zones SET preferred_credential_id = ''
WHERE id = ? AND preferred_credential_id = ?`, zoneID, credentialID); err != nil {
return fmt.Errorf("sqlite: detach invalid zone credential: %w", err)
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("sqlite: commit credential zone capability invalidation: %w", err)
}
return nil
}
func (r *Repository) SaveAccounts(ctx context.Context, accounts []domain.RemoteAccount, links []domain.AccountCredential) error {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("sqlite: begin account save: %w", err)
}
defer tx.Rollback()
for _, value := range accounts {
if _, err := tx.ExecContext(ctx, `INSERT INTO accounts (
id, provider, provider_id, name, created_at, last_synced_at
) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET provider=excluded.provider,
provider_id=excluded.provider_id, name=excluded.name,
created_at=excluded.created_at, last_synced_at=excluded.last_synced_at`,
value.ID, value.Provider, value.ProviderID, value.Name, encodeTime(value.CreatedAt),
encodeOptionalTime(value.LastSyncedAt)); err != nil {
return fmt.Errorf("sqlite: save account %s: %w", value.ID, err)
}
}
for _, value := range links {
if value.Preferred {
if _, err := tx.ExecContext(ctx, "UPDATE account_credentials SET preferred = 0 WHERE account_id = ?", value.AccountID); err != nil {
return fmt.Errorf("sqlite: reset preferred account credential: %w", err)
}
}
if _, err := tx.ExecContext(ctx, `INSERT INTO account_credentials(account_id, credential_id, preferred)
VALUES (?, ?, ?)
ON CONFLICT(account_id, credential_id) DO UPDATE SET preferred =
CASE WHEN excluded.preferred = 1 THEN 1 ELSE account_credentials.preferred END`,
value.AccountID, value.CredentialID, value.Preferred); err != nil {
return fmt.Errorf("sqlite: save account credential: %w", err)
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("sqlite: commit account save: %w", err)
}
return nil
}
func scanAccount(scanner interface{ Scan(...any) error }) (domain.RemoteAccount, error) {
var value domain.RemoteAccount
var created string
var synced sql.NullString
if err := scanner.Scan(&value.ID, &value.Provider, &value.ProviderID, &value.Name, &created, &synced); err != nil {
return value, err
}
var err error
if value.CreatedAt, err = decodeTime(created); err != nil {
return value, err
}
if value.LastSyncedAt, err = decodeOptionalTime(synced); err != nil {
return value, err
}
return value, nil
}
func (r *Repository) ListAccounts(ctx context.Context) ([]domain.RemoteAccount, error) {
rows, err := r.db.QueryContext(ctx, `SELECT id, provider, provider_id, name, created_at, last_synced_at
FROM accounts ORDER BY name COLLATE NOCASE, id`)
if err != nil {
return nil, fmt.Errorf("sqlite: list accounts: %w", err)
}
defer rows.Close()
values := make([]domain.RemoteAccount, 0)
for rows.Next() {
value, err := scanAccount(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan account: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) SaveZones(ctx context.Context, zones []domain.Zone) error {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("sqlite: begin zone save: %w", err)
}
defer tx.Rollback()
for _, value := range zones {
servers, err := encodeJSON(value.NameServers)
if err != nil {
return fmt.Errorf("sqlite: encode zone name servers: %w", err)
}
if _, err := tx.ExecContext(ctx, `INSERT INTO zones (
id, provider, provider_id, account_id, preferred_credential_id, name,
unicode_name, status, paused, plan, name_servers_json, modified_at, last_synced_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET provider=excluded.provider,
provider_id=excluded.provider_id, account_id=excluded.account_id,
preferred_credential_id=excluded.preferred_credential_id, name=excluded.name,
unicode_name=excluded.unicode_name, status=excluded.status, paused=excluded.paused,
plan=excluded.plan, name_servers_json=excluded.name_servers_json,
modified_at=excluded.modified_at, last_synced_at=excluded.last_synced_at`,
value.ID, value.Provider, value.ProviderID, value.AccountID, value.PreferredCredentialID,
value.Name, value.UnicodeName, string(value.Status), value.Paused, value.Plan,
servers, encodeOptionalTime(value.ModifiedAt), encodeOptionalTime(value.LastSyncedAt)); err != nil {
return fmt.Errorf("sqlite: save zone %s: %w", value.ID, err)
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("sqlite: commit zone save: %w", err)
}
return nil
}
const zoneColumns = `id, provider, provider_id, account_id, preferred_credential_id, name,
unicode_name, status, paused, plan, name_servers_json, modified_at, last_synced_at`
func scanZone(scanner interface{ Scan(...any) error }) (domain.Zone, error) {
var value domain.Zone
var status, servers string
var modified, synced sql.NullString
if err := scanner.Scan(&value.ID, &value.Provider, &value.ProviderID, &value.AccountID,
&value.PreferredCredentialID, &value.Name, &value.UnicodeName, &status, &value.Paused,
&value.Plan, &servers, &modified, &synced); err != nil {
return value, err
}
value.Status = domain.ZoneStatus(status)
if err := decodeJSON(servers, &value.NameServers); err != nil {
return value, err
}
var err error
if value.ModifiedAt, err = decodeOptionalTime(modified); err != nil {
return value, err
}
if value.LastSyncedAt, err = decodeOptionalTime(synced); err != nil {
return value, err
}
return value, nil
}
func (r *Repository) ListZones(ctx context.Context) ([]domain.Zone, error) {
rows, err := r.db.QueryContext(ctx, "SELECT "+zoneColumns+" FROM zones ORDER BY name COLLATE NOCASE, id")
if err != nil {
return nil, fmt.Errorf("sqlite: list zones: %w", err)
}
defer rows.Close()
values := make([]domain.Zone, 0)
for rows.Next() {
value, err := scanZone(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan zone: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) GetZone(ctx context.Context, id string) (domain.Zone, error) {
value, err := scanZone(r.db.QueryRowContext(ctx, "SELECT "+zoneColumns+" FROM zones WHERE id = ?", id))
if err != nil {
return value, fmt.Errorf("sqlite: get zone: %w", err)
}
return value, nil
}
@@ -0,0 +1,209 @@
CREATE TABLE credentials (
id TEXT PRIMARY KEY,
provider TEXT NOT NULL,
label TEXT NOT NULL,
kind TEXT NOT NULL,
account_hint TEXT NOT NULL DEFAULT '',
secret_ref TEXT NOT NULL,
status TEXT NOT NULL,
capabilities_json TEXT NOT NULL DEFAULT '[]',
created_at TEXT NOT NULL,
last_verified_at TEXT,
last_error TEXT NOT NULL DEFAULT ''
);
CREATE TABLE accounts (
id TEXT PRIMARY KEY,
provider TEXT NOT NULL,
provider_id TEXT NOT NULL,
name TEXT NOT NULL,
created_at TEXT NOT NULL,
last_synced_at TEXT,
UNIQUE(provider, provider_id)
);
CREATE TABLE account_credentials (
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
credential_id TEXT NOT NULL REFERENCES credentials(id) ON DELETE CASCADE,
preferred INTEGER NOT NULL DEFAULT 0 CHECK (preferred IN (0, 1)),
PRIMARY KEY (account_id, credential_id)
);
CREATE INDEX account_credentials_credential_idx ON account_credentials(credential_id);
CREATE TABLE zones (
id TEXT PRIMARY KEY,
provider TEXT NOT NULL,
provider_id TEXT NOT NULL,
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
preferred_credential_id TEXT NOT NULL,
name TEXT NOT NULL,
unicode_name TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL,
paused INTEGER NOT NULL DEFAULT 0 CHECK (paused IN (0, 1)),
plan TEXT NOT NULL DEFAULT '',
name_servers_json TEXT NOT NULL DEFAULT '[]',
modified_at TEXT,
last_synced_at TEXT,
UNIQUE(provider, provider_id)
);
CREATE INDEX zones_account_idx ON zones(account_id);
CREATE INDEX zones_name_idx ON zones(name);
CREATE TABLE dns_records (
id TEXT PRIMARY KEY,
provider_id TEXT NOT NULL,
zone_id TEXT NOT NULL REFERENCES zones(id) ON DELETE CASCADE,
type TEXT NOT NULL,
name TEXT NOT NULL,
unicode_name TEXT NOT NULL DEFAULT '',
content TEXT NOT NULL DEFAULT '',
priority INTEGER,
ttl INTEGER NOT NULL,
proxied INTEGER NOT NULL DEFAULT 0 CHECK (proxied IN (0, 1)),
proxiable INTEGER NOT NULL DEFAULT 0 CHECK (proxiable IN (0, 1)),
comment TEXT NOT NULL DEFAULT '',
tags_json TEXT NOT NULL DEFAULT '[]',
managed INTEGER NOT NULL DEFAULT 0 CHECK (managed IN (0, 1)),
data_json BLOB,
raw_json BLOB,
modified_at TEXT,
last_synced_at TEXT,
UNIQUE(zone_id, provider_id)
);
CREATE INDEX dns_records_zone_idx ON dns_records(zone_id);
CREATE INDEX dns_records_lookup_idx ON dns_records(zone_id, name, type);
CREATE TABLE zone_dns_sync (
zone_id TEXT PRIMARY KEY REFERENCES zones(id) ON DELETE CASCADE,
synced_at TEXT NOT NULL
);
CREATE TABLE tls_settings (
zone_id TEXT PRIMARY KEY REFERENCES zones(id) ON DELETE CASCADE,
mode TEXT NOT NULL,
always_use_https INTEGER NOT NULL DEFAULT 0 CHECK (always_use_https IN (0, 1)),
minimum_tls TEXT NOT NULL,
tls_1_3 INTEGER NOT NULL DEFAULT 0 CHECK (tls_1_3 IN (0, 1)),
has_proxied_dns INTEGER NOT NULL DEFAULT 0 CHECK (has_proxied_dns IN (0, 1)),
last_synced_at TEXT
);
CREATE TABLE acme_accounts (
id TEXT PRIMARY KEY,
environment TEXT NOT NULL UNIQUE,
directory_url TEXT NOT NULL,
email TEXT NOT NULL,
registration TEXT NOT NULL,
secret_ref TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE certificate_lineages (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
zone_id TEXT,
source TEXT NOT NULL,
identifiers_json TEXT NOT NULL,
key_algorithm TEXT NOT NULL,
profile TEXT NOT NULL,
acme_account_id TEXT,
current_version_id TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX certificate_lineages_zone_idx ON certificate_lineages(zone_id);
CREATE TABLE certificate_versions (
id TEXT PRIMARY KEY,
lineage_id TEXT NOT NULL REFERENCES certificate_lineages(id) ON DELETE CASCADE,
serial_number TEXT NOT NULL,
fingerprint_sha256 TEXT NOT NULL,
issuer TEXT NOT NULL,
identifiers_json TEXT NOT NULL,
not_before TEXT NOT NULL,
not_after TEXT NOT NULL,
certificate_path TEXT NOT NULL,
chain_path TEXT NOT NULL DEFAULT '',
private_key_ref TEXT NOT NULL,
renewal_window_start TEXT,
renewal_window_end TEXT,
exported_at TEXT,
export_path TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL
);
CREATE INDEX certificate_versions_lineage_idx ON certificate_versions(lineage_id, created_at DESC);
CREATE INDEX certificate_versions_expiry_idx ON certificate_versions(not_after);
CREATE TABLE endpoints (
id TEXT PRIMARY KEY,
zone_id TEXT NOT NULL REFERENCES zones(id) ON DELETE CASCADE,
host TEXT NOT NULL,
port INTEGER NOT NULL CHECK (port > 0 AND port <= 65535),
enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1)),
last_checked_at TEXT,
resolved_addresses_json TEXT NOT NULL DEFAULT '[]',
fingerprint_sha256 TEXT NOT NULL DEFAULT '',
issuer TEXT NOT NULL DEFAULT '',
not_after TEXT,
valid_for_host INTEGER NOT NULL DEFAULT 0 CHECK (valid_for_host IN (0, 1)),
trusted INTEGER NOT NULL DEFAULT 0 CHECK (trusted IN (0, 1)),
last_error TEXT NOT NULL DEFAULT '',
UNIQUE(host, port)
);
CREATE INDEX endpoints_zone_idx ON endpoints(zone_id);
CREATE TABLE health_issues (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL,
severity TEXT NOT NULL,
kind TEXT NOT NULL,
resource_id TEXT NOT NULL,
title TEXT NOT NULL,
detail TEXT NOT NULL,
action TEXT NOT NULL DEFAULT '',
observed_at TEXT NOT NULL
);
CREATE INDEX health_issues_owner_idx ON health_issues(owner_id);
CREATE INDEX health_issues_order_idx ON health_issues(severity, observed_at DESC);
CREATE TABLE jobs (
id TEXT PRIMARY KEY,
kind TEXT NOT NULL,
state TEXT NOT NULL,
resource_id TEXT NOT NULL DEFAULT '',
progress INTEGER NOT NULL DEFAULT 0 CHECK (progress >= 0 AND progress <= 100),
message TEXT NOT NULL DEFAULT '',
payload_json BLOB,
error TEXT NOT NULL DEFAULT '',
retry_at TEXT,
created_at TEXT NOT NULL,
started_at TEXT,
finished_at TEXT,
updated_at TEXT NOT NULL
);
CREATE INDEX jobs_updated_idx ON jobs(updated_at DESC);
CREATE INDEX jobs_recoverable_idx ON jobs(state, retry_at, updated_at);
CREATE TABLE challenge_journal (
id TEXT PRIMARY KEY,
job_id TEXT NOT NULL,
zone_id TEXT NOT NULL,
record_id TEXT NOT NULL,
fqdn TEXT NOT NULL,
value_hash TEXT NOT NULL,
created_at TEXT NOT NULL,
cleaned_at TEXT
);
CREATE INDEX challenge_journal_open_idx ON challenge_journal(cleaned_at, created_at);
CREATE INDEX challenge_journal_job_idx ON challenge_journal(job_id);
CREATE TABLE audit_events (
id TEXT PRIMARY KEY,
actor TEXT NOT NULL,
action TEXT NOT NULL,
resource_id TEXT NOT NULL DEFAULT '',
before_json BLOB,
after_json BLOB,
created_at TEXT NOT NULL
);
CREATE INDEX audit_events_created_idx ON audit_events(created_at DESC);
@@ -0,0 +1 @@
ALTER TABLE challenge_journal ADD COLUMN credential_id TEXT NOT NULL DEFAULT '';
@@ -0,0 +1,2 @@
ALTER TABLE certificate_versions ADD COLUMN revoked_at TEXT;
ALTER TABLE certificate_versions ADD COLUMN revocation_reason INTEGER;
@@ -0,0 +1 @@
ALTER TABLE certificate_versions ADD COLUMN revocation_pending_at TEXT;
@@ -0,0 +1,9 @@
CREATE TABLE credential_zone_capabilities (
credential_id TEXT NOT NULL REFERENCES credentials(id) ON DELETE CASCADE,
zone_id TEXT NOT NULL REFERENCES zones(id) ON DELETE CASCADE,
capability TEXT NOT NULL,
observed_at TEXT NOT NULL,
PRIMARY KEY (credential_id, zone_id, capability)
);
CREATE INDEX credential_zone_capabilities_zone_idx
ON credential_zone_capabilities(zone_id, capability);
@@ -0,0 +1,9 @@
CREATE TABLE certificate_commit_journal (
version_id TEXT PRIMARY KEY,
lineage_id TEXT NOT NULL,
secret_ref TEXT NOT NULL DEFAULT '',
artifact_path TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX certificate_commit_journal_created_idx
ON certificate_commit_journal(created_at);
@@ -0,0 +1,7 @@
CREATE TABLE acme_account_commit_journal (
account_id TEXT PRIMARY KEY,
secret_ref TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX acme_account_commit_journal_created_idx
ON acme_account_commit_journal(created_at);
@@ -0,0 +1,29 @@
-- Older development schemas did not enforce the physical endpoint identity.
-- Retain the most useful observation, remove duplicate-owned stale health
-- issues, and then make host+port safe for ON CONFLICT routing reassignment.
CREATE TEMP TABLE endpoint_deduplication AS
SELECT id AS duplicate_id, keeper_id
FROM (
SELECT id,
FIRST_VALUE(id) OVER (
PARTITION BY host, port
ORDER BY enabled DESC,
CASE WHEN last_checked_at IS NULL THEN 1 ELSE 0 END,
last_checked_at DESC,
id
) AS keeper_id
FROM endpoints
)
WHERE id <> keeper_id;
DELETE FROM health_issues
WHERE owner_id IN (SELECT duplicate_id FROM endpoint_deduplication)
OR resource_id IN (SELECT duplicate_id FROM endpoint_deduplication);
DELETE FROM endpoints
WHERE id IN (SELECT duplicate_id FROM endpoint_deduplication);
CREATE UNIQUE INDEX IF NOT EXISTS endpoints_host_port_unique_idx
ON endpoints(host, port);
DROP TABLE endpoint_deduplication;
+476
View File
@@ -0,0 +1,476 @@
package sqlite
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
func (r *Repository) SaveEndpoint(ctx context.Context, value domain.ObservedEndpoint) error {
addresses, err := encodeJSON(value.ResolvedAddresses)
if err != nil {
return fmt.Errorf("sqlite: encode endpoint addresses: %w", err)
}
_, err = r.db.ExecContext(ctx, `INSERT INTO endpoints (
id, zone_id, host, port, enabled, last_checked_at, resolved_addresses_json,
fingerprint_sha256, issuer, not_after, valid_for_host, trusted, last_error
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET zone_id=excluded.zone_id, host=excluded.host,
port=excluded.port, enabled=excluded.enabled,
last_checked_at=excluded.last_checked_at,
resolved_addresses_json=excluded.resolved_addresses_json,
fingerprint_sha256=excluded.fingerprint_sha256, issuer=excluded.issuer,
not_after=excluded.not_after, valid_for_host=excluded.valid_for_host,
trusted=excluded.trusted, last_error=excluded.last_error
ON CONFLICT(host, port) DO UPDATE SET zone_id=excluded.zone_id,
enabled=excluded.enabled, last_checked_at=excluded.last_checked_at,
resolved_addresses_json=excluded.resolved_addresses_json,
fingerprint_sha256=excluded.fingerprint_sha256, issuer=excluded.issuer,
not_after=excluded.not_after, valid_for_host=excluded.valid_for_host,
trusted=excluded.trusted, last_error=excluded.last_error`,
value.ID, value.ZoneID, value.Host, value.Port, value.Enabled,
encodeOptionalTime(value.LastCheckedAt), addresses, value.FingerprintSHA256,
value.Issuer, encodeOptionalTime(value.NotAfter), value.ValidForHost,
value.Trusted, value.LastError)
if err != nil {
return fmt.Errorf("sqlite: save endpoint: %w", err)
}
return nil
}
func scanEndpoint(scanner interface{ Scan(...any) error }) (domain.ObservedEndpoint, error) {
var value domain.ObservedEndpoint
var checked, notAfter sql.NullString
var addresses string
if err := scanner.Scan(&value.ID, &value.ZoneID, &value.Host, &value.Port,
&value.Enabled, &checked, &addresses, &value.FingerprintSHA256, &value.Issuer,
&notAfter, &value.ValidForHost, &value.Trusted, &value.LastError); err != nil {
return value, err
}
if err := decodeJSON(addresses, &value.ResolvedAddresses); err != nil {
return value, err
}
var err error
if value.LastCheckedAt, err = decodeOptionalTime(checked); err != nil {
return value, err
}
if value.NotAfter, err = decodeOptionalTime(notAfter); err != nil {
return value, err
}
return value, nil
}
const endpointColumns = `id, zone_id, host, port, enabled, last_checked_at,
resolved_addresses_json, fingerprint_sha256, issuer, not_after,
valid_for_host, trusted, last_error`
func (r *Repository) ListEndpoints(ctx context.Context) ([]domain.ObservedEndpoint, error) {
rows, err := r.db.QueryContext(ctx, "SELECT "+endpointColumns+" FROM endpoints ORDER BY host COLLATE NOCASE, port, id")
if err != nil {
return nil, fmt.Errorf("sqlite: list endpoints: %w", err)
}
defer rows.Close()
values := make([]domain.ObservedEndpoint, 0)
for rows.Next() {
value, err := scanEndpoint(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan endpoint: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) SaveHealthIssues(ctx context.Context, ownerID string, values []domain.HealthIssue) error {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("sqlite: begin health replacement: %w", err)
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "DELETE FROM health_issues WHERE owner_id = ?", ownerID); err != nil {
return fmt.Errorf("sqlite: clear health issues: %w", err)
}
for _, value := range values {
if _, err := tx.ExecContext(ctx, `INSERT INTO health_issues (
id, owner_id, severity, kind, resource_id, title, detail, action, observed_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, value.ID, ownerID,
string(value.Severity), value.Kind, value.ResourceID, value.Title,
value.Detail, value.Action, encodeTime(value.ObservedAt)); err != nil {
return fmt.Errorf("sqlite: save health issue %s: %w", value.ID, err)
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("sqlite: commit health replacement: %w", err)
}
return nil
}
func scanHealthIssue(scanner interface{ Scan(...any) error }) (domain.HealthIssue, error) {
var value domain.HealthIssue
var severity, observed string
if err := scanner.Scan(&value.ID, &severity, &value.Kind, &value.ResourceID,
&value.Title, &value.Detail, &value.Action, &observed); err != nil {
return value, err
}
value.Severity = domain.Severity(severity)
var err error
value.ObservedAt, err = decodeTime(observed)
return value, err
}
const healthColumns = `id, severity, kind, resource_id, title, detail, action, observed_at`
const healthOrder = `CASE severity WHEN 'critical' THEN 0 WHEN 'warning' THEN 1 ELSE 2 END,
observed_at DESC, id`
func listHealthIssues(ctx context.Context, queryer interface {
QueryContext(context.Context, string, ...any) (*sql.Rows, error)
}) ([]domain.HealthIssue, error) {
rows, err := queryer.QueryContext(ctx, "SELECT "+healthColumns+" FROM health_issues ORDER BY "+healthOrder)
if err != nil {
return nil, err
}
defer rows.Close()
values := make([]domain.HealthIssue, 0)
for rows.Next() {
value, err := scanHealthIssue(rows)
if err != nil {
return nil, err
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) ListHealthIssues(ctx context.Context) ([]domain.HealthIssue, error) {
values, err := listHealthIssues(ctx, r.db)
if err != nil {
return nil, fmt.Errorf("sqlite: list health issues: %w", err)
}
return values, nil
}
func (r *Repository) SaveJob(ctx context.Context, value domain.Job) error {
_, err := r.db.ExecContext(ctx, `INSERT INTO jobs (
id, kind, state, resource_id, progress, message, payload_json, error,
retry_at, created_at, started_at, finished_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET kind=excluded.kind, state=excluded.state,
resource_id=excluded.resource_id, progress=excluded.progress,
message=excluded.message, payload_json=excluded.payload_json,
error=excluded.error, retry_at=excluded.retry_at, created_at=excluded.created_at,
started_at=excluded.started_at, finished_at=excluded.finished_at,
updated_at=excluded.updated_at`, value.ID, value.Kind, string(value.State),
value.ResourceID, value.Progress, value.Message, rawOrNil(value.Payload), value.Error,
encodeOptionalTime(value.RetryAt), encodeTime(value.CreatedAt),
encodeOptionalTime(value.StartedAt), encodeOptionalTime(value.FinishedAt),
encodeTime(value.UpdatedAt))
if err != nil {
return fmt.Errorf("sqlite: save job: %w", err)
}
return nil
}
const jobColumns = `id, kind, state, resource_id, progress, message, payload_json,
error, retry_at, created_at, started_at, finished_at, updated_at`
func scanJob(scanner interface{ Scan(...any) error }) (domain.Job, error) {
var value domain.Job
var state, created, updated string
var payload []byte
var retry, started, finished sql.NullString
if err := scanner.Scan(&value.ID, &value.Kind, &state, &value.ResourceID,
&value.Progress, &value.Message, &payload, &value.Error, &retry, &created,
&started, &finished, &updated); err != nil {
return value, err
}
value.State = domain.JobState(state)
value.Payload = copyRaw(payload)
var err error
if value.CreatedAt, err = decodeTime(created); err != nil {
return value, err
}
if value.UpdatedAt, err = decodeTime(updated); err != nil {
return value, err
}
if value.RetryAt, err = decodeOptionalTime(retry); err != nil {
return value, err
}
if value.StartedAt, err = decodeOptionalTime(started); err != nil {
return value, err
}
if value.FinishedAt, err = decodeOptionalTime(finished); err != nil {
return value, err
}
return value, nil
}
func (r *Repository) GetJob(ctx context.Context, id string) (domain.Job, error) {
value, err := scanJob(r.db.QueryRowContext(ctx, "SELECT "+jobColumns+" FROM jobs WHERE id = ?", id))
if err != nil {
return value, fmt.Errorf("sqlite: get job: %w", err)
}
return value, nil
}
func (r *Repository) ListJobs(ctx context.Context, limit int) ([]domain.Job, error) {
query := "SELECT " + jobColumns + " FROM jobs ORDER BY updated_at DESC, id"
var args []any
if limit > 0 {
query += " LIMIT ?"
args = append(args, limit)
}
rows, err := r.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("sqlite: list jobs: %w", err)
}
defer rows.Close()
values := make([]domain.Job, 0)
for rows.Next() {
value, err := scanJob(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan job: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) ListRecoverableJobs(ctx context.Context) ([]domain.Job, error) {
rows, err := r.db.QueryContext(ctx, "SELECT "+jobColumns+` FROM jobs
WHERE state IN ('queued', 'running', 'waiting_for_dns')
OR (state = 'failed' AND retry_at IS NOT NULL)
ORDER BY created_at, id`)
if err != nil {
return nil, fmt.Errorf("sqlite: list recoverable jobs: %w", err)
}
defer rows.Close()
values := make([]domain.Job, 0)
for rows.Next() {
value, err := scanJob(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan recoverable job: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
// ReconcileInterruptedJobs closes process-local work that cannot still be
// running after a new DomainOps process has acquired the data-directory lock.
// Journal recovery runs first; this final state transition prevents abandoned
// jobs from remaining permanently active on the dashboard.
func (r *Repository) ReconcileInterruptedJobs(ctx context.Context, now time.Time) (int64, error) {
encodedNow := encodeTime(now.UTC())
result, err := r.db.ExecContext(ctx, `UPDATE jobs
SET state = 'failed',
message = 'Interrupted by previous DomainOps shutdown',
error = 'operation was interrupted; crash recovery completed but the operation itself was not resumed',
retry_at = NULL,
finished_at = ?,
updated_at = ?
WHERE state IN ('queued', 'running', 'waiting_for_dns')`, encodedNow, encodedNow)
if err != nil {
return 0, fmt.Errorf("sqlite: reconcile interrupted jobs: %w", err)
}
count, err := result.RowsAffected()
if err != nil {
return 0, fmt.Errorf("sqlite: count reconciled interrupted jobs: %w", err)
}
return count, nil
}
func (r *Repository) SaveChallenge(ctx context.Context, value domain.ChallengeJournal) error {
_, err := r.db.ExecContext(ctx, `INSERT INTO challenge_journal (
id, job_id, credential_id, zone_id, record_id, fqdn, value_hash, created_at, cleaned_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET job_id=excluded.job_id, credential_id=excluded.credential_id, zone_id=excluded.zone_id,
record_id=excluded.record_id, fqdn=excluded.fqdn,
value_hash=excluded.value_hash, created_at=excluded.created_at,
cleaned_at=excluded.cleaned_at`, value.ID, value.JobID, value.CredentialID, value.ZoneID,
value.RecordID, value.FQDN, value.ValueHash, encodeTime(value.CreatedAt),
encodeOptionalTime(value.CleanedAt))
if err != nil {
return fmt.Errorf("sqlite: save challenge journal: %w", err)
}
return nil
}
func scanChallenge(scanner interface{ Scan(...any) error }) (domain.ChallengeJournal, error) {
var value domain.ChallengeJournal
var created string
var cleaned sql.NullString
if err := scanner.Scan(&value.ID, &value.JobID, &value.CredentialID, &value.ZoneID, &value.RecordID,
&value.FQDN, &value.ValueHash, &created, &cleaned); err != nil {
return value, err
}
var err error
if value.CreatedAt, err = decodeTime(created); err != nil {
return value, err
}
if value.CleanedAt, err = decodeOptionalTime(cleaned); err != nil {
return value, err
}
return value, nil
}
func (r *Repository) ListOpenChallenges(ctx context.Context) ([]domain.ChallengeJournal, error) {
rows, err := r.db.QueryContext(ctx, `SELECT id, job_id, credential_id, zone_id, record_id, fqdn,
value_hash, created_at, cleaned_at FROM challenge_journal
WHERE cleaned_at IS NULL ORDER BY created_at, id`)
if err != nil {
return nil, fmt.Errorf("sqlite: list open challenges: %w", err)
}
defer rows.Close()
values := make([]domain.ChallengeJournal, 0)
for rows.Next() {
value, err := scanChallenge(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan challenge: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) MarkChallengeCleaned(ctx context.Context, id string, cleanedAt time.Time) error {
if _, err := r.db.ExecContext(ctx, `UPDATE challenge_journal SET cleaned_at = ? WHERE id = ?`,
encodeTime(cleanedAt), id); err != nil {
return fmt.Errorf("sqlite: mark challenge cleaned: %w", err)
}
return nil
}
func (r *Repository) AppendAudit(ctx context.Context, value domain.AuditEvent) error {
_, err := r.db.ExecContext(ctx, `INSERT INTO audit_events (
id, actor, action, resource_id, before_json, after_json, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?)`, value.ID, value.Actor, value.Action,
value.ResourceID, rawOrNil(value.Before), rawOrNil(value.After), encodeTime(value.CreatedAt))
if err != nil {
return fmt.Errorf("sqlite: append audit event: %w", err)
}
return nil
}
func scanAudit(scanner interface{ Scan(...any) error }) (domain.AuditEvent, error) {
var value domain.AuditEvent
var before, after []byte
var created string
if err := scanner.Scan(&value.ID, &value.Actor, &value.Action, &value.ResourceID,
&before, &after, &created); err != nil {
return value, err
}
value.Before = copyRaw(before)
value.After = copyRaw(after)
var err error
value.CreatedAt, err = decodeTime(created)
return value, err
}
func (r *Repository) ListAudit(ctx context.Context, limit int) ([]domain.AuditEvent, error) {
query := `SELECT id, actor, action, resource_id, before_json, after_json, created_at
FROM audit_events ORDER BY created_at DESC, id`
var args []any
if limit > 0 {
query += " LIMIT ?"
args = append(args, limit)
}
rows, err := r.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("sqlite: list audit events: %w", err)
}
defer rows.Close()
values := make([]domain.AuditEvent, 0)
for rows.Next() {
value, err := scanAudit(rows)
if err != nil {
return nil, fmt.Errorf("sqlite: scan audit event: %w", err)
}
values = append(values, value)
}
return values, rows.Err()
}
func (r *Repository) Dashboard(ctx context.Context, now time.Time) (domain.DashboardSnapshot, error) {
snapshot := domain.DashboardSnapshot{GeneratedAt: now}
tx, err := r.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
return snapshot, fmt.Errorf("sqlite: begin dashboard snapshot: %w", err)
}
defer tx.Rollback()
counts := []struct {
query string
value *int
}{
{"SELECT COUNT(*) FROM credentials", &snapshot.Credentials},
{"SELECT COUNT(*) FROM accounts", &snapshot.Accounts},
{"SELECT COUNT(*) FROM zones", &snapshot.Zones},
{"SELECT COUNT(*) FROM dns_records", &snapshot.DNSRecords},
{"SELECT COUNT(*) FROM certificate_lineages", &snapshot.Certificates},
{`SELECT COUNT(*) FROM jobs WHERE state IN ('queued', 'running', 'waiting_for_dns')`, &snapshot.ActiveJobs},
}
for _, item := range counts {
if err := tx.QueryRowContext(ctx, item.query).Scan(item.value); err != nil {
return snapshot, fmt.Errorf("sqlite: count dashboard resources: %w", err)
}
}
rows, err := tx.QueryContext(ctx, `SELECT v.not_before, v.not_after, v.renewal_window_start
FROM certificate_lineages l
JOIN certificate_versions v ON v.id = l.current_version_id
WHERE v.revoked_at IS NULL AND v.revocation_pending_at IS NULL`)
if err != nil {
return snapshot, fmt.Errorf("sqlite: load dashboard certificates: %w", err)
}
for rows.Next() {
var notBeforeRaw, notAfterRaw string
var renewalRaw sql.NullString
if err := rows.Scan(&notBeforeRaw, &notAfterRaw, &renewalRaw); err != nil {
rows.Close()
return snapshot, fmt.Errorf("sqlite: scan dashboard certificate: %w", err)
}
notBefore, err := decodeTime(notBeforeRaw)
if err != nil {
rows.Close()
return snapshot, fmt.Errorf("sqlite: decode dashboard certificate: %w", err)
}
notAfter, err := decodeTime(notAfterRaw)
if err != nil {
rows.Close()
return snapshot, fmt.Errorf("sqlite: decode dashboard certificate: %w", err)
}
if !now.Before(notAfter) {
snapshot.CertificatesExpired++
continue
}
var dueAt time.Time
if renewalRaw.Valid {
dueAt, err = decodeTime(renewalRaw.String)
if err != nil {
rows.Close()
return snapshot, fmt.Errorf("sqlite: decode renewal window: %w", err)
}
} else {
dueAt = notBefore.Add(notAfter.Sub(notBefore) * 2 / 3)
}
if !now.Before(dueAt) {
snapshot.CertificatesDue++
}
}
if err := rows.Close(); err != nil {
return snapshot, fmt.Errorf("sqlite: close dashboard certificates: %w", err)
}
if err := rows.Err(); err != nil {
return snapshot, fmt.Errorf("sqlite: iterate dashboard certificates: %w", err)
}
snapshot.Issues, err = listHealthIssues(ctx, tx)
if err != nil {
return snapshot, fmt.Errorf("sqlite: load dashboard issues: %w", err)
}
if err := tx.Commit(); err != nil {
return snapshot, fmt.Errorf("sqlite: commit dashboard snapshot: %w", err)
}
return snapshot, nil
}
+150
View File
@@ -0,0 +1,150 @@
// Package sqlite implements DomainOps' durable local repository.
package sqlite
import (
"context"
"database/sql"
"embed"
"errors"
"fmt"
"io/fs"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/MeghdadFadaee/domainops/internal/store"
_ "modernc.org/sqlite"
)
const (
directoryMode = 0o700
databaseMode = 0o600
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
// Repository is a SQLite-backed store.Repository.
type Repository struct {
db *sql.DB
}
var _ store.Repository = (*Repository)(nil)
// New creates the database parent directory, opens path, and configures SQLite.
// It intentionally does not run migrations; callers must call Migrate before use.
func New(path string) (*Repository, error) {
if strings.TrimSpace(path) == "" {
return nil, errors.New("sqlite: database path is empty")
}
var dsn string
if path == ":memory:" {
dsn = "file:domainops-memory?mode=memory&cache=shared"
} else {
absolute, err := filepath.Abs(path)
if err != nil {
return nil, fmt.Errorf("sqlite: resolve database path: %w", err)
}
dir := filepath.Dir(absolute)
if err := os.MkdirAll(dir, directoryMode); err != nil {
return nil, fmt.Errorf("sqlite: create database directory: %w", err)
}
if err := os.Chmod(dir, directoryMode); err != nil {
return nil, fmt.Errorf("sqlite: secure database directory: %w", err)
}
u := &url.URL{Scheme: "file", Path: filepath.ToSlash(absolute)}
dsn = u.String()
}
separator := "?"
if strings.Contains(dsn, "?") {
separator = "&"
}
// FULL synchronous mode is required for the certificate/challenge journals:
// an acknowledged intent or final metadata commit must survive power loss
// before filesystem activation or orphan cleanup can rely on it.
dsn += separator + "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=synchronous(FULL)"
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fmt.Errorf("sqlite: open: %w", err)
}
db.SetMaxOpenConns(4)
db.SetMaxIdleConns(4)
db.SetConnMaxLifetime(0)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
_ = db.Close()
return nil, fmt.Errorf("sqlite: connect: %w", err)
}
if path != ":memory:" {
if err := os.Chmod(path, databaseMode); err != nil {
_ = db.Close()
return nil, fmt.Errorf("sqlite: secure database file: %w", err)
}
}
return &Repository{db: db}, nil
}
// Close closes the database and releases its resources.
func (r *Repository) Close() error {
if r == nil || r.db == nil {
return nil
}
return r.db.Close()
}
// Migrate applies all embedded migrations exactly once, in filename order.
func (r *Repository) Migrate(ctx context.Context) error {
if _, err := r.db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TEXT NOT NULL
)`); err != nil {
return fmt.Errorf("sqlite: initialize migrations: %w", err)
}
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
return fmt.Errorf("sqlite: read migrations: %w", err)
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
var applied int
err := r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM schema_migrations WHERE version = ?", entry.Name()).Scan(&applied)
if err != nil {
return fmt.Errorf("sqlite: inspect migration %s: %w", entry.Name(), err)
}
if applied != 0 {
continue
}
body, err := fs.ReadFile(migrationFiles, "migrations/"+entry.Name())
if err != nil {
return fmt.Errorf("sqlite: read migration %s: %w", entry.Name(), err)
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("sqlite: begin migration %s: %w", entry.Name(), err)
}
if _, err = tx.ExecContext(ctx, string(body)); err == nil {
_, err = tx.ExecContext(ctx, "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", entry.Name(), encodeTime(time.Now()))
}
if err != nil {
_ = tx.Rollback()
return fmt.Errorf("sqlite: apply migration %s: %w", entry.Name(), err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("sqlite: commit migration %s: %w", entry.Name(), err)
}
}
return nil
}
+490
View File
@@ -0,0 +1,490 @@
package sqlite
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/MeghdadFadaee/domainops/internal/domain"
"github.com/MeghdadFadaee/domainops/internal/store"
)
func openTestRepository(t *testing.T) *Repository {
t.Helper()
repository, err := New(filepath.Join(t.TempDir(), "state", "domainops.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = repository.Close() })
if err := repository.Migrate(context.Background()); err != nil {
t.Fatal(err)
}
if err := repository.Migrate(context.Background()); err != nil {
t.Fatalf("second migration must be idempotent: %v", err)
}
return repository
}
func TestRepositoryUsesFullSynchronousDurability(t *testing.T) {
r := openTestRepository(t)
var synchronous int
if err := r.db.QueryRow("PRAGMA synchronous").Scan(&synchronous); err != nil {
t.Fatal(err)
}
if synchronous != 2 {
t.Fatalf("PRAGMA synchronous = %d, want FULL (2)", synchronous)
}
}
func TestACMEAccountCommitClosesSecretIntentAtomically(t *testing.T) {
ctx := context.Background()
r := openTestRepository(t)
now := time.Now().UTC().Truncate(time.Second)
intent := domain.ACMEAccountCommitIntent{AccountID: "acme-journal", SecretRef: "acme-account/acme-journal", CreatedAt: now}
if err := r.SaveACMEAccountCommitIntent(ctx, intent); err != nil {
t.Fatal(err)
}
account := domain.ACMEAccount{ID: intent.AccountID, Environment: "staging", DirectoryURL: "https://ca.invalid/directory", Email: "ops@example.com", Registration: `{}`, SecretRef: intent.SecretRef, CreatedAt: now}
if err := r.CommitACMEAccount(ctx, account); err != nil {
t.Fatal(err)
}
intents, err := r.ListACMEAccountCommitIntents(ctx)
if err != nil || len(intents) != 0 {
t.Fatalf("ACME account intents = %#v, %v", intents, err)
}
loaded, err := r.GetACMEAccountByEnvironment(ctx, account.Environment)
if err != nil || loaded.ID != account.ID || loaded.SecretRef != account.SecretRef {
t.Fatalf("committed ACME account = %#v, %v", loaded, err)
}
}
func TestACMEAccountCommitConflictPreservesExistingAccountAndIntent(t *testing.T) {
ctx := context.Background()
r := openTestRepository(t)
now := time.Now().UTC().Truncate(time.Second)
existing := domain.ACMEAccount{ID: "acme-existing", Environment: "staging", DirectoryURL: "https://ca.invalid/directory", Email: "existing@example.com", Registration: `{}`, SecretRef: "acme-account/acme-existing", CreatedAt: now}
if err := r.SaveACMEAccount(ctx, existing); err != nil {
t.Fatal(err)
}
intent := domain.ACMEAccountCommitIntent{AccountID: "acme-loser", SecretRef: "acme-account/acme-loser", CreatedAt: now.Add(time.Second)}
if err := r.SaveACMEAccountCommitIntent(ctx, intent); err != nil {
t.Fatal(err)
}
challenger := domain.ACMEAccount{ID: intent.AccountID, Environment: existing.Environment, DirectoryURL: "https://ca.invalid/directory", Email: "loser@example.com", Registration: `{}`, SecretRef: intent.SecretRef, CreatedAt: intent.CreatedAt}
if err := r.CommitACMEAccount(ctx, challenger); !errors.Is(err, store.ErrACMEAccountConflict) {
t.Fatalf("commit conflict = %v, want %v", err, store.ErrACMEAccountConflict)
}
loaded, err := r.GetACMEAccountByEnvironment(ctx, existing.Environment)
if err != nil {
t.Fatal(err)
}
if loaded.ID != existing.ID || loaded.SecretRef != existing.SecretRef || loaded.Email != existing.Email {
t.Fatalf("existing account was replaced: %#v", loaded)
}
intents, err := r.ListACMEAccountCommitIntents(ctx)
if err != nil {
t.Fatal(err)
}
if len(intents) != 1 || intents[0].AccountID != intent.AccountID {
t.Fatalf("losing commit intent = %#v, want %#v", intents, intent)
}
}
func TestRepositoryInventoryDNSAndTLSRoundTrip(t *testing.T) {
ctx := context.Background()
r := openTestRepository(t)
now := time.Date(2026, 7, 11, 10, 0, 0, 0, time.UTC)
verified := now.Add(time.Minute)
credential := domain.Credential{
ID: "cred_1", Provider: domain.ProviderCloudflare, Label: "Production",
Kind: domain.CredentialUserToken, SecretRef: "secret_1", Status: domain.CredentialValid,
Capabilities: []string{"dns:read", "dns:write"}, CreatedAt: now, LastVerifiedAt: &verified,
}
if err := r.SaveCredential(ctx, credential); err != nil {
t.Fatal(err)
}
accounts := []domain.RemoteAccount{{ID: "cfacct_a", Provider: domain.ProviderCloudflare, ProviderID: "a", Name: "Account A", CreatedAt: now}}
links := []domain.AccountCredential{{AccountID: "cfacct_a", CredentialID: credential.ID, Preferred: true}}
if err := r.SaveAccounts(ctx, accounts, links); err != nil {
t.Fatal(err)
}
zone := domain.Zone{
ID: "cfzone_z", Provider: domain.ProviderCloudflare, ProviderID: "z", AccountID: "cfacct_a",
PreferredCredentialID: credential.ID, Name: "example.com", Status: domain.ZoneActive,
Plan: "Free", NameServers: []string{"ns1.example", "ns2.example"}, LastSyncedAt: &now,
}
if err := r.SaveZones(ctx, []domain.Zone{zone}); err != nil {
t.Fatal(err)
}
if err := r.SaveCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:write", now); err != nil {
t.Fatal(err)
}
if observed, err := r.HasCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:write"); err != nil || !observed {
t.Fatalf("credential zone capability = %v, %v", observed, err)
}
if observedAt, observed, err := r.GetCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:write"); err != nil || !observed || !observedAt.Equal(now) {
t.Fatalf("credential zone capability observation = %v, %v, %v", observedAt, observed, err)
}
if observed, err := r.HasCredentialZoneCapability(ctx, credential.ID, zone.ID, "tls:write"); err != nil || observed {
t.Fatalf("unobserved zone capability = %v, %v", observed, err)
}
if err := r.SaveCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:read", now); err != nil {
t.Fatal(err)
}
if err := r.InvalidateCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:read"); err != nil {
t.Fatal(err)
}
if observed, err := r.HasCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:read"); err != nil || observed {
t.Fatalf("invalidated DNS-read capability = %v, %v", observed, err)
}
if observed, err := r.HasCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:write"); err != nil || !observed {
t.Fatalf("unrelated DNS-write capability changed = %v, %v", observed, err)
}
if detached, err := r.GetZone(ctx, zone.ID); err != nil || detached.PreferredCredentialID != "" {
t.Fatalf("invalidated preferred route = %#v, %v", detached, err)
}
priority := uint16(10)
records := []domain.DNSRecord{
{ID: "cfrecord_1", ProviderID: "1", ZoneID: zone.ID, Type: domain.RecordA, Name: "example.com", Content: "192.0.2.1", TTL: 1, Proxied: true, Proxiable: true, Tags: []string{"owner:test"}},
{ID: "cfrecord_2", ProviderID: "2", ZoneID: zone.ID, Type: domain.RecordMX, Name: "example.com", Content: "mail.example.com", TTL: 3600, Priority: &priority},
}
if err := r.ReplaceDNSRecords(ctx, zone.ID, records, now); err != nil {
t.Fatal(err)
}
loaded, err := r.ListDNSRecords(ctx, zone.ID)
if err != nil {
t.Fatal(err)
}
if len(loaded) != 2 || loaded[0].ZoneID != zone.ID {
t.Fatalf("loaded records = %#v", loaded)
}
if err := r.ReplaceDNSRecords(ctx, zone.ID, records[:1], now.Add(time.Minute)); err != nil {
t.Fatal(err)
}
loaded, err = r.ListDNSRecords(ctx, zone.ID)
if err != nil || len(loaded) != 1 {
t.Fatalf("replacement = %#v, %v", loaded, err)
}
settings := domain.EdgeTLSSettings{ZoneID: zone.ID, Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true, HasProxiedDNS: true, LastSyncedAt: &now}
if err := r.SaveTLSSettings(ctx, settings); err != nil {
t.Fatal(err)
}
gotSettings, err := r.GetTLSSettings(ctx, zone.ID)
if err != nil || gotSettings.Mode != "strict" || !gotSettings.TLS13 {
t.Fatalf("TLS = %#v, %v", gotSettings, err)
}
gotCredential, err := r.GetCredential(ctx, credential.ID)
if err != nil || gotCredential.SecretRef != "secret_1" || len(gotCredential.Capabilities) != 2 {
t.Fatalf("credential = %#v, %v", gotCredential, err)
}
gotZone, err := r.GetZone(ctx, zone.ID)
if err != nil || gotZone.Name != zone.Name || len(gotZone.NameServers) != 2 {
t.Fatalf("zone = %#v, %v", gotZone, err)
}
}
func TestRepositoryCertificatesJobsHealthAndDashboard(t *testing.T) {
ctx := context.Background()
r := openTestRepository(t)
now := time.Date(2026, 7, 11, 10, 0, 0, 0, time.UTC)
credential := domain.Credential{ID: "cred", Provider: domain.ProviderCloudflare, Label: "CF", Kind: domain.CredentialUserToken, SecretRef: "secret", Status: domain.CredentialValid, CreatedAt: now}
if err := r.SaveCredential(ctx, credential); err != nil {
t.Fatal(err)
}
account := domain.RemoteAccount{ID: "account", Provider: domain.ProviderCloudflare, ProviderID: "remote", Name: "Remote", CreatedAt: now}
if err := r.SaveAccounts(ctx, []domain.RemoteAccount{account}, []domain.AccountCredential{{AccountID: account.ID, CredentialID: credential.ID, Preferred: true}}); err != nil {
t.Fatal(err)
}
zone := domain.Zone{ID: "zone", Provider: domain.ProviderCloudflare, ProviderID: "remote-zone", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "example.com", Status: domain.ZoneActive}
if err := r.SaveZones(ctx, []domain.Zone{zone}); err != nil {
t.Fatal(err)
}
acme := domain.ACMEAccount{ID: "acme", Environment: "production", DirectoryURL: "https://ca.invalid/directory", Email: "ops@example.com", Registration: `{}`, SecretRef: "acme-secret", CreatedAt: now}
if err := r.SaveACMEAccount(ctx, acme); err != nil {
t.Fatal(err)
}
if loaded, err := r.GetACMEAccountByEnvironment(ctx, "production"); err != nil || loaded.SecretRef != acme.SecretRef {
t.Fatalf("ACME = %#v, %v", loaded, err)
}
lineage := domain.CertificateLineage{ID: "lineage", Name: "example.com", ZoneID: zone.ID, Source: domain.CertificateManaged, Identifiers: []string{"example.com", "*.example.com"}, KeyAlgorithm: domain.KeyECDSAP256, Profile: "classic", ACMEAccountID: acme.ID, CreatedAt: now, UpdatedAt: now}
if err := r.SaveCertificateLineage(ctx, lineage); err != nil {
t.Fatal(err)
}
due := now.Add(-time.Hour)
version := domain.CertificateVersion{ID: "version", LineageID: lineage.ID, SerialNumber: "01", FingerprintSHA256: "abc", Issuer: "Test CA", Identifiers: lineage.Identifiers, NotBefore: now.Add(-60 * 24 * time.Hour), NotAfter: now.Add(30 * 24 * time.Hour), CertificatePath: "/tmp/cert.pem", ChainPath: "/tmp/chain.pem", PrivateKeyRef: "key", RenewalWindowStart: &due, CreatedAt: now}
if err := r.SaveCertificateVersion(ctx, version); err != nil {
t.Fatal(err)
}
revokedAt := now.Add(-2 * time.Hour)
pendingAt := now.Add(-3 * time.Hour)
reason := uint(1)
revokedVersion := version
revokedVersion.ID, revokedVersion.SerialNumber = "revoked-version", "02"
revokedVersion.RevocationPendingAt, revokedVersion.RevokedAt, revokedVersion.RevocationReason = &pendingAt, &revokedAt, &reason
if err := r.SaveCertificateVersion(ctx, revokedVersion); err != nil {
t.Fatal(err)
}
versions, err := r.ListCertificateVersions(ctx, lineage.ID)
if err != nil || len(versions) != 2 || versions[0].RevocationPendingAt == nil || versions[0].RevokedAt == nil || versions[0].RevocationReason == nil || *versions[0].RevocationReason != reason {
t.Fatalf("revocation round trip = %#v, %v", versions, err)
}
lineage.CurrentVersionID = version.ID
if err := r.SaveCertificateLineage(ctx, lineage); err != nil {
t.Fatal(err)
}
endpoint := domain.ObservedEndpoint{ID: "endpoint", ZoneID: zone.ID, Host: "example.com", Port: 443, Enabled: true, FingerprintSHA256: "def", LastCheckedAt: &now}
if err := r.SaveEndpoint(ctx, endpoint); err != nil {
t.Fatal(err)
}
issue := domain.HealthIssue{ID: "issue", Severity: domain.SeverityWarning, Kind: "stale", ResourceID: endpoint.ID, Title: "Certificate differs", Detail: "Observed fingerprint differs", ObservedAt: now}
if err := r.SaveHealthIssues(ctx, endpoint.ID, []domain.HealthIssue{issue}); err != nil {
t.Fatal(err)
}
job := domain.Job{ID: "job", Kind: "certificate.issue", State: domain.JobRunning, Progress: 50, Message: "Waiting", Payload: json.RawMessage(`{"safe":true}`), CreatedAt: now, StartedAt: &now, UpdatedAt: now}
if err := r.SaveJob(ctx, job); err != nil {
t.Fatal(err)
}
challenge := domain.ChallengeJournal{ID: "challenge", JobID: job.ID, CredentialID: credential.ID, ZoneID: zone.ID, RecordID: "txt", FQDN: "_acme-challenge.example.com", ValueHash: "hash", CreatedAt: now}
if err := r.SaveChallenge(ctx, challenge); err != nil {
t.Fatal(err)
}
if err := r.AppendAudit(ctx, domain.AuditEvent{ID: "audit", Actor: "test", Action: "dns.patch", ResourceID: "record", Before: json.RawMessage(`{"a":1}`), After: json.RawMessage(`{"a":2}`), CreatedAt: now}); err != nil {
t.Fatal(err)
}
snapshot, err := r.Dashboard(ctx, now)
if err != nil {
t.Fatal(err)
}
if snapshot.Accounts != 1 || snapshot.Zones != 1 || snapshot.Certificates != 1 || snapshot.CertificatesDue != 1 || snapshot.ActiveJobs != 1 || len(snapshot.Issues) != 1 {
t.Fatalf("dashboard = %#v", snapshot)
}
recoverable, err := r.ListRecoverableJobs(ctx)
if err != nil || len(recoverable) != 1 {
t.Fatalf("recoverable = %#v, %v", recoverable, err)
}
open, err := r.ListOpenChallenges(ctx)
if err != nil || len(open) != 1 || open[0].CredentialID != credential.ID {
t.Fatalf("open challenges = %#v, %v", open, err)
}
if err := r.MarkChallengeCleaned(ctx, challenge.ID, now.Add(time.Minute)); err != nil {
t.Fatal(err)
}
open, err = r.ListOpenChallenges(ctx)
if err != nil || len(open) != 0 {
t.Fatalf("cleaned challenges = %#v, %v", open, err)
}
audit, err := r.ListAudit(ctx, 10)
if err != nil || len(audit) != 1 || string(audit[0].Before) != `{"a":1}` {
t.Fatalf("audit = %#v, %v", audit, err)
}
}
func TestReconcileInterruptedJobsMarksOnlyActiveStatesFailed(t *testing.T) {
ctx := context.Background()
repository := openTestRepository(t)
started := time.Date(2026, 7, 12, 10, 0, 0, 0, time.UTC)
states := []domain.JobState{
domain.JobQueued,
domain.JobRunning,
domain.JobWaitingForDNS,
domain.JobSucceeded,
domain.JobFailed,
}
for _, state := range states {
job := domain.Job{ID: "job-" + string(state), Kind: "test", State: state, Message: string(state), CreatedAt: started, UpdatedAt: started}
if state == domain.JobFailed {
retry := started.Add(time.Hour)
job.RetryAt = &retry
}
if err := repository.SaveJob(ctx, job); err != nil {
t.Fatal(err)
}
}
finished := started.Add(5 * time.Minute)
count, err := repository.ReconcileInterruptedJobs(ctx, finished)
if err != nil || count != 3 {
t.Fatalf("reconciled count = %d, %v; want 3", count, err)
}
for _, state := range states {
job, err := repository.GetJob(ctx, "job-"+string(state))
if err != nil {
t.Fatal(err)
}
switch state {
case domain.JobQueued, domain.JobRunning, domain.JobWaitingForDNS:
if job.State != domain.JobFailed || job.FinishedAt == nil || !job.FinishedAt.Equal(finished) || job.RetryAt != nil || !strings.Contains(job.Error, "interrupted") {
t.Fatalf("active %s job after reconcile = %#v", state, job)
}
default:
if job.State != state {
t.Fatalf("terminal %s job changed to %s", state, job.State)
}
}
}
}
func TestSaveEndpointReusesUniqueHostPortAcrossZoneReassignment(t *testing.T) {
ctx := context.Background()
repository := openTestRepository(t)
now := time.Date(2026, 7, 12, 11, 0, 0, 0, time.UTC)
credential := domain.Credential{ID: "cred-endpoint", Provider: domain.ProviderCloudflare, Label: "CF", Kind: domain.CredentialUserToken, SecretRef: "secret", Status: domain.CredentialValid, CreatedAt: now}
if err := repository.SaveCredential(ctx, credential); err != nil {
t.Fatal(err)
}
account := domain.RemoteAccount{ID: "account-endpoint", Provider: domain.ProviderCloudflare, ProviderID: "account-endpoint", Name: "Endpoints", CreatedAt: now}
if err := repository.SaveAccounts(ctx, []domain.RemoteAccount{account}, []domain.AccountCredential{{AccountID: account.ID, CredentialID: credential.ID}}); err != nil {
t.Fatal(err)
}
zones := []domain.Zone{
{ID: "zone-old", Provider: domain.ProviderCloudflare, ProviderID: "zone-old", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "example.com", Status: domain.ZoneUnknown},
{ID: "zone-new", Provider: domain.ProviderCloudflare, ProviderID: "zone-new", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "www.example.com", Status: domain.ZoneActive},
}
if err := repository.SaveZones(ctx, zones); err != nil {
t.Fatal(err)
}
old := domain.ObservedEndpoint{ID: "endpoint-old", ZoneID: zones[0].ID, Host: "www.example.com", Port: 443, Enabled: true, FingerprintSHA256: "old"}
if err := repository.SaveEndpoint(ctx, old); err != nil {
t.Fatal(err)
}
reassigned := domain.ObservedEndpoint{ID: "endpoint-new", ZoneID: zones[1].ID, Host: "www.example.com", Port: 443, Enabled: true, FingerprintSHA256: "new"}
if err := repository.SaveEndpoint(ctx, reassigned); err != nil {
t.Fatalf("host/port reassignment conflicted: %v", err)
}
endpoints, err := repository.ListEndpoints(ctx)
if err != nil || len(endpoints) != 1 {
t.Fatalf("reassigned endpoints = %#v, %v", endpoints, err)
}
if endpoints[0].ID != old.ID || endpoints[0].ZoneID != zones[1].ID || endpoints[0].FingerprintSHA256 != "new" {
t.Fatalf("retained endpoint after reassignment = %#v", endpoints[0])
}
}
func TestEndpointHostPortMigrationDeduplicatesLegacyDatabase(t *testing.T) {
ctx := context.Background()
repository, err := New(filepath.Join(t.TempDir(), "legacy.db"))
if err != nil {
t.Fatal(err)
}
defer repository.Close()
initial, err := migrationFiles.ReadFile("migrations/001_initial.sql")
if err != nil {
t.Fatal(err)
}
legacy := strings.Replace(string(initial), " last_error TEXT NOT NULL DEFAULT '',\n UNIQUE(host, port)\n", " last_error TEXT NOT NULL DEFAULT ''\n", 1)
if legacy == string(initial) {
t.Fatal("legacy schema fixture did not remove endpoint uniqueness")
}
if _, err := repository.db.ExecContext(ctx, legacy); err != nil {
t.Fatalf("create legacy initial schema: %v", err)
}
if _, err := repository.db.ExecContext(ctx, `CREATE TABLE schema_migrations (
version TEXT PRIMARY KEY,
applied_at TEXT NOT NULL
)`); err != nil {
t.Fatal(err)
}
legacyMigrations := []string{
"001_initial.sql",
"002_challenge_credential.sql",
"003_certificate_revocation.sql",
"004_revocation_intent.sql",
"005_zone_capabilities.sql",
"006_certificate_commit_journal.sql",
"007_acme_account_commit_journal.sql",
}
for _, name := range legacyMigrations {
if name != "001_initial.sql" {
body, readErr := migrationFiles.ReadFile("migrations/" + name)
if readErr != nil {
t.Fatal(readErr)
}
if _, execErr := repository.db.ExecContext(ctx, string(body)); execErr != nil {
t.Fatalf("apply legacy migration %s: %v", name, execErr)
}
}
if _, err := repository.db.ExecContext(ctx, "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", name, encodeTime(time.Now())); err != nil {
t.Fatal(err)
}
}
now := time.Now().UTC()
credential := domain.Credential{ID: "legacy-cred", Provider: domain.ProviderCloudflare, Label: "Legacy", Kind: domain.CredentialUserToken, SecretRef: "secret", Status: domain.CredentialValid, CreatedAt: now}
if err := repository.SaveCredential(ctx, credential); err != nil {
t.Fatal(err)
}
account := domain.RemoteAccount{ID: "legacy-account", Provider: domain.ProviderCloudflare, ProviderID: "legacy-account", Name: "Legacy", CreatedAt: now}
if err := repository.SaveAccounts(ctx, []domain.RemoteAccount{account}, []domain.AccountCredential{{AccountID: account.ID, CredentialID: credential.ID}}); err != nil {
t.Fatal(err)
}
zones := []domain.Zone{
{ID: "legacy-zone-a", Provider: domain.ProviderCloudflare, ProviderID: "legacy-zone-a", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "example.com", Status: domain.ZoneActive},
{ID: "legacy-zone-b", Provider: domain.ProviderCloudflare, ProviderID: "legacy-zone-b", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "www.example.com", Status: domain.ZoneActive},
}
if err := repository.SaveZones(ctx, zones); err != nil {
t.Fatal(err)
}
insertEndpoint := `INSERT INTO endpoints (
id, zone_id, host, port, enabled, resolved_addresses_json,
fingerprint_sha256, issuer, valid_for_host, trusted, last_error
) VALUES (?, ?, 'www.example.com', 443, ?, '[]', '', '', 0, 0, '')`
if _, err := repository.db.ExecContext(ctx, insertEndpoint, "legacy-keeper", zones[0].ID, true); err != nil {
t.Fatal(err)
}
if _, err := repository.db.ExecContext(ctx, insertEndpoint, "legacy-duplicate", zones[1].ID, false); err != nil {
t.Fatalf("legacy schema unexpectedly enforced uniqueness: %v", err)
}
for _, endpointID := range []string{"legacy-keeper", "legacy-duplicate"} {
if _, err := repository.db.ExecContext(ctx, `INSERT INTO health_issues (
id, owner_id, severity, kind, resource_id, title, detail, action, observed_at
) VALUES (?, ?, 'warning', 'legacy', ?, 'Legacy', 'Legacy issue', '', ?)`, "issue-"+endpointID, endpointID, endpointID, encodeTime(now)); err != nil {
t.Fatal(err)
}
}
if err := repository.Migrate(ctx); err != nil {
t.Fatalf("upgrade legacy endpoint schema: %v", err)
}
endpoints, err := repository.ListEndpoints(ctx)
if err != nil || len(endpoints) != 1 || endpoints[0].ID != "legacy-keeper" {
t.Fatalf("deduplicated endpoints = %#v, %v", endpoints, err)
}
issues, err := repository.ListHealthIssues(ctx)
if err != nil || len(issues) != 1 || issues[0].ResourceID != "legacy-keeper" {
t.Fatalf("deduplicated health issues = %#v, %v", issues, err)
}
if _, err := repository.db.ExecContext(ctx, insertEndpoint, "legacy-third", zones[1].ID, true); err == nil {
t.Fatal("upgraded schema accepted duplicate host/port")
}
}
func TestRepositoryFilePermissions(t *testing.T) {
path := filepath.Join(t.TempDir(), "private", "domainops.db")
r, err := New(path)
if err != nil {
t.Fatal(err)
}
defer r.Close()
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0o600 {
t.Fatalf("database mode = %o", info.Mode().Perm())
}
dir, err := os.Stat(filepath.Dir(path))
if err != nil {
t.Fatal(err)
}
if dir.Mode().Perm() != 0o700 {
t.Fatalf("database directory mode = %o", dir.Mode().Perm())
}
}
File diff suppressed because it is too large. Load diff
+853
View File
@@ -0,0 +1,853 @@
package tui
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"github.com/MeghdadFadaee/domainops/internal/app"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
func TestModelRendersResponsiveOperationalViews(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{Version: "test"})
now := time.Now().UTC()
_, _ = model.Update(tea.WindowSizeMsg{Width: 132, Height: 38})
_, _ = model.Update(loadMsg{
dashboard: domain.DashboardSnapshot{GeneratedAt: now, Accounts: 2, Zones: 60, DNSRecords: 420, Certificates: 12, CertificatesDue: 2, Issues: []domain.HealthIssue{{ID: "i", Severity: domain.SeverityWarning, Title: "Certificate differs", Detail: "public endpoint is stale"}}},
credentials: []domain.Credential{{ID: "cred", Label: "Production", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid}},
accounts: []domain.RemoteAccount{{ID: "account", Name: "Primary account"}},
zones: []domain.Zone{{ID: "zone", AccountID: "account", PreferredCredentialID: "cred", Name: "example.com", Status: domain.ZoneActive, Plan: "Pro"}},
records: []domain.DNSRecord{{ID: "record", ZoneID: "zone", Type: domain.RecordA, Name: "example.com", Content: "192.0.2.1", TTL: 1, Proxied: true}},
})
view := model.View().Content
for _, expected := range []string{"DOMAINOPS", "Dashboard", "ACTION QUEUE", "Certificate differs", "60"} {
if !strings.Contains(view, expected) {
t.Fatalf("dashboard does not contain %q", expected)
}
}
model.screen = screenDNS
view = model.View().Content
for _, expected := range []string{"DNS · example.com", "192.0.2.1", "proxied"} {
if !strings.Contains(view, expected) {
t.Fatalf("DNS view does not contain %q", expected)
}
}
model.screen = screenZones
view = model.View().Content
for _, expected := range []string{"Primary account", "Production"} {
if !strings.Contains(view, expected) {
t.Fatalf("zone ownership view does not contain %q", expected)
}
}
_, _ = model.Update(tea.WindowSizeMsg{Width: 50, Height: 12})
if view = model.View().Content; !strings.Contains(view, "terminal is too small") {
t.Fatalf("small-terminal fallback missing: %q", view)
}
}
func TestUndersizedTerminalRejectsAllHiddenInteractiveInput(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{})
model.width, model.height = 50, 12
model.screen = screenDNS
model.zones = []domain.Zone{{ID: "zone", Name: "example.com"}}
model.activeDNSZoneID = "zone"
model.records = []domain.DNSRecord{{ID: "record", ZoneID: "zone", Type: domain.RecordA, Name: "example.com"}}
_, cmd := model.Update(tea.KeyPressMsg{Code: 'd', Text: "d"})
if cmd != nil || model.confirmDelete {
t.Fatalf("undersized view opened hidden delete confirmation: cmd=%v confirm=%v", cmd != nil, model.confirmDelete)
}
// A modal that became hidden after a resize must not accept confirmation input.
model.confirmDelete = true
_, cmd = model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if cmd != nil || backend.deleteCalls != 0 || !model.confirmDelete {
t.Fatalf("undersized hidden confirmation mutated state: cmd=%v calls=%d confirm=%v", cmd != nil, backend.deleteCalls, model.confirmDelete)
}
locked := &fakeBackend{locked: true}
unlockModel := New(locked, Options{})
unlockModel.width, unlockModel.height = 40, 10
unlockModel.unlockInputs[0].SetValue("secret")
_, cmd = unlockModel.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if cmd != nil || locked.unlockCalls != 0 || !unlockModel.unlock {
t.Fatalf("undersized hidden unlock accepted input: cmd=%v calls=%d unlock=%v", cmd != nil, locked.unlockCalls, unlockModel.unlock)
}
}
func TestRecordFormBuildsStructuredCAAAndSRVData(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.zones = []domain.Zone{{ID: "zone", Name: "example.com"}}
model.openRecordForm(false)
model.recordInputs[0].SetValue("CAA")
model.recordInputs[1].SetValue("@")
model.recordInputs[2].SetValue("0 issue letsencrypt.org")
model.recordInputs[3].SetValue("300")
record, err := model.recordFromForm()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(record.Data), `"tag":"issue"`) || !strings.Contains(string(record.Data), `"value":"letsencrypt.org"`) {
t.Fatalf("CAA data = %s", record.Data)
}
model.recordInputs[2].SetValue(`0 issue "letsencrypt.org"`)
record, err = model.recordFromForm()
if err != nil || !strings.Contains(string(record.Data), `"value":"letsencrypt.org"`) || strings.Contains(string(record.Data), `\\"letsencrypt.org\\"`) {
t.Fatalf("quoted CAA value was not normalized: data=%s err=%v", record.Data, err)
}
model.recordInputs[0].SetValue("SRV")
model.recordInputs[1].SetValue("_https._tcp")
model.recordInputs[2].SetValue("10 5 443 target.example.com")
record, err = model.recordFromForm()
if err != nil {
t.Fatal(err)
}
if record.Priority == nil || *record.Priority != 10 || !strings.Contains(string(record.Data), `"port":443`) {
t.Fatalf("SRV record = %#v data=%s", record, record.Data)
}
model.recordInputs[2].SetValue("10 5 0 .")
if _, err := model.recordFromForm(); err != nil {
t.Fatalf("valid SRV port zero was rejected: %v", err)
}
model.records = []domain.DNSRecord{{
ID: "srv", ZoneID: "zone", Type: domain.RecordSRV, Name: "_https._tcp.example.com",
Priority: record.Priority, TTL: 300, Data: record.Data,
}}
model.openRecordForm(true)
if got := model.recordInputs[2].Value(); got != "10 5 443 target.example.com" {
t.Fatalf("structured SRV edit value = %q", got)
}
}
func TestCertificateSelectionClampsAfterFiltering(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.screen = screenCertificates
model.lineages = []domain.CertificateLineage{{ID: "first", Name: "first.example"}, {ID: "second", Name: "second.example"}}
model.rowOffset = 1
model.searchInput.SetValue("first")
model.clampSelection()
if model.rowOffset != 0 {
t.Fatalf("filtered certificate selection = %d, want 0", model.rowOffset)
}
model.openCertificateForm("export")
if model.certificateAction != "export" {
t.Fatalf("certificate action = %q", model.certificateAction)
}
}
func TestRecordFormOpensReviewBeforeMutation(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.screen = screenDNS
model.zones = []domain.Zone{{ID: "zone", Name: "example.com"}}
model.activeDNSZoneID = "zone"
model.openRecordForm(false)
model.recordInputs[0].SetValue("A")
model.recordInputs[1].SetValue("www")
model.recordInputs[2].SetValue("192.0.2.10")
model.recordInputs[3].SetValue("300")
model.recordFocus = len(model.recordInputs) - 1
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if cmd != nil || !model.confirmRecord || model.busy || model.editRecord {
t.Fatalf("record skipped review: cmd=%v confirm=%v busy=%v edit=%v", cmd != nil, model.confirmRecord, model.busy, model.editRecord)
}
if view := model.View().Content; !strings.Contains(view, "APPLY DNS CHANGE?") || !strings.Contains(view, "192.0.2.10") {
t.Fatalf("record review is incomplete: %q", view)
}
}
func TestDNSFilterKeepsActiveZoneAndUsesStructuredContent(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.screen = screenDNS
model.zones = []domain.Zone{{ID: "zone", Name: "example.com"}}
model.activeDNSZoneID = "zone"
model.records = []domain.DNSRecord{{
ID: "caa", ZoneID: "zone", Type: domain.RecordCAA, Name: "example.com", TTL: 300,
Data: []byte(`{"flags":0,"tag":"issue","value":"letsencrypt.org"}`),
}}
model.searchInput.SetValue("letsencrypt")
view := model.View().Content
if !strings.Contains(view, "DNS · example.com") || !strings.Contains(view, "letsencrypt.org") {
t.Fatalf("DNS filter lost active zone or structured content: %q", view)
}
}
func TestFiltersCoverVisibleOperationalFields(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.accounts = []domain.RemoteAccount{{ID: "account", Name: "Customer Production"}}
model.credentials = []domain.Credential{{ID: "credential", Label: "Write Token", Kind: domain.CredentialAccountToken, Capabilities: []string{"dns:write"}}}
model.zones = []domain.Zone{{ID: "zone", Name: "example.com", AccountID: "account", PreferredCredentialID: "credential", Plan: "Business"}}
model.searchInput.SetValue("customer production")
if len(model.filteredZones()) != 1 {
t.Fatal("zone filter ignored visible account name")
}
model.searchInput.SetValue("dns:write")
if len(model.filteredCredentials()) != 1 {
t.Fatal("account filter ignored visible capability")
}
model.lineages = []domain.CertificateLineage{{ID: "lineage", Name: "example.com"}}
model.certificateItems = []app.CertificateInventoryItem{{Lineage: model.lineages[0], Environment: "production", Status: "valid", Current: &domain.CertificateVersion{Issuer: "Example Issuer"}}}
model.searchInput.SetValue("example issuer")
if len(model.filteredLineages()) != 1 {
t.Fatal("certificate filter ignored visible issuer")
}
model.jobs = []domain.Job{{ID: "job", Kind: "cloudflare.sync", Message: "Loaded zones"}}
model.searchInput.SetValue("loaded zones")
if len(model.filteredJobs()) != 1 {
t.Fatal("activity filter ignored visible job message")
}
}
func TestLongZoneListKeepsSelectionVisible(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.screen = screenZones
for index := range 60 {
model.zones = append(model.zones, domain.Zone{ID: fmt.Sprintf("zone-%d", index), Name: fmt.Sprintf("zone-%02d.example", index)})
}
model.zoneIndex = 59
model.width, model.height = 120, 18
if view := model.View().Content; !strings.Contains(view, "zone-59.example") {
t.Fatalf("selected zone is outside viewport: %q", view)
}
}
func TestCertificateExportRequiresExplicitDestination(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.lineages = []domain.CertificateLineage{{ID: "lineage", Name: "example.com"}}
model.openCertificateForm("export")
if cmd := model.submitCertificateForm(); cmd != nil || model.err == nil || model.busy || model.certificateAction != "export" {
t.Fatalf("empty export destination was accepted: cmd=%v err=%v busy=%v action=%q", cmd != nil, model.err, model.busy, model.certificateAction)
}
}
func TestRevokeRequiresManuallyTypedExactLineageName(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{})
model.screen = screenCertificates
model.lineages = []domain.CertificateLineage{{ID: "lineage", Name: "example.com"}}
model.certificateItems = []app.CertificateInventoryItem{{Lineage: model.lineages[0], Environment: "production"}}
model.openCertificateForm("revoke")
if got := model.certificateInputs[1].Value(); got != "" {
t.Fatalf("exact-name revocation confirmation was prefilled: %q", got)
}
if view := model.View().Content; !strings.Contains(view, "Expected exact name:") || !strings.Contains(view, "example.com") {
t.Fatalf("revocation form does not render expected name separately: %q", view)
}
if cmd := model.submitCertificateForm(); cmd != nil || model.certificateAction != "revoke" || model.err == nil {
t.Fatalf("blank revocation confirmation was accepted: cmd=%v action=%q err=%v", cmd != nil, model.certificateAction, model.err)
}
model.certificateInputs[1].SetValue("example.com")
cmd := model.submitCertificateForm()
if cmd == nil {
t.Fatalf("exact revocation confirmation did not submit: err=%v", model.err)
}
_ = cmd()
if len(backend.revokeLineages) != 1 || backend.revokeLineages[0] != "lineage" || backend.revokeConfirmations[0] != "example.com" {
t.Fatalf("revocation call = lineages:%v confirmations:%v", backend.revokeLineages, backend.revokeConfirmations)
}
}
func TestDuplicateZoneNamesRequireIDsAndSelectedIssueRetainsLocalID(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{})
model.screen = screenCertificates
model.zones = []domain.Zone{
{ID: "zone-account-a", AccountID: "account-a", Name: "shared.example"},
{ID: "zone-account-b", AccountID: "account-b", Name: "shared.example"},
}
if _, err := model.resolveZoneValues([]string{"shared.example"}); err == nil || !strings.Contains(err.Error(), "ambiguous") {
t.Fatalf("duplicate-name zone resolution = %v, want ambiguity", err)
}
if ids, err := model.resolveZoneValues([]string{"zone-account-a"}); err != nil || len(ids) != 1 || ids[0] != "zone-account-a" {
t.Fatalf("explicit zone ID resolution = %v, %v", ids, err)
}
model.zoneIndex = 1
model.openCertificateForm("issue")
if got := model.certificateInputs[0].Value(); got != "zone-account-b" || model.certificateIssueZoneID != "zone-account-b" {
t.Fatalf("selected issue zone was not retained by local ID: input=%q retained=%q", got, model.certificateIssueZoneID)
}
model.certificateInputs[2].SetValue("ops@example.com")
cmd := model.submitCertificateForm()
if cmd == nil {
t.Fatalf("selected-ID issue did not submit: %v", model.err)
}
_ = cmd()
if len(backend.issueRequests) != 1 || len(backend.issueRequests[0].ZoneIDs) != 1 || backend.issueRequests[0].ZoneIDs[0] != "zone-account-b" {
t.Fatalf("issue request routed to wrong zone: %#v", backend.issueRequests)
}
}
func TestBusyModelRejectsOverlappingMutation(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.screen = screenDNS
model.busy = true
model.zones = []domain.Zone{{ID: "zone", Name: "example.com"}}
_, cmd := model.Update(tea.KeyPressMsg{Code: 'n', Text: "n"})
if cmd != nil || model.editRecord {
t.Fatalf("busy model opened another mutation: cmd=%v edit=%v", cmd != nil, model.editRecord)
}
}
func TestZonesNavigationLoadsTheHighlightedZoneInsteadOfOldDNSZone(t *testing.T) {
for _, test := range []struct {
name string
key tea.KeyPressMsg
}{
{name: "enter", key: tea.KeyPressMsg{Code: tea.KeyEnter}},
{name: "next screen", key: tea.KeyPressMsg{Code: 'l', Text: "l"}},
{name: "DNS shortcut", key: tea.KeyPressMsg{Code: '4', Text: "4"}},
} {
t.Run(test.name, func(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{})
model.screen = screenZones
model.zones = []domain.Zone{{ID: "zone-old", Name: "old.example"}, {ID: "zone-new", Name: "new.example"}}
model.zoneIndex = 1
model.activeDNSZoneID = "zone-old"
_, cmd := model.Update(test.key)
if cmd == nil {
t.Fatal("navigation did not start DNS zone load")
}
_ = cmd()
if model.screen != screenDNS {
t.Fatalf("screen = %d, want DNS", model.screen)
}
if len(backend.dnsZones) == 0 || backend.dnsZones[len(backend.dnsZones)-1] != "zone-new" {
t.Fatalf("DNS load zones = %#v, want zone-new", backend.dnsZones)
}
})
}
}
func TestPaletteZonesNavigationLoadsHighlightedDNSZone(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{})
model.screen = screenZones
model.zones = []domain.Zone{{ID: "zone-old", Name: "old.example"}, {ID: "zone-new", Name: "new.example"}}
model.zoneIndex = 1
model.activeDNSZoneID = "zone-old"
model.showPalette = true
model.paletteIndex = int(screenDNS)
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if cmd == nil {
t.Fatal("palette navigation did not start DNS zone load")
}
_ = cmd()
if model.screen != screenDNS || model.rowOffset != 0 {
t.Fatalf("palette navigation state = screen:%d offset:%d", model.screen, model.rowOffset)
}
if len(backend.dnsZones) == 0 || backend.dnsZones[len(backend.dnsZones)-1] != "zone-new" {
t.Fatalf("DNS load zones = %#v, want zone-new", backend.dnsZones)
}
}
func TestTLSNavigationToDNSCarriesTheActiveTLSZone(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{})
model.screen = screenTLS
model.zones = []domain.Zone{{ID: "zone-old", Name: "old.example"}, {ID: "zone-new", Name: "new.example"}}
model.activeDNSZoneID = "zone-old"
model.activeTLSZoneID = "zone-new"
model.zoneIndex = 1
_, cmd := model.Update(tea.KeyPressMsg{Code: '4', Text: "4"})
if cmd == nil || model.screen != screenDNS || model.activeDNSZoneID != "zone-new" {
t.Fatalf("TLS→DNS navigation state = cmd:%v screen:%d DNS:%q", cmd != nil, model.screen, model.activeDNSZoneID)
}
_ = cmd()
if len(backend.dnsZones) == 0 || backend.dnsZones[len(backend.dnsZones)-1] != "zone-new" {
t.Fatalf("TLS→DNS loaded stale zone: %v", backend.dnsZones)
}
}
func TestBackwardNavigationIntoTLSStartsZoneBoundLoad(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{})
model.screen = screenActivity
model.zones = []domain.Zone{{ID: "zone-a", Name: "alpha.example"}, {ID: "zone-b", Name: "beta.example"}}
model.zoneIndex = 1
_, cmd := model.Update(tea.KeyPressMsg{Code: 'h', Text: "h"})
if cmd == nil || model.screen != screenTLS || model.activeTLSZoneID != "zone-b" || !model.loading {
t.Fatalf("backward TLS navigation = cmd:%v screen:%d active:%q loading:%v", cmd != nil, model.screen, model.activeTLSZoneID, model.loading)
}
_ = cmd()
if len(backend.tlsZones) == 0 || backend.tlsZones[len(backend.tlsZones)-1] != "zone-b" {
t.Fatalf("backward TLS navigation loaded zones: %v", backend.tlsZones)
}
}
func TestStaleZoneLoadCannotOverwriteLatestRequest(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{})
first := model.startLoad("zone-old", true, false)
second := model.startLoad("zone-new", true, false)
_, _ = model.Update(first())
if !model.loading || model.tls.ZoneID != "" {
t.Fatalf("stale load was accepted: loading=%v tls=%#v", model.loading, model.tls)
}
_, _ = model.Update(second())
if model.loading || model.tls.ZoneID != "zone-new" {
t.Fatalf("latest load was not accepted: loading=%v tls=%#v", model.loading, model.tls)
}
}
func TestFailedTLSRefreshPreservesDraftButDisablesEditing(t *testing.T) {
backend := &fakeBackend{tlsErr: errors.New("Cloudflare unavailable")}
model := New(backend, Options{})
model.screen = screenTLS
model.zones = []domain.Zone{{ID: "zone", Name: "example.com"}}
model.activeTLSZoneID = "zone"
loadedAt := time.Now().UTC()
model.tls = domain.EdgeTLSSettings{ZoneID: "zone", Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true}
model.tlsDraft = model.tls
model.tlsSnapshotReady = true
model.tlsSnapshotZone = "zone"
model.tlsSnapshotAt = loadedAt
refresh := model.startLoad("zone", true, false)
if model.tlsSnapshotReady {
t.Fatal("refresh left the old snapshot marked ready")
}
_, _ = model.Update(refresh())
if model.tlsDraft.Mode != "strict" || !model.tlsDraft.AlwaysUseHTTPS || !model.tlsDraft.TLS13 {
t.Fatalf("failed refresh overwrote the prior draft: %#v", model.tlsDraft)
}
if model.tlsSnapshotReady {
t.Fatal("failed refresh produced a ready snapshot")
}
_, cmd := model.Update(tea.KeyPressMsg{Code: 'm', Text: "m"})
if cmd != nil || model.tlsDraft.Mode != "strict" {
t.Fatalf("unready TLS draft was editable: cmd=%v draft=%#v", cmd != nil, model.tlsDraft)
}
_, cmd = model.Update(tea.KeyPressMsg{Code: 's', Text: "s"})
if cmd != nil || model.confirmTLS || len(backend.updateTLSZones) != 0 {
t.Fatalf("unready TLS snapshot was applicable: cmd=%v confirm=%v calls=%v", cmd != nil, model.confirmTLS, backend.updateTLSZones)
}
}
func TestTLSSnapshotIsZoneBoundAndTimestamped(t *testing.T) {
zones := []domain.Zone{{ID: "zone-a", Name: "alpha.example"}, {ID: "zone-b", Name: "beta.example"}}
backend := &fakeBackend{zones: zones, tlsSettings: map[string]domain.EdgeTLSSettings{
"zone-a": {Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true},
}}
model := New(backend, Options{})
model.screen = screenTLS
model.zones = zones
model.activeTLSZoneID = "zone-a"
load := model.startLoad("zone-a", true, false)
_, _ = model.Update(load())
if !model.tlsSnapshotReadyForSelectedZone() || model.tlsSnapshotZone != "zone-a" || model.tls.ZoneID != "zone-a" || model.tlsSnapshotAt.IsZero() {
t.Fatalf("TLS snapshot metadata = ready:%v zone:%q settings:%#v at:%v", model.tlsSnapshotReady, model.tlsSnapshotZone, model.tls, model.tlsSnapshotAt)
}
model.activeTLSZoneID = "zone-b"
_, cmd := model.Update(tea.KeyPressMsg{Code: 's', Text: "s"})
if cmd != nil || model.confirmTLS {
t.Fatalf("zone-mismatched TLS snapshot was applicable: cmd=%v confirm=%v", cmd != nil, model.confirmTLS)
}
}
func TestTLSFilterZoneChangeReloadsAndEdgeFilterKeepsActiveZone(t *testing.T) {
zones := []domain.Zone{{ID: "zone-a", Name: "alpha.example"}, {ID: "zone-b", Name: "beta.example"}}
backend := &fakeBackend{zones: zones}
model := New(backend, Options{})
model.screen = screenTLS
model.zones = zones
model.activeTLSZoneID = "zone-a"
model.zoneIndex = 0
model.searching = true
model.searchInput.Focus()
model.searchInput.SetValue("bet")
_, cmd := model.Update(tea.KeyPressMsg{Code: 'a', Text: "a"})
if cmd == nil || model.activeTLSZoneID != "zone-b" || !model.loading {
t.Fatalf("TLS zone filter did not schedule reload: cmd=%v active=%q loading=%v", cmd != nil, model.activeTLSZoneID, model.loading)
}
message := cmd()
_, _ = model.Update(message)
if len(backend.tlsZones) == 0 || backend.tlsZones[len(backend.tlsZones)-1] != "zone-b" || !model.tlsSnapshotReadyForSelectedZone() {
t.Fatalf("TLS filter loaded zones=%v ready=%v snapshot=%q", backend.tlsZones, model.tlsSnapshotReady, model.tlsSnapshotZone)
}
model.edgeCertificates = []domain.EdgeCertificate{{ID: "edge", ZoneID: "zone-b", Type: "universal", Status: "active"}}
model.searchInput.SetValue("universal")
if reload := model.reloadTLSAfterFilterChange("zone-b"); reload != nil || model.activeTLSZoneID != "zone-b" {
t.Fatalf("edge-only TLS filter changed the active zone: reload=%v active=%q", reload != nil, model.activeTLSZoneID)
}
if view := model.View().Content; !strings.Contains(view, "universal") || strings.Contains(view, "No zone selected") {
t.Fatalf("edge-only filter hid the active TLS view: %q", view)
}
}
func TestLoadingModelRejectsMutations(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.screen = screenTLS
model.loading = true
model.zones = []domain.Zone{{ID: "zone", Name: "example.com"}}
_, cmd := model.Update(tea.KeyPressMsg{Code: 's', Text: "s"})
if cmd != nil || model.confirmTLS {
t.Fatalf("loading model opened TLS confirmation: cmd=%v confirm=%v", cmd != nil, model.confirmTLS)
}
if model.toast != "Loading the latest zone state" {
t.Fatalf("loading mutation toast = %q", model.toast)
}
}
func TestUnlockEnterCannotStartConcurrentRecovery(t *testing.T) {
backend := &fakeBackend{locked: true}
model := New(backend, Options{})
model.busy = true
model.unlockInputs[0].SetValue("password")
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if cmd != nil || backend.unlockCalls != 0 {
t.Fatalf("busy unlock started again: cmd=%v calls=%d", cmd != nil, backend.unlockCalls)
}
}
type nonFatalUnlockWarning struct{}
func (nonFatalUnlockWarning) Error() string { return "recovery warning" }
func (nonFatalUnlockWarning) NonFatal() bool { return true }
func TestNonFatalRecoveryWarningLeavesUnlockScreen(t *testing.T) {
model := New(&fakeBackend{locked: true}, Options{})
_, cmd := model.Update(unlockMsg{err: nonFatalUnlockWarning{}})
if cmd == nil || model.unlock || model.err == nil {
t.Fatalf("nonfatal recovery state = cmd:%v unlock:%v err:%v", cmd != nil, model.unlock, model.err)
}
if model.toast != "Vault unlocked; recovery requires attention" {
t.Fatalf("recovery warning toast = %q", model.toast)
}
}
func TestPersistedRecoveryIssueBlocksTUIAndPaletteMutations(t *testing.T) {
issue := domain.HealthIssue{Kind: "certificate_commit_recovery_failed", ResourceID: "certificate-commit-recovery"}
for _, palette := range []bool{false, true} {
model := New(&fakeBackend{}, Options{})
_, _ = model.Update(loadMsg{dashboard: domain.DashboardSnapshot{Issues: []domain.HealthIssue{issue}}})
model.screen = screenDashboard
if palette {
model.showPalette = true
model.paletteIndex = len(screens)
}
key := tea.KeyPressMsg{Code: 'a', Text: "a"}
if palette {
key = tea.KeyPressMsg{Code: tea.KeyEnter}
}
_, cmd := model.Update(key)
if cmd != nil || model.addCredential {
t.Fatalf("recovery-blocked mutation (palette=%v) = cmd:%v form:%v", palette, cmd != nil, model.addCredential)
}
if !strings.Contains(model.toast, "Crash recovery") {
t.Fatalf("recovery-blocked toast (palette=%v) = %q", palette, model.toast)
}
}
}
func TestRecoveryRetryUsesUnlockedVaultPathAndReloadsOnSuccess(t *testing.T) {
backend := &fakeBackend{}
model := New(backend, Options{})
model.recoveryBlocked = true
_, cmd := model.Update(tea.KeyPressMsg{Code: 'R', Text: "R"})
if cmd == nil || !model.busy {
t.Fatalf("recovery retry did not start: cmd=%v busy=%v", cmd != nil, model.busy)
}
message := cmd()
if backend.unlockNilCalls != 1 {
t.Fatalf("recovery retry did not call UnlockVault with nil password: nil calls=%d", backend.unlockNilCalls)
}
_, reload := model.Update(message)
if reload == nil || model.recoveryBlocked || !model.busy {
t.Fatalf("successful recovery did not clear/reload safely: reload=%v blocked=%v busy=%v", reload != nil, model.recoveryBlocked, model.busy)
}
_, _ = model.Update(reload())
if model.busy || model.recoveryBlocked {
t.Fatalf("recovery reload did not settle: busy=%v blocked=%v", model.busy, model.recoveryBlocked)
}
}
func TestRecoveryRetryWarningRetainsStickyBlockAndAdvertisesRetry(t *testing.T) {
backend := &fakeBackend{unlockErr: nonFatalUnlockWarning{}}
model := New(backend, Options{})
model.recoveryBlocked = true
if footer := model.renderFooter(); !strings.Contains(footer, "retry recovery") {
t.Fatalf("recovery footer does not advertise retry: %q", footer)
}
model.showHelp = true
if help := model.renderHelp(); !strings.Contains(help, "Retry blocked crash recovery") {
t.Fatalf("recovery help does not advertise retry: %q", help)
}
model.showHelp = false
_, cmd := model.Update(tea.KeyPressMsg{Code: 'R', Text: "R"})
if cmd == nil {
t.Fatal("recovery warning retry did not start")
}
_, reload := model.Update(cmd())
if reload != nil || !model.recoveryBlocked || model.busy || model.err == nil {
t.Fatalf("warning did not retain recovery block: reload=%v blocked=%v busy=%v err=%v", reload != nil, model.recoveryBlocked, model.busy, model.err)
}
}
func TestUnrelatedLoadDoesNotReleaseBusyMutation(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.busy = true
model.loading = true
_, _ = model.Update(loadMsg{})
if !model.busy {
t.Fatal("unrelated load released the active mutation lock")
}
if model.loading {
t.Fatal("completed load left the loading indicator active")
}
}
func TestOperationReloadReleasesBusyOnlyAfterItsLoad(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.busy = true
_, reload := model.Update(operationMsg{message: "saved", reload: true})
if reload == nil || !model.busy || !model.loading {
t.Fatalf("operation reload state = cmd:%v busy:%v loading:%v", reload != nil, model.busy, model.loading)
}
// A navigation/background load may finish before the operation's own reload.
_, _ = model.Update(loadMsg{})
if !model.busy {
t.Fatal("unrelated load released the operation reload lock")
}
message := reload()
completed, ok := message.(loadMsg)
if !ok || !completed.releasesBusy {
t.Fatalf("operation reload message = %#v", message)
}
_, _ = model.Update(completed)
if model.busy || model.loading {
t.Fatalf("operation reload did not release lock: busy:%v loading:%v", model.busy, model.loading)
}
}
func TestNavigationLoadInheritsPendingOperationBusyRelease(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.busy = true
_, operationReload := model.Update(operationMsg{message: "saved", reload: true})
if operationReload == nil || !model.busyReleasePending {
t.Fatalf("operation reload did not establish release obligation")
}
navigationLoad := model.startLoad("zone-new", true, false)
_, _ = model.Update(operationReload())
if !model.busy {
t.Fatal("stale operation reload released busy before the latest load")
}
latest := navigationLoad()
message, ok := latest.(loadMsg)
if !ok || !message.releasesBusy {
t.Fatalf("navigation load did not inherit busy release: %#v", latest)
}
_, _ = model.Update(message)
if model.busy || model.busyReleasePending {
t.Fatalf("latest navigation load left busy locked: busy=%v pending=%v", model.busy, model.busyReleasePending)
}
}
func TestBusyCommandPaletteRejectsMutationEntries(t *testing.T) {
for _, test := range []struct {
name string
index int
}{
{name: "add credential", index: len(screens)},
{name: "synchronize", index: len(screens) + 1},
} {
t.Run(test.name, func(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.busy = true
model.showPalette = true
model.paletteIndex = test.index
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if cmd != nil || !model.busy || model.addCredential {
t.Fatalf("busy palette mutation = cmd:%v busy:%v form:%v", cmd != nil, model.busy, model.addCredential)
}
if model.toast != "An operation is already running" {
t.Fatalf("busy palette toast = %q", model.toast)
}
})
}
}
func TestLoadingCommandPaletteRejectsMutationEntries(t *testing.T) {
model := New(&fakeBackend{}, Options{})
model.loading = true
model.showPalette = true
model.paletteIndex = len(screens) + 1
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if cmd != nil || model.busy {
t.Fatalf("loading palette started sync: cmd=%v busy=%v", cmd != nil, model.busy)
}
if model.toast != "Loading the latest zone state" {
t.Fatalf("loading palette toast = %q", model.toast)
}
}
func TestFirstRunVaultRequiresConfirmation(t *testing.T) {
backend := &fakeBackend{locked: true}
model := New(backend, Options{FirstRun: true})
if !model.unlock || len(model.unlockInputs) != 2 {
t.Fatalf("first-run unlock state = %#v", model)
}
view := model.View().Content
if !strings.Contains(view, "CREATE LOCAL VAULT") || !strings.Contains(view, "Confirm password") {
t.Fatalf("first-run view missing setup copy")
}
}
func TestFirstRunRejectsShortVaultPassword(t *testing.T) {
backend := &fakeBackend{locked: true}
model := New(backend, Options{FirstRun: true})
model.unlockInputs[0].SetValue("short")
model.unlockInputs[1].SetValue("short")
model.unlockFocus = 1
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if cmd != nil || model.err == nil || !strings.Contains(model.err.Error(), "at least 10") {
t.Fatalf("short first-run password was not rejected: err=%v cmd=%v", model.err, cmd != nil)
}
}
func TestExistingVaultAcceptsLegacyShortPassword(t *testing.T) {
backend := &fakeBackend{locked: true}
model := New(backend, Options{FirstRun: false})
model.unlockInputs[0].SetValue("short")
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if cmd == nil || model.err != nil {
t.Fatalf("legacy password should be sent to the vault: err=%v cmd=%v", model.err, cmd != nil)
}
message := cmd()
if result, ok := message.(unlockMsg); !ok || result.err != nil || backend.locked {
t.Fatalf("unlock result = %#v, locked=%v", message, backend.locked)
}
}
type fakeBackend struct {
locked bool
unlockCalls int
unlockNilCalls int
unlockErr error
dnsZones []string
zones []domain.Zone
deleteCalls int
tlsSettings map[string]domain.EdgeTLSSettings
tlsErr error
tlsZones []string
updateTLSZones []string
updateTLSDrafts []domain.EdgeTLSSettings
issueRequests []app.IssueZonesRequest
revokeLineages []string
revokeConfirmations []string
}
func (f *fakeBackend) VaultLocked() bool { return f.locked }
func (f *fakeBackend) UnlockVault(_ context.Context, password []byte) error {
f.unlockCalls++
if password == nil {
f.unlockNilCalls++
}
if f.unlockErr == nil {
f.locked = false
}
return f.unlockErr
}
func (f *fakeBackend) Dashboard(context.Context) (domain.DashboardSnapshot, error) {
return domain.DashboardSnapshot{}, nil
}
func (f *fakeBackend) Credentials(context.Context) ([]domain.Credential, error) { return nil, nil }
func (f *fakeBackend) Accounts(context.Context) ([]domain.RemoteAccount, error) { return nil, nil }
func (f *fakeBackend) Zones(context.Context) ([]domain.Zone, error) { return f.zones, nil }
func (f *fakeBackend) DNSRecords(_ context.Context, zoneID string) ([]domain.DNSRecord, error) {
f.dnsZones = append(f.dnsZones, zoneID)
return nil, nil
}
func (f *fakeBackend) Certificates(context.Context) ([]domain.CertificateLineage, error) {
return nil, nil
}
func (f *fakeBackend) CertificateInventory(context.Context) ([]app.CertificateInventoryItem, error) {
return nil, nil
}
func (f *fakeBackend) Jobs(context.Context, int) ([]domain.Job, error) { return nil, nil }
func (f *fakeBackend) Audit(context.Context, int) ([]domain.AuditEvent, error) { return nil, nil }
func (f *fakeBackend) AddCloudflareCredential(context.Context, app.AddCredentialInput) (domain.Credential, error) {
return domain.Credential{}, nil
}
func (f *fakeBackend) SyncAll(context.Context) ([]domain.Job, error) { return nil, nil }
func (f *fakeBackend) CreateDNSRecord(context.Context, string, domain.DNSRecord) (domain.DNSRecord, error) {
return domain.DNSRecord{}, nil
}
func (f *fakeBackend) PatchDNSRecord(context.Context, string, string, domain.DNSRecord) (domain.DNSRecord, error) {
return domain.DNSRecord{}, nil
}
func (f *fakeBackend) DeleteDNSRecord(context.Context, string, string) error {
f.deleteCalls++
return nil
}
func (f *fakeBackend) TLSSettings(_ context.Context, zoneID string, _ bool) (domain.EdgeTLSSettings, error) {
f.tlsZones = append(f.tlsZones, zoneID)
if f.tlsErr != nil {
return domain.EdgeTLSSettings{}, f.tlsErr
}
if settings, ok := f.tlsSettings[zoneID]; ok {
return settings, nil
}
return domain.EdgeTLSSettings{ZoneID: zoneID, Mode: "strict", MinimumTLS: "1.2", TLS13: true}, nil
}
func (f *fakeBackend) EdgeCertificates(context.Context, string) ([]domain.EdgeCertificate, error) {
return nil, nil
}
func (f *fakeBackend) UpdateTLSSettings(_ context.Context, zoneID string, draft domain.EdgeTLSSettings) (domain.EdgeTLSSettings, error) {
f.updateTLSZones = append(f.updateTLSZones, zoneID)
f.updateTLSDrafts = append(f.updateTLSDrafts, draft)
return draft, nil
}
func (f *fakeBackend) IssueCertificates(_ context.Context, request app.IssueZonesRequest) (app.IssueZonesResult, error) {
f.issueRequests = append(f.issueRequests, request)
return app.IssueZonesResult{}, nil
}
func (f *fakeBackend) ImportCertificateMetadata(context.Context, string, string, string) (domain.CertificateLineage, domain.CertificateVersion, error) {
return domain.CertificateLineage{}, domain.CertificateVersion{}, nil
}
func (f *fakeBackend) ExportCertificate(context.Context, string, string) (string, error) {
return "", nil
}
func (f *fakeBackend) RevokeCertificate(_ context.Context, lineageID, _ string, confirmation string, _ *uint) error {
f.revokeLineages = append(f.revokeLineages, lineageID)
f.revokeConfirmations = append(f.revokeConfirmations, confirmation)
return nil
}
func (f *fakeBackend) RenewCertificates(context.Context, string, bool) (app.IssueZonesResult, error) {
return app.IssueZonesResult{}, nil
}
+762
View File
@@ -0,0 +1,762 @@
package tui
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"charm.land/lipgloss/v2"
"github.com/MeghdadFadaee/domainops/internal/app"
"github.com/MeghdadFadaee/domainops/internal/domain"
)
func (m *Model) render() string {
if m.terminalUndersized() {
message := m.theme.modal.Width(min(52, max(20, m.width-4))).Render(
m.theme.brand.Render("DOMAINOPS") + "\n\n" +
"The terminal is too small for a safe operator view.\n" +
m.theme.mutedText.Render(fmt.Sprintf("Current %d×%d · minimum 64×18", m.width, m.height)),
)
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, message))
}
if m.unlock {
return m.renderUnlock()
}
if m.addCredential {
return m.renderCredentialForm()
}
if m.editRecord {
return m.renderRecordForm()
}
if m.certificateAction != "" {
return m.renderCertificateForm()
}
if m.confirmRecord {
return m.renderRecordConfirmation()
}
if m.confirmDelete {
return m.renderDeleteConfirmation()
}
if m.confirmTLS {
return m.renderTLSConfirmation()
}
if m.showHelp {
return m.renderHelp()
}
if m.showPalette {
return m.renderPalette()
}
header := m.renderHeader()
foot := m.renderFooter()
bodyHeight := max(1, m.height-lipgloss.Height(header)-lipgloss.Height(foot))
sidebarWidth := 23
if m.width < 88 {
sidebarWidth = 15
}
mainWidth := max(20, m.width-sidebarWidth)
sidebar := m.renderSidebar(sidebarWidth, bodyHeight)
main := m.theme.app.Width(mainWidth).Height(bodyHeight).Padding(1, 1).Render(m.renderScreen(mainWidth-2, bodyHeight-2))
body := lipgloss.JoinHorizontal(lipgloss.Top, sidebar, main)
return m.theme.app.Width(m.width).Height(m.height).Render(header + "\n" + body + "\n" + foot)
}
func (m *Model) renderHeader() string {
brand := m.theme.brand.Render("◆ DOMAINOPS")
section := m.theme.mutedText.Render(" / " + screens[m.screen].name)
left := brand + section
state := m.theme.statusOK.Render("● READY")
if m.busy || m.loading {
state = m.theme.statusWarn.Render("◌ WORKING")
} else if m.err != nil {
state = m.theme.statusBad.Render("● ATTENTION")
}
version := m.options.Version
if version == "" {
version = "dev"
}
right := m.theme.mutedText.Render(version) + " " + state
space := strings.Repeat(" ", max(1, m.width-lipgloss.Width(left)-lipgloss.Width(right)-4))
return m.theme.header.Width(m.width).Render(left + space + right)
}
func (m *Model) renderFooter() string {
left := m.theme.key.Render("?") + " help " + m.theme.key.Render("Ctrl+K") + " commands " + m.theme.key.Render("/") + " filter"
right := m.theme.key.Render("r") + " sync " + m.theme.key.Render("q") + " quit"
if m.recoveryBlocked {
right = m.theme.key.Render("R") + " retry recovery " + m.theme.key.Render("q") + " quit"
}
if m.searching {
left = m.searchInput.View()
} else if m.filterValue() != "" {
left = m.theme.statusWarn.Render("FILTER: ") + m.searchInput.Value() + " " + m.theme.mutedText.Render("/ to edit")
}
if m.err != nil {
left = m.theme.statusBad.Render("! ") + truncate(m.err.Error(), max(16, m.width-lipgloss.Width(right)-8))
} else if m.toast != "" && time.Since(m.toastAt) < 12*time.Second {
left = m.theme.statusOK.Render("✓ ") + m.toast
}
space := strings.Repeat(" ", max(1, m.width-lipgloss.Width(left)-lipgloss.Width(right)-2))
return m.theme.header.Width(m.width).Render(left + space + right)
}
func (m *Model) renderSidebar(width, height int) string {
var lines []string
for i, item := range screens {
label := fmt.Sprintf("%d %s %s", i+1, item.icon, item.name)
if width < 18 {
label = fmt.Sprintf("%d %s %s", i+1, item.icon, truncate(item.name, 7))
}
style := m.theme.nav.Width(width - 3)
if screen(i) == m.screen {
style = m.theme.navActive.Width(width - 3)
}
lines = append(lines, style.Render(label))
}
lines = append(lines, "", m.theme.mutedText.Render("WORKSPACE"))
if zone, ok := m.selectedZone(); ok {
lines = append(lines, m.theme.panelTitle.Render(truncate(zone.Name, width-4)), m.theme.mutedText.Render(strings.ToUpper(string(zone.Status))))
} else {
lines = append(lines, m.theme.mutedText.Render("No zone selected"))
}
return m.theme.sidebar.Width(width).Height(height).Render(strings.Join(lines, "\n"))
}
func (m *Model) renderScreen(width, height int) string {
if m.loading && len(m.zones) == 0 && m.screen != screenDashboard {
return m.emptyState("Synchronizing local state…", "The view will update without blocking the terminal.", width, height)
}
switch m.screen {
case screenDashboard:
return m.renderDashboard(width, height)
case screenAccounts:
return m.renderAccounts(width, height)
case screenZones:
return m.renderZones(width, height)
case screenDNS:
return m.renderDNS(width, height)
case screenCertificates:
return m.renderCertificates(width, height)
case screenTLS:
return m.renderTLS(width, height)
case screenActivity:
return m.renderActivity(width, height)
default:
return ""
}
}
func (m *Model) renderDashboard(width, height int) string {
if len(m.credentials) == 0 {
body := m.theme.brand.Render("Welcome to DomainOps") + "\n\n" +
"Connect a scoped Cloudflare API token to build your live domain inventory.\n" +
m.theme.mutedText.Render("Recommended scopes: Zone Read, DNS Read/Write, and optional Zone Settings Read/Write.") + "\n\n" +
m.theme.key.Render("a") + " Add your first Cloudflare account"
return m.panel("GET STARTED", body, width, min(height, 12))
}
cardGap := 1
columns := 3
if width < 78 {
columns = 2
}
cardWidth := max(15, (width-(columns-1)*cardGap)/columns)
cards := []string{
m.statCard("ACCOUNTS", m.dashboard.Accounts, "connected", cardWidth),
m.statCard("ZONES", m.dashboard.Zones, "managed", cardWidth),
m.statCard("DNS RECORDS", m.dashboard.DNSRecords, "cached", cardWidth),
m.statCard("CERTIFICATES", m.dashboard.Certificates, "tracked", cardWidth),
m.statCard("RENEWAL DUE", m.dashboard.CertificatesDue, "action needed", cardWidth),
m.statCard("EXPIRED", m.dashboard.CertificatesExpired, "critical", cardWidth),
m.statCard("ACTIVE JOBS", m.dashboard.ActiveJobs, "background", cardWidth),
}
var rows []string
for i := 0; i < len(cards); i += columns {
end := min(i+columns, len(cards))
rows = append(rows, lipgloss.JoinHorizontal(lipgloss.Top, intersperse(cards[i:end], strings.Repeat(" ", cardGap))...))
}
stats := strings.Join(rows, "\n")
remaining := max(6, height-lipgloss.Height(stats)-1)
issues := m.renderIssues(width, remaining)
return stats + "\n" + issues
}
func (m *Model) statCard(label string, value int, note string, width int) string {
valueStyle := m.theme.brand.Copy().Bold(true)
body := m.theme.mutedText.Render(label) + "\n" + valueStyle.Render(fmt.Sprintf("%d", value)) + " " + m.theme.mutedText.Render(note)
return m.theme.panel.Width(width - 2).Height(3).Render(body)
}
func (m *Model) renderIssues(width, height int) string {
issues := append([]domain.HealthIssue(nil), m.dashboard.Issues...)
sort.SliceStable(issues, func(i, j int) bool { return severityRank(issues[i].Severity) > severityRank(issues[j].Severity) })
var rows []string
limit := max(1, height-3)
for i, issue := range issues {
if i >= limit {
break
}
marker := m.theme.mutedText.Render("●")
switch issue.Severity {
case domain.SeverityCritical:
marker = m.theme.statusBad.Render("●")
case domain.SeverityWarning:
marker = m.theme.statusWarn.Render("●")
default:
marker = m.theme.statusOK.Render("●")
}
rows = append(rows, marker+" "+truncate(issue.Title, width-10)+" "+m.theme.mutedText.Render(truncate(issue.Detail, max(0, width-len(issue.Title)-16))))
}
if len(rows) == 0 {
rows = []string{m.theme.statusOK.Render("✓ No urgent findings"), m.theme.mutedText.Render("Run a sync to refresh DNS and public certificate observations.")}
}
return m.panel("ACTION QUEUE", strings.Join(rows, "\n"), width, height)
}
func (m *Model) renderAccounts(width, height int) string {
values := m.filteredCredentials()
if len(values) == 0 {
return m.emptyState("No Cloudflare accounts", "Press a to add a scoped API token.", width, height)
}
header := row(width, []cell{{"LABEL", 28}, {"TOKEN", 18}, {"STATUS", 14}, {"CAPABILITIES", 40}})
rows := []string{m.theme.mutedText.Render(header)}
reserved := 0
if len(m.accounts) > 0 {
reserved = 4
}
limit := max(1, height-4-reserved)
start := viewportStart(m.rowOffset, limit, len(values))
for i := start; i < len(values) && i < start+limit; i++ {
value := values[i]
status := string(value.Status)
line := row(width, []cell{{value.Label, 28}, {string(value.Kind), 18}, {status, 14}, {strings.Join(value.Capabilities, ", "), 40}})
if i == m.rowOffset {
line = m.theme.selected.Width(width - 2).Render(line)
}
rows = append(rows, line)
}
if len(m.accounts) > 0 {
names := make([]string, 0, len(m.accounts))
for _, account := range m.accounts {
names = append(names, account.Name)
}
rows = append(rows, "", m.theme.panelTitle.Render(fmt.Sprintf("REMOTE ACCOUNTS · %d", len(m.accounts))), m.theme.mutedText.Render(truncate(strings.Join(names, " · "), max(1, width-6))))
}
return m.panel("CLOUDFLARE CONNECTIONS · a add · r sync", strings.Join(rows, "\n"), width, height)
}
func (m *Model) renderZones(width, height int) string {
values := m.filteredZones()
if len(values) == 0 {
return m.emptyState("No zones found", "Add an account or synchronize Cloudflare.", width, height)
}
header := row(width, []cell{{"ZONE", 32}, {"ACCOUNT", 24}, {"CONNECTION", 22}, {"STATUS", 14}, {"PLAN", 14}})
rows := []string{m.theme.mutedText.Render(header)}
limit := max(1, height-4)
start := viewportStart(m.zoneIndex, limit, len(values))
for i := start; i < len(values) && i < start+limit; i++ {
value := values[i]
line := row(width, []cell{{value.Name, 32}, {m.accountLabel(value.AccountID), 24}, {m.credentialLabel(value.PreferredCredentialID), 22}, {string(value.Status), 14}, {value.Plan, 14}})
if i == m.zoneIndex {
line = m.theme.selected.Width(width - 2).Render(line)
}
rows = append(rows, line)
}
return m.panel("ZONES · Enter open DNS · j/k select", strings.Join(rows, "\n"), width, height)
}
func (m *Model) accountLabel(id string) string {
for _, account := range m.accounts {
if account.ID == id {
return account.Name
}
}
return id
}
func (m *Model) credentialLabel(id string) string {
for _, credential := range m.credentials {
if credential.ID == id {
return credential.Label
}
}
return id
}
func (m *Model) renderDNS(width, height int) string {
zone, ok := m.selectedZone()
if !ok {
return m.emptyState("Select a zone", "Synchronize a Cloudflare account first.", width, height)
}
values := m.filteredRecords()
if len(values) == 0 {
return m.emptyState("No records in "+zone.Name, "Press n to create an A, AAAA, CNAME, TXT, MX, CAA, NS, or SRV record.", width, height)
}
header := row(width, []cell{{"TYPE", 8}, {"NAME", 34}, {"CONTENT", 42}, {"PROXY", 10}, {"TTL", 10}})
rows := []string{m.theme.mutedText.Render(header)}
limit := max(1, height-4)
start := 0
if m.recordIndex >= limit {
start = m.recordIndex - limit + 1
}
for i := start; i < len(values) && i < start+limit; i++ {
value := values[i]
proxy := "DNS only"
if value.Proxied {
proxy = "proxied"
}
ttl := fmt.Sprintf("%ds", value.TTL)
if value.TTL <= 1 {
ttl = "Auto"
}
line := row(width, []cell{{string(value.Type), 8}, {value.Name, 34}, {displayRecordContent(value), 42}, {proxy, 10}, {ttl, 10}})
if i == m.recordIndex {
line = m.theme.selected.Width(width - 2).Render(line)
}
if !value.Type.Editable() || value.Managed {
line = m.theme.mutedText.Render(line)
}
rows = append(rows, line)
}
title := fmt.Sprintf("DNS · %s · n new e edit d delete Ctrl+P proxy", zone.Name)
return m.panel(title, strings.Join(rows, "\n"), width, height)
}
func (m *Model) renderCertificates(width, height int) string {
values := m.filteredLineages()
if len(values) == 0 {
return m.emptyState("No certificates tracked", "Press n to issue a managed certificate or i to import PEM metadata.", width, height)
}
header := row(width, []cell{{"LINEAGE", 26}, {"ENV", 11}, {"STATUS", 11}, {"EXPIRES", 13}, {"ISSUER", 30}, {"IDENTIFIERS", 40}})
rows := []string{m.theme.mutedText.Render(header)}
limit := max(1, height-4)
start := viewportStart(m.rowOffset, limit, len(values))
for i := start; i < len(values) && i < start+limit; i++ {
value := values[i]
item := m.certificateItem(value.ID)
expires, issuer := "—", "—"
if item.Current != nil {
expires = item.Current.NotAfter.Local().Format("2006-01-02")
issuer = item.Current.Issuer
}
line := row(width, []cell{{value.Name, 26}, {item.Environment, 11}, {item.Status, 11}, {expires, 13}, {issuer, 30}, {strings.Join(value.Identifiers, ", "), 40}})
if i == m.rowOffset {
line = m.theme.selected.Width(width - 2).Render(line)
}
rows = append(rows, line)
}
return m.panel("CERTIFICATE INVENTORY · n issue u renew due i import x export d revoke", strings.Join(rows, "\n"), width, height)
}
func (m *Model) certificateItem(lineageID string) app.CertificateInventoryItem {
for _, item := range m.certificateItems {
if item.Lineage.ID == lineageID {
return item
}
}
for _, lineage := range m.lineages {
if lineage.ID == lineageID {
return app.CertificateInventoryItem{Lineage: lineage, Environment: "unknown", Status: "unknown"}
}
}
return app.CertificateInventoryItem{Environment: "unknown", Status: "unknown"}
}
func (m *Model) renderTLS(width, height int) string {
zone, ok := m.selectedZone()
if !ok {
return m.emptyState("No zone selected", "Cloudflare TLS settings are zone-specific.", width, height)
}
if !m.tlsSnapshotReadyForSelectedZone() {
detail := "A verified TLS snapshot has not loaded for this zone. Leave and reopen this view to retry."
if m.loading {
detail = "Loading a fresh, zone-bound Cloudflare TLS snapshot…"
}
return m.emptyState("TLS snapshot unavailable for "+zone.Name, detail, width, height)
}
value := func(enabled bool) string {
if enabled {
return m.theme.statusOK.Render("ENABLED")
}
return m.theme.mutedText.Render("DISABLED")
}
modeStyle := m.theme.statusOK
if m.tlsDraft.Mode == "flexible" || m.tlsDraft.Mode == "off" {
modeStyle = m.theme.statusWarn
}
body := m.theme.mutedText.Render("Cloudflare edge and origin controls are separate from your local Let’s Encrypt files.") + "\n" +
m.theme.mutedText.Render("Verified for "+zone.Name+" · loaded "+m.tlsSnapshotAt.Local().Format("Jan 02 15:04:05")) + "\n\n" +
row(width-8, []cell{{"Origin encryption mode", 34}, {modeStyle.Render(strings.ToUpper(m.tlsDraft.Mode)), 28}, {"m to cycle", 18}}) + "\n" +
row(width-8, []cell{{"Always Use HTTPS", 34}, {value(m.tlsDraft.AlwaysUseHTTPS), 28}, {"h to toggle", 18}}) + "\n" +
row(width-8, []cell{{"TLS 1.3", 34}, {value(m.tlsDraft.TLS13), 28}, {"t to toggle", 18}}) + "\n" +
row(width-8, []cell{{"Minimum TLS", 34}, {m.tlsDraft.MinimumTLS, 28}, {"v to cycle", 22}}) + "\n\n" +
m.theme.statusWarn.Render("Changes can interrupt proxied traffic. Review the diff, then press s to apply.")
edgeCertificates := m.filteredEdgeCertificates()
if len(edgeCertificates) > 0 {
body += "\n\n" + m.theme.panelTitle.Render("EDGE CERTIFICATE PACKS")
for _, certificate := range edgeCertificates {
expiry := "managed by Cloudflare"
if certificate.ExpiresAt != nil {
expiry = certificate.ExpiresAt.Local().Format("2006-01-02")
}
body += "\n" + row(width-8, []cell{{certificate.Type, 20}, {certificate.Status, 16}, {strings.Join(certificate.Hosts, ", "), 44}, {expiry, 18}})
}
}
return m.panel("CLOUDFLARE TLS · "+zone.Name, body, width, height)
}
func (m *Model) renderActivity(width, height int) string {
jobs, audit := m.filteredJobs(), m.filteredAudit()
if len(jobs) == 0 && len(audit) == 0 {
return m.emptyState("No activity yet", "Synchronization and certificate jobs will appear here.", width, height)
}
header := row(width, []cell{{"STATE", 14}, {"KIND", 24}, {"PROGRESS", 12}, {"MESSAGE", 48}, {"UPDATED", 20}})
rows := []string{m.theme.mutedText.Render(header)}
limit := max(1, height-4)
jobLimit := max(1, limit/2+1)
start := viewportStart(m.rowOffset, jobLimit, len(jobs))
for i := start; i < len(jobs) && i < start+jobLimit; i++ {
value := jobs[i]
line := row(width, []cell{{string(value.State), 14}, {value.Kind, 24}, {fmt.Sprintf("%d%%", value.Progress), 12}, {value.Message, 48}, {value.UpdatedAt.Local().Format("Jan 02 15:04"), 20}})
if i == m.rowOffset {
line = m.theme.selected.Width(width - 2).Render(line)
}
rows = append(rows, line)
}
if len(audit) > 0 {
rows = append(rows, "", m.theme.panelTitle.Render("AUDIT TRAIL"), m.theme.mutedText.Render(row(width, []cell{{"TIME", 18}, {"ACTION", 24}, {"RESOURCE", 34}, {"CHANGE", 56}})))
remaining := max(1, limit-len(rows)+2)
for i, event := range audit {
if i >= remaining {
break
}
rows = append(rows, row(width, []cell{{event.CreatedAt.Local().Format("Jan 02 15:04"), 18}, {event.Action, 24}, {event.ResourceID, 34}, {auditChange(event), 56}}))
}
}
return m.panel("DURABLE ACTIVITY & AUDIT", strings.Join(rows, "\n"), width, height)
}
func viewportStart(selected, limit, total int) int {
if limit <= 0 || total <= limit {
return 0
}
start := selected - limit + 1
if start < 0 {
start = 0
}
if start+limit > total {
start = total - limit
}
return start
}
func auditChange(event domain.AuditEvent) string {
compact := func(value []byte) string {
if len(value) == 0 {
return "∅"
}
var buffer bytes.Buffer
if json.Compact(&buffer, value) == nil {
return buffer.String()
}
return string(value)
}
return compact(event.Before) + " → " + compact(event.After)
}
func (m *Model) panel(title, body string, width, height int) string {
if height < 3 {
height = 3
}
return m.theme.panel.Width(max(8, width-2)).Height(max(1, height-2)).Render(m.theme.panelTitle.Render(title) + "\n" + body)
}
func (m *Model) emptyState(title, detail string, width, height int) string {
body := m.theme.brand.Render(title) + "\n\n" + m.theme.mutedText.Render(detail)
return m.theme.panel.Width(max(20, width-2)).Height(max(5, height-2)).Align(lipgloss.Center, lipgloss.Center).Render(body)
}
func (m *Model) renderUnlock() string {
title := "UNLOCK DOMAINOPS"
detail := "Enter your local vault password. It never leaves this machine."
if m.unlockFirst {
title = "CREATE LOCAL VAULT"
detail = "Protect Cloudflare tokens and private keys with a local password."
}
lines := []string{m.theme.brand.Render(title), "", m.theme.mutedText.Render(detail), ""}
labels := []string{"Password", "Confirm password"}
for i, input := range m.unlockInputs {
label := labels[i]
if i == m.unlockFocus {
label = m.theme.panelTitle.Render(label)
} else {
label = m.theme.mutedText.Render(label)
}
lines = append(lines, label, input.View(), "")
}
if m.err != nil {
lines = append(lines, m.theme.statusBad.Render("! "+m.err.Error()), "")
}
if m.busy {
lines = append(lines, m.theme.statusWarn.Render("Unlocking…"))
} else {
lines = append(lines, m.theme.mutedText.Render("Tab to move · Enter to continue · Ctrl+C to quit"))
}
modal := m.theme.modal.Width(min(62, m.width-8)).Render(strings.Join(lines, "\n"))
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
}
func (m *Model) renderCredentialForm() string {
labels := []string{"Connection label", "Scoped API token", "Account ID (optional)"}
lines := []string{m.theme.brand.Render("ADD CLOUDFLARE CONNECTION"), "", m.theme.mutedText.Render("User tokens can discover multiple accounts. Add an Account ID only for account-owned tokens."), ""}
for i, input := range m.credentialInputs {
label := m.theme.mutedText.Render(labels[i])
if i == m.credentialFocus {
label = m.theme.panelTitle.Render(labels[i])
}
lines = append(lines, label, input.View(), "")
}
if m.err != nil {
lines = append(lines, m.theme.statusBad.Render("! "+m.err.Error()), "")
}
lines = append(lines, m.theme.mutedText.Render("Tab to move · Enter to verify and save · Esc to cancel"))
modal := m.theme.modal.Width(min(72, m.width-8)).Render(strings.Join(lines, "\n"))
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
}
func (m *Model) renderRecordForm() string {
labels := []string{"Record type", "Name", "Content", "TTL", "Priority"}
title := "CREATE DNS RECORD"
if m.recordEditing {
title = "EDIT DNS RECORD"
}
lines := []string{m.theme.brand.Render(title), ""}
for i, input := range m.recordInputs {
label := m.theme.mutedText.Render(labels[i])
if i == m.recordFocus {
label = m.theme.panelTitle.Render(labels[i])
}
lines = append(lines, label, input.View())
}
proxy := m.theme.mutedText.Render("DNS only")
if m.recordProxied {
proxy = m.theme.statusOK.Render("Cloudflare proxied")
}
lines = append(lines, "", "Proxy: "+proxy+" "+m.theme.key.Render("Ctrl+P")+" toggle")
if m.err != nil {
lines = append(lines, "", m.theme.statusBad.Render("! "+m.err.Error()))
}
lines = append(lines, "", m.theme.mutedText.Render("Tab to move · Enter on Priority to review/apply · Esc to cancel"))
modal := m.theme.modal.Width(min(74, m.width-8)).Render(strings.Join(lines, "\n"))
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
}
func (m *Model) renderCertificateForm() string {
var title string
var labels []string
switch m.certificateAction {
case "issue":
title = "ISSUE WILDCARD CERTIFICATES"
labels = []string{"Zones (local IDs or unique names)", "Environment", "Contact email", "Nested labels", "Key algorithm"}
case "import":
title = "IMPORT CERTIFICATE METADATA"
labels = []string{"PEM file", "Display name", "Zone"}
case "export":
title = "EXPORT CURRENT PEM FILES"
labels = []string{"Destination"}
case "revoke":
title = "REVOKE CERTIFICATE — IRREVERSIBLE"
labels = []string{"Environment", "Exact lineage name", "Reason code"}
case "renew":
title = "RENEW DUE CERTIFICATES"
labels = []string{"Environment"}
}
lines := []string{m.theme.brand.Render(title), ""}
for i, input := range m.certificateInputs {
label := m.theme.mutedText.Render(labels[i])
if i == m.certificateFocus {
label = m.theme.panelTitle.Render(labels[i])
}
lines = append(lines, label, input.View(), "")
}
if m.certificateAction == "issue" {
if zone, ok := m.zoneByID(m.certificateIssueZoneID); ok {
lines = append(lines, m.theme.mutedText.Render("Selected zone: "+zone.Name+" · local ID "+zone.ID), "")
}
terms := m.theme.mutedText.Render("not accepted")
if m.certificateAcceptTerms {
terms = m.theme.statusOK.Render("accepted")
}
production := m.theme.mutedText.Render("not confirmed")
if m.certificateConfirmProduction {
production = m.theme.statusWarn.Render("confirmed")
}
lines = append(lines,
"CA terms: "+terms+" "+m.theme.key.Render("Ctrl+T")+" toggle",
"Production: "+production+" "+m.theme.key.Render("Ctrl+P")+" toggle", "")
}
if m.certificateAction == "renew" {
production := m.theme.mutedText.Render("not confirmed")
if m.certificateConfirmProduction {
production = m.theme.statusWarn.Render("confirmed")
}
lines = append(lines, "Production: "+production+" "+m.theme.key.Render("Ctrl+P")+" toggle", "")
}
if m.certificateAction == "revoke" {
lines = append(lines,
m.theme.mutedText.Render("Expected exact name: ")+m.theme.panelTitle.Render(m.certificateExpectedName),
m.theme.statusWarn.Render("The CA revocation cannot be undone. Confirm by typing the exact lineage name."), "")
}
if m.err != nil {
lines = append(lines, m.theme.statusBad.Render("! "+m.err.Error()), "")
}
lines = append(lines, m.theme.mutedText.Render("Tab to move · Enter on final field to run · Esc to cancel"))
modal := m.theme.modal.Width(min(76, m.width-8)).Render(strings.Join(lines, "\n"))
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
}
func (m *Model) renderDeleteConfirmation() string {
values := m.filteredRecords()
var detail string
if len(values) > 0 {
record := values[min(m.recordIndex, len(values)-1)]
detail = fmt.Sprintf("%s %s %s", record.Type, record.Name, record.Content)
}
return m.confirmation("DELETE DNS RECORD?", detail, "This change is sent immediately after a fresh remote read.")
}
func (m *Model) renderRecordConfirmation() string {
after := fmt.Sprintf("%s %s %s TTL=%d proxied=%t", m.recordDraft.Type, m.recordDraft.Name, displayRecordContent(m.recordDraft), m.recordDraft.TTL, m.recordDraft.Proxied)
detail := "Create\n " + after
if m.recordDraftEdit {
before := "current cached record"
for _, record := range m.records {
if record.ID == m.recordDraftID || record.ProviderID == m.recordDraftID {
before = fmt.Sprintf("%s %s %s TTL=%d proxied=%t", record.Type, record.Name, displayRecordContent(record), record.TTL, record.Proxied)
break
}
}
detail = "Before\n " + before + "\nAfter\n " + after
}
return m.confirmation("APPLY DNS CHANGE?", detail, "DomainOps will re-read the remote record and reject a concurrent change.")
}
func (m *Model) renderTLSConfirmation() string {
detail := fmt.Sprintf("Mode: %s → %s\nAlways HTTPS: %t → %t\nMinimum TLS: %s → %s\nTLS 1.3: %t → %t", m.tls.Mode, m.tlsDraft.Mode, m.tls.AlwaysUseHTTPS, m.tlsDraft.AlwaysUseHTTPS, m.tls.MinimumTLS, m.tlsDraft.MinimumTLS, m.tls.TLS13, m.tlsDraft.TLS13)
return m.confirmation("APPLY CLOUDFLARE TLS CHANGES?", detail, "A wrong origin mode can interrupt proxied traffic.")
}
func (m *Model) confirmation(title, detail, warning string) string {
body := m.theme.brand.Render(title) + "\n\n" + detail + "\n\n" + m.theme.statusWarn.Render(warning) + "\n\n" + m.theme.key.Render("y / Enter") + " apply " + m.theme.key.Render("n / Esc") + " cancel"
modal := m.theme.modal.Width(min(66, m.width-8)).Render(body)
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
}
func (m *Model) renderHelp() string {
lines := []string{
m.theme.brand.Render("KEYBOARD REFERENCE"), "",
m.theme.key.Render("1…7") + " Navigate sections", m.theme.key.Render("j / k") + " Move selection",
m.theme.key.Render("/") + " Filter current view", m.theme.key.Render("Ctrl+K") + " Command palette",
m.theme.key.Render("r") + " Synchronize", m.theme.key.Render("a") + " Add Cloudflare connection",
m.theme.key.Render("n / e / d") + " New, edit, delete DNS record", m.theme.key.Render("?") + " Close this help",
m.theme.key.Render("n / u / i / x / d") + " Issue, renew due, import, export, revoke certificate",
"", m.theme.mutedText.Render("All operations are keyboard-accessible and safe over SSH."),
}
if m.recoveryBlocked {
lines = append(lines, "", m.theme.key.Render("R")+" Retry blocked crash recovery")
}
modal := m.theme.modal.Width(min(72, m.width-8)).Render(strings.Join(lines, "\n"))
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
}
func (m *Model) renderPalette() string {
commands := paletteCommands()
lines := []string{m.theme.brand.Render("COMMAND PALETTE"), ""}
for i, command := range commands {
line := " " + command
if i == m.paletteIndex {
line = m.theme.selected.Width(48).Render("› " + command)
}
lines = append(lines, line)
}
lines = append(lines, "", m.theme.mutedText.Render("j/k select · Enter run · Esc close"))
modal := m.theme.modal.Width(min(58, m.width-8)).Render(strings.Join(lines, "\n"))
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
}
type cell struct {
value string
share int
}
func row(width int, cells []cell) string {
total := 0
for _, value := range cells {
total += value.share
}
if total == 0 {
return ""
}
available := max(1, width-len(cells)+1)
parts := make([]string, 0, len(cells))
used := 0
for i, value := range cells {
cellWidth := available * value.share / total
if i == len(cells)-1 {
cellWidth = available - used
}
used += cellWidth
text := truncate(stripLines(value.value), max(0, cellWidth-1))
parts = append(parts, text+strings.Repeat(" ", max(0, cellWidth-lipgloss.Width(text))))
}
return strings.Join(parts, " ")
}
func truncate(value string, width int) string {
if width <= 0 {
return ""
}
if lipgloss.Width(value) <= width {
return value
}
if width == 1 {
return "…"
}
runes := []rune(value)
for len(runes) > 0 && lipgloss.Width(string(runes))+1 > width {
runes = runes[:len(runes)-1]
}
return string(runes) + "…"
}
func stripLines(value string) string {
return strings.Join(strings.Fields(value), " ")
}
func intersperse(values []string, separator string) []string {
if len(values) <= 1 {
return values
}
result := make([]string, 0, len(values)*2-1)
for i, value := range values {
if i > 0 {
result = append(result, separator)
}
result = append(result, value)
}
return result
}
func severityRank(value domain.Severity) int {
switch value {
case domain.SeverityCritical:
return 3
case domain.SeverityWarning:
return 2
default:
return 1
}
}
+69
View File
@@ -0,0 +1,69 @@
package tui
import (
"image/color"
"charm.land/lipgloss/v2"
)
type theme struct {
bg color.Color
surface color.Color
surface2 color.Color
border color.Color
primary color.Color
secondary color.Color
text color.Color
muted color.Color
green color.Color
amber color.Color
red color.Color
app lipgloss.Style
header lipgloss.Style
brand lipgloss.Style
sidebar lipgloss.Style
nav lipgloss.Style
navActive lipgloss.Style
panel lipgloss.Style
panelTitle lipgloss.Style
mutedText lipgloss.Style
statusOK lipgloss.Style
statusWarn lipgloss.Style
statusBad lipgloss.Style
selected lipgloss.Style
modal lipgloss.Style
key lipgloss.Style
}
func newTheme() theme {
t := theme{
bg: lipgloss.Color("#0A0F1D"),
surface: lipgloss.Color("#11182A"),
surface2: lipgloss.Color("#172139"),
border: lipgloss.Color("#2A3858"),
primary: lipgloss.Color("#66E3D4"),
secondary: lipgloss.Color("#A78BFA"),
text: lipgloss.Color("#E8EEF8"),
muted: lipgloss.Color("#8190AA"),
green: lipgloss.Color("#6ED59A"),
amber: lipgloss.Color("#F3C969"),
red: lipgloss.Color("#FF7188"),
}
t.app = lipgloss.NewStyle().Background(t.bg).Foreground(t.text)
t.header = lipgloss.NewStyle().Background(t.surface).Foreground(t.text).Padding(0, 1)
t.brand = lipgloss.NewStyle().Foreground(t.primary).Bold(true)
t.sidebar = lipgloss.NewStyle().Background(t.surface).Foreground(t.muted).Padding(1, 1).BorderRight(true).BorderForeground(t.border)
t.nav = lipgloss.NewStyle().Foreground(t.muted).Padding(0, 1)
t.navActive = lipgloss.NewStyle().Background(t.surface2).Foreground(t.primary).Bold(true).Padding(0, 1)
t.panel = lipgloss.NewStyle().Background(t.surface).Foreground(t.text).Border(lipgloss.RoundedBorder()).BorderForeground(t.border).Padding(0, 1)
t.panelTitle = lipgloss.NewStyle().Foreground(t.primary).Bold(true)
t.mutedText = lipgloss.NewStyle().Foreground(t.muted)
t.statusOK = lipgloss.NewStyle().Foreground(t.green).Bold(true)
t.statusWarn = lipgloss.NewStyle().Foreground(t.amber).Bold(true)
t.statusBad = lipgloss.NewStyle().Foreground(t.red).Bold(true)
t.selected = lipgloss.NewStyle().Background(t.surface2).Foreground(t.text)
t.modal = lipgloss.NewStyle().Background(t.surface).Foreground(t.text).Border(lipgloss.DoubleBorder()).BorderForeground(t.secondary).Padding(1, 2)
t.key = lipgloss.NewStyle().Background(t.surface2).Foreground(t.primary).Padding(0, 1)
return t
}