init
This commit is contained in:
76 files changed
+22739
No files matched your search
@@ -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 = ¤t
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 ""
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 = ©
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -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
Reference in new issue
Block a user