Newer
Older
EnvoyControlPlane / internal / pkg / cert / persist.go
package cert

import (
	"context"
	"envoy-control-plane/internal/pkg/cert/api"
	"envoy-control-plane/internal/pkg/storage"
	"errors"
	"fmt"
)

// SaveCertificateData persists the certificate data needed for renewal to the database.
// It uses the underlying CertStorer dependency.
func SaveCertificateData(ctx context.Context, store *storage.Storage, cert *api.Certificate, email string, issuertype string, secretname string) error {
	if store == nil {
		return errors.New("certificate store dependency is nil, cannot save data")
	}

	certStorage := &storage.CertStorage{
		Domain:     cert.Domain,
		Email:      email, // Store email with the cert
		CertPEM:    cert.CertPEM,
		KeyPEM:     cert.KeyPEM,
		AccountKey: cert.AccountKey,
		AccountURL: cert.AccountURL,
		IssuerType: issuertype,
		SecretName: secretname,
	}

	if err := store.SaveCertificate(ctx, certStorage); err != nil {
		return fmt.Errorf("failed to save certificate data for %s: %w", cert.Domain, err)
	}
	return nil
}

// LoadCertificateData retrieves the certificate data needed for renewal from the database.
// It uses the underlying CertStorer dependency.
func LoadCertificateData(ctx context.Context, store *storage.Storage, domain string) (*api.Certificate, string, string, error) {
	if store == nil {
		return nil, "", "", errors.New("certificate store dependency is nil, cannot load data")
	}

	certStorage, err := store.LoadCertificate(ctx, domain)
	if err != nil {
		return nil, "", "", fmt.Errorf("failed to load certificate data for %s: %w", domain, err)
	}
	if certStorage == nil {
		return nil, "", "", fmt.Errorf("no certificate data found for domain %s", domain)
	}

	cert := &api.Certificate{
		Domain:     certStorage.Domain,
		CertPEM:    certStorage.CertPEM,
		KeyPEM:     certStorage.KeyPEM,
		AccountKey: certStorage.AccountKey,
		AccountURL: certStorage.AccountURL,
	}

	return cert, certStorage.Email, certStorage.IssuerType, nil
}