Files
probo/pkg/cert/certificate_provisioner.go
Bryan Frimin eb11eb0970 Add ACME workers
Signed-off-by: Bryan Frimin <bryan@getprobo.com>
2025-10-09 15:03:34 +02:00

187 lines
5.0 KiB
Go

// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package cert
import (
"context"
"fmt"
"time"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/crypto/cipher"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
)
type (
CertificateProvisioner struct {
pg *pg.Client
acmeService *ACMEService
encryptionKey cipher.EncryptionKey
interval time.Duration
logger *log.Logger
}
)
func NewCertificateProvisioner(
pg *pg.Client,
acmeService *ACMEService,
encryptionKey cipher.EncryptionKey,
interval time.Duration,
logger *log.Logger,
) *CertificateProvisioner {
return &CertificateProvisioner{
pg: pg,
acmeService: acmeService,
encryptionKey: encryptionKey,
interval: interval,
logger: logger.Named("cert.provisioner"),
}
}
func (p *CertificateProvisioner) Run(ctx context.Context) error {
p.logger.InfoCtx(ctx, "certificate provisioner starting", log.Duration("interval", p.interval))
if err := p.checkPendingDomains(ctx); err != nil {
p.logger.ErrorCtx(ctx, "initial check failed", log.Error(err))
}
ticker := time.NewTicker(p.interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
p.logger.InfoCtx(ctx, "certificate provisioner shutting down")
return ctx.Err()
case <-ticker.C:
if err := p.checkPendingDomains(ctx); err != nil {
p.logger.ErrorCtx(ctx, "periodic check failed", log.Error(err))
}
}
}
}
func (p *CertificateProvisioner) checkPendingDomains(ctx context.Context) error {
return p.pg.WithConn(ctx, func(conn pg.Conn) error {
var domains coredata.CustomDomains
if err := domains.ListDomainsWithPendingHTTPChallenges(ctx, conn, coredata.NewNoScope()); err != nil {
return fmt.Errorf("cannot load domains with pending challenges: %w", err)
}
if len(domains) == 0 {
return nil
}
p.logger.InfoCtx(ctx, "found domains with pending challenges", log.Int("count", len(domains)))
for _, domain := range domains {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if err := p.completeDomainCertificate(ctx, conn, domain); err != nil {
p.logger.ErrorCtx(
ctx,
"cannot complete certificate for domain",
log.String("domain", domain.Domain),
log.Error(err),
)
}
}
return nil
})
}
func (p *CertificateProvisioner) completeDomainCertificate(
ctx context.Context,
conn pg.Conn,
domain *coredata.CustomDomain,
) error {
challenge := &HTTPChallenge{
Domain: domain.Domain,
Token: *domain.HTTPChallengeToken,
KeyAuth: *domain.HTTPChallengeKeyAuth,
URL: *domain.HTTPChallengeURL,
OrderURL: *domain.HTTPOrderURL,
}
cert, err := p.acmeService.CompleteHTTPChallenge(ctx, challenge)
if err != nil {
p.logger.WarnCtx(
ctx,
"cannot complete HTTP challenge",
log.String("domain", domain.Domain),
log.Error(err),
)
return nil
}
p.logger.InfoCtx(
ctx,
"certificate obtained successfully",
log.String("domain", domain.Domain),
log.Time("expires_at", cert.ExpiresAt),
)
scope := coredata.NewScope(domain.OrganizationID.TenantID())
fullDomain := &coredata.CustomDomain{}
if err := fullDomain.LoadByID(ctx, conn, scope, p.encryptionKey, domain.ID); err != nil {
return fmt.Errorf("cannot load domain: %w", err)
}
fullDomain.SSLCertificatePEM = cert.CertPEM
fullDomain.SSLPrivateKeyPEM = cert.KeyPEM
chainStr := string(cert.ChainPEM)
fullDomain.SSLCertificateChain = &chainStr
fullDomain.SSLExpiresAt = &cert.ExpiresAt
status := coredata.CustomDomainSSLStatusActive
fullDomain.SSLStatus = &status
fullDomain.HTTPChallengeToken = nil
fullDomain.HTTPChallengeKeyAuth = nil
fullDomain.HTTPChallengeURL = nil
fullDomain.HTTPOrderURL = nil
if err := fullDomain.Update(ctx, conn, scope, p.encryptionKey); err != nil {
return fmt.Errorf("cannot update domain: %w", err)
}
cache := &coredata.CachedCertificate{
Domain: fullDomain.Domain,
CertificatePEM: string(cert.CertPEM),
PrivateKeyPEM: string(cert.KeyPEM),
CertificateChain: &chainStr,
ExpiresAt: cert.ExpiresAt,
CachedAt: time.Now(),
CustomDomainID: fullDomain.ID,
}
if err := cache.Upsert(ctx, conn); err != nil {
p.logger.ErrorCtx(
ctx,
"cannot update certificate cache",
log.String("domain", fullDomain.Domain),
log.Error(err),
)
}
return nil
}