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

+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)
}