init
This commit is contained in:
76 files changed
+22739
No files matched your search
@@ -0,0 +1,412 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/MeghdadFadaee/domainops/internal/domain"
|
||||
"github.com/MeghdadFadaee/domainops/internal/store"
|
||||
)
|
||||
|
||||
func (r *Repository) SaveACMEAccount(ctx context.Context, value domain.ACMEAccount) error {
|
||||
return saveACMEAccount(ctx, r.db, value)
|
||||
}
|
||||
|
||||
func saveACMEAccount(ctx context.Context, executor sqlExecutor, value domain.ACMEAccount) error {
|
||||
_, err := executor.ExecContext(ctx, `INSERT INTO acme_accounts (
|
||||
id, environment, directory_url, email, registration, secret_ref, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(environment) DO UPDATE SET id=excluded.id,
|
||||
directory_url=excluded.directory_url, email=excluded.email,
|
||||
registration=excluded.registration, secret_ref=excluded.secret_ref,
|
||||
created_at=excluded.created_at`, value.ID, value.Environment,
|
||||
value.DirectoryURL, value.Email, value.Registration, value.SecretRef,
|
||||
encodeTime(value.CreatedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save ACME account: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func insertACMEAccount(ctx context.Context, executor sqlExecutor, value domain.ACMEAccount) error {
|
||||
result, err := executor.ExecContext(ctx, `INSERT INTO acme_accounts (
|
||||
id, environment, directory_url, email, registration, secret_ref, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(environment) DO NOTHING`, value.ID, value.Environment,
|
||||
value.DirectoryURL, value.Email, value.Registration, value.SecretRef,
|
||||
encodeTime(value.CreatedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: insert ACME account: %w", err)
|
||||
}
|
||||
inserted, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: inspect ACME account insert: %w", err)
|
||||
}
|
||||
if inserted != 1 {
|
||||
return fmt.Errorf("sqlite: %w: %s", store.ErrACMEAccountConflict, value.Environment)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CommitACMEAccount installs account metadata and closes its secret intent in
|
||||
// one FULL-synchronous SQLite transaction.
|
||||
func (r *Repository) CommitACMEAccount(ctx context.Context, value domain.ACMEAccount) error {
|
||||
if value.ID == "" || value.Environment == "" || value.SecretRef == "" {
|
||||
return fmt.Errorf("sqlite: invalid ACME account commit")
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: begin ACME account commit: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if err := insertACMEAccount(ctx, tx, value); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM acme_account_commit_journal WHERE account_id = ?", value.ID); err != nil {
|
||||
return fmt.Errorf("sqlite: complete ACME account commit intent: %w", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("sqlite: commit ACME account: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveACMEAccountCommitIntent(ctx context.Context, intent domain.ACMEAccountCommitIntent) error {
|
||||
if intent.AccountID == "" || intent.SecretRef == "" || intent.CreatedAt.IsZero() {
|
||||
return fmt.Errorf("sqlite: invalid ACME account commit intent")
|
||||
}
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO acme_account_commit_journal (account_id, secret_ref, created_at)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(account_id) DO UPDATE SET secret_ref=excluded.secret_ref, created_at=excluded.created_at`,
|
||||
intent.AccountID, intent.SecretRef, encodeTime(intent.CreatedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save ACME account commit intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListACMEAccountCommitIntents(ctx context.Context) ([]domain.ACMEAccountCommitIntent, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `SELECT account_id, secret_ref, created_at
|
||||
FROM acme_account_commit_journal ORDER BY created_at, account_id`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list ACME account commit intents: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var intents []domain.ACMEAccountCommitIntent
|
||||
for rows.Next() {
|
||||
var intent domain.ACMEAccountCommitIntent
|
||||
var created string
|
||||
if err := rows.Scan(&intent.AccountID, &intent.SecretRef, &created); err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan ACME account commit intent: %w", err)
|
||||
}
|
||||
intent.CreatedAt, err = decodeTime(created)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: decode ACME account commit intent: %w", err)
|
||||
}
|
||||
intents = append(intents, intent)
|
||||
}
|
||||
return intents, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteACMEAccountCommitIntent(ctx context.Context, accountID string) error {
|
||||
if _, err := r.db.ExecContext(ctx, "DELETE FROM acme_account_commit_journal WHERE account_id = ?", accountID); err != nil {
|
||||
return fmt.Errorf("sqlite: delete ACME account commit intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) GetACMEAccountByEnvironment(ctx context.Context, environment string) (domain.ACMEAccount, error) {
|
||||
var value domain.ACMEAccount
|
||||
var created string
|
||||
err := r.db.QueryRowContext(ctx, `SELECT id, environment, directory_url, email,
|
||||
registration, secret_ref, created_at FROM acme_accounts WHERE environment = ?`, environment).
|
||||
Scan(&value.ID, &value.Environment, &value.DirectoryURL, &value.Email,
|
||||
&value.Registration, &value.SecretRef, &created)
|
||||
if err != nil {
|
||||
return value, fmt.Errorf("sqlite: get ACME account: %w", err)
|
||||
}
|
||||
if value.CreatedAt, err = decodeTime(created); err != nil {
|
||||
return value, fmt.Errorf("sqlite: decode ACME account: %w", err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveCertificateLineage(ctx context.Context, value domain.CertificateLineage) error {
|
||||
return saveCertificateLineage(ctx, r.db, value)
|
||||
}
|
||||
|
||||
type sqlExecutor interface {
|
||||
ExecContext(context.Context, string, ...any) (sql.Result, error)
|
||||
}
|
||||
|
||||
func saveCertificateLineage(ctx context.Context, executor sqlExecutor, value domain.CertificateLineage) error {
|
||||
identifiers, err := encodeJSON(value.Identifiers)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: encode lineage identifiers: %w", err)
|
||||
}
|
||||
_, err = executor.ExecContext(ctx, `INSERT INTO certificate_lineages (
|
||||
id, name, zone_id, source, identifiers_json, key_algorithm, profile,
|
||||
acme_account_id, current_version_id, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET name=excluded.name, zone_id=excluded.zone_id,
|
||||
source=excluded.source, identifiers_json=excluded.identifiers_json,
|
||||
key_algorithm=excluded.key_algorithm, profile=excluded.profile,
|
||||
acme_account_id=excluded.acme_account_id,
|
||||
current_version_id=excluded.current_version_id, created_at=excluded.created_at,
|
||||
updated_at=excluded.updated_at`, value.ID, value.Name, value.ZoneID,
|
||||
string(value.Source), identifiers, string(value.KeyAlgorithm), value.Profile,
|
||||
value.ACMEAccountID, value.CurrentVersionID, encodeTime(value.CreatedAt),
|
||||
encodeTime(value.UpdatedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save certificate lineage: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const lineageColumns = `id, name, zone_id, source, identifiers_json, key_algorithm,
|
||||
profile, acme_account_id, current_version_id, created_at, updated_at`
|
||||
|
||||
func scanLineage(scanner interface{ Scan(...any) error }) (domain.CertificateLineage, error) {
|
||||
var value domain.CertificateLineage
|
||||
var source, identifiers, algorithm, created, updated string
|
||||
if err := scanner.Scan(&value.ID, &value.Name, &value.ZoneID, &source,
|
||||
&identifiers, &algorithm, &value.Profile, &value.ACMEAccountID,
|
||||
&value.CurrentVersionID, &created, &updated); err != nil {
|
||||
return value, err
|
||||
}
|
||||
value.Source = domain.CertificateSource(source)
|
||||
value.KeyAlgorithm = domain.KeyAlgorithm(algorithm)
|
||||
if err := decodeJSON(identifiers, &value.Identifiers); err != nil {
|
||||
return value, err
|
||||
}
|
||||
var err error
|
||||
if value.CreatedAt, err = decodeTime(created); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.UpdatedAt, err = decodeTime(updated); err != nil {
|
||||
return value, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListCertificateLineages(ctx context.Context) ([]domain.CertificateLineage, error) {
|
||||
rows, err := r.db.QueryContext(ctx, "SELECT "+lineageColumns+" FROM certificate_lineages ORDER BY name COLLATE NOCASE, id")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list certificate lineages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.CertificateLineage, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanLineage(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan certificate lineage: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) GetCertificateLineage(ctx context.Context, id string) (domain.CertificateLineage, error) {
|
||||
value, err := scanLineage(r.db.QueryRowContext(ctx, "SELECT "+lineageColumns+" FROM certificate_lineages WHERE id = ?", id))
|
||||
if err != nil {
|
||||
return value, fmt.Errorf("sqlite: get certificate lineage: %w", err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveCertificateVersion(ctx context.Context, value domain.CertificateVersion) error {
|
||||
return saveCertificateVersion(ctx, r.db, value)
|
||||
}
|
||||
|
||||
func (r *Repository) SaveCertificateCommitIntent(ctx context.Context, value domain.CertificateCommitIntent) error {
|
||||
if value.VersionID == "" || value.LineageID == "" || value.ArtifactPath == "" {
|
||||
return fmt.Errorf("sqlite: invalid certificate commit intent")
|
||||
}
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO certificate_commit_journal (
|
||||
version_id, lineage_id, secret_ref, artifact_path, created_at
|
||||
) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(version_id) DO UPDATE SET lineage_id=excluded.lineage_id,
|
||||
secret_ref=excluded.secret_ref, artifact_path=excluded.artifact_path,
|
||||
created_at=excluded.created_at`, value.VersionID, value.LineageID,
|
||||
value.SecretRef, value.ArtifactPath, encodeTime(value.CreatedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save certificate commit intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListCertificateCommitIntents(ctx context.Context) ([]domain.CertificateCommitIntent, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `SELECT version_id, lineage_id, secret_ref,
|
||||
artifact_path, created_at FROM certificate_commit_journal ORDER BY created_at, version_id`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list certificate commit intents: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var values []domain.CertificateCommitIntent
|
||||
for rows.Next() {
|
||||
var value domain.CertificateCommitIntent
|
||||
var created string
|
||||
if err := rows.Scan(&value.VersionID, &value.LineageID, &value.SecretRef, &value.ArtifactPath, &created); err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan certificate commit intent: %w", err)
|
||||
}
|
||||
value.CreatedAt, err = decodeTime(created)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: decode certificate commit intent: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteCertificateCommitIntent(ctx context.Context, versionID string) error {
|
||||
if _, err := r.db.ExecContext(ctx, "DELETE FROM certificate_commit_journal WHERE version_id = ?", versionID); err != nil {
|
||||
return fmt.Errorf("sqlite: delete certificate commit intent: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveCertificateVersion(ctx context.Context, executor sqlExecutor, value domain.CertificateVersion) error {
|
||||
identifiers, err := encodeJSON(value.Identifiers)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: encode certificate identifiers: %w", err)
|
||||
}
|
||||
_, err = executor.ExecContext(ctx, `INSERT INTO certificate_versions (
|
||||
id, lineage_id, serial_number, fingerprint_sha256, issuer, identifiers_json,
|
||||
not_before, not_after, certificate_path, chain_path, private_key_ref,
|
||||
renewal_window_start, renewal_window_end, revocation_pending_at, revoked_at,
|
||||
revocation_reason, exported_at, export_path, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET lineage_id=excluded.lineage_id,
|
||||
serial_number=excluded.serial_number, fingerprint_sha256=excluded.fingerprint_sha256,
|
||||
issuer=excluded.issuer, identifiers_json=excluded.identifiers_json,
|
||||
not_before=excluded.not_before, not_after=excluded.not_after,
|
||||
certificate_path=excluded.certificate_path, chain_path=excluded.chain_path,
|
||||
private_key_ref=excluded.private_key_ref,
|
||||
renewal_window_start=excluded.renewal_window_start,
|
||||
renewal_window_end=excluded.renewal_window_end,
|
||||
revocation_pending_at=excluded.revocation_pending_at, revoked_at=excluded.revoked_at,
|
||||
revocation_reason=excluded.revocation_reason, exported_at=excluded.exported_at,
|
||||
export_path=excluded.export_path, created_at=excluded.created_at`,
|
||||
value.ID, value.LineageID, value.SerialNumber, value.FingerprintSHA256,
|
||||
value.Issuer, identifiers, encodeTime(value.NotBefore), encodeTime(value.NotAfter),
|
||||
value.CertificatePath, value.ChainPath, value.PrivateKeyRef,
|
||||
encodeOptionalTime(value.RenewalWindowStart), encodeOptionalTime(value.RenewalWindowEnd),
|
||||
encodeOptionalTime(value.RevocationPendingAt), encodeOptionalTime(value.RevokedAt), optionalUint(value.RevocationReason),
|
||||
encodeOptionalTime(value.ExportedAt), value.ExportPath, encodeTime(value.CreatedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save certificate version: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CommitCertificateVersion installs a version row and advances its lineage in
|
||||
// one SQLite transaction. Filesystem activation happens only after this method
|
||||
// succeeds, so `current` can never point at an untracked version.
|
||||
func (r *Repository) CommitCertificateVersion(ctx context.Context, lineage domain.CertificateLineage, version domain.CertificateVersion) error {
|
||||
if lineage.ID == "" || version.ID == "" || version.LineageID != lineage.ID || lineage.CurrentVersionID != version.ID {
|
||||
return fmt.Errorf("sqlite: invalid certificate lineage/version commit")
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: begin certificate commit: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
activeVersionID := lineage.CurrentVersionID
|
||||
lineage.CurrentVersionID = ""
|
||||
if err := saveCertificateLineage(ctx, tx, lineage); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := saveCertificateVersion(ctx, tx, version); err != nil {
|
||||
return err
|
||||
}
|
||||
lineage.CurrentVersionID = activeVersionID
|
||||
if err := saveCertificateLineage(ctx, tx, lineage); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM certificate_commit_journal WHERE version_id = ?", version.ID); err != nil {
|
||||
return fmt.Errorf("sqlite: complete certificate commit intent: %w", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("sqlite: commit certificate version: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const versionColumns = `id, lineage_id, serial_number, fingerprint_sha256, issuer,
|
||||
identifiers_json, not_before, not_after, certificate_path, chain_path,
|
||||
private_key_ref, renewal_window_start, renewal_window_end, revocation_pending_at,
|
||||
revoked_at, revocation_reason, exported_at,
|
||||
export_path, created_at`
|
||||
|
||||
func scanVersion(scanner interface{ Scan(...any) error }) (domain.CertificateVersion, error) {
|
||||
var value domain.CertificateVersion
|
||||
var identifiers, notBefore, notAfter, created string
|
||||
var renewalStart, renewalEnd, revocationPending, revoked, exported sql.NullString
|
||||
var revocationReason sql.NullInt64
|
||||
if err := scanner.Scan(&value.ID, &value.LineageID, &value.SerialNumber,
|
||||
&value.FingerprintSHA256, &value.Issuer, &identifiers, ¬Before, ¬After,
|
||||
&value.CertificatePath, &value.ChainPath, &value.PrivateKeyRef, &renewalStart,
|
||||
&renewalEnd, &revocationPending, &revoked, &revocationReason, &exported, &value.ExportPath, &created); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if err := decodeJSON(identifiers, &value.Identifiers); err != nil {
|
||||
return value, err
|
||||
}
|
||||
var err error
|
||||
if value.NotBefore, err = decodeTime(notBefore); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.NotAfter, err = decodeTime(notAfter); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.CreatedAt, err = decodeTime(created); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.RenewalWindowStart, err = decodeOptionalTime(renewalStart); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.RenewalWindowEnd, err = decodeOptionalTime(renewalEnd); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.RevocationPendingAt, err = decodeOptionalTime(revocationPending); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.RevokedAt, err = decodeOptionalTime(revoked); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if revocationReason.Valid {
|
||||
reason := uint(revocationReason.Int64)
|
||||
value.RevocationReason = &reason
|
||||
}
|
||||
if value.ExportedAt, err = decodeOptionalTime(exported); err != nil {
|
||||
return value, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func optionalUint(value *uint) any {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
return int64(*value)
|
||||
}
|
||||
|
||||
func (r *Repository) ListCertificateVersions(ctx context.Context, lineageID string) ([]domain.CertificateVersion, error) {
|
||||
rows, err := r.db.QueryContext(ctx, "SELECT "+versionColumns+` FROM certificate_versions
|
||||
WHERE lineage_id = ? ORDER BY created_at DESC, id`, lineageID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list certificate versions: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.CertificateVersion, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanVersion(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan certificate version: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func encodeTime(t time.Time) string {
|
||||
return t.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
func encodeOptionalTime(t *time.Time) any {
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
return encodeTime(*t)
|
||||
}
|
||||
|
||||
func decodeTime(raw string) (time.Time, error) {
|
||||
t, err := time.Parse(time.RFC3339Nano, raw)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("decode time %q: %w", raw, err)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func decodeOptionalTime(raw sql.NullString) (*time.Time, error) {
|
||||
if !raw.Valid {
|
||||
return nil, nil
|
||||
}
|
||||
t, err := decodeTime(raw.String)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func encodeJSON(value any) (string, error) {
|
||||
b, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
func decodeJSON(raw string, target any) error {
|
||||
if raw == "" {
|
||||
raw = "null"
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), target); err != nil {
|
||||
return fmt.Errorf("decode JSON: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func rawOrNil(raw []byte) any {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func copyRaw(raw []byte) []byte {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
return append([]byte(nil), raw...)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/MeghdadFadaee/domainops/internal/domain"
|
||||
)
|
||||
|
||||
type sqlExecer interface {
|
||||
ExecContext(context.Context, string, ...any) (sql.Result, error)
|
||||
}
|
||||
|
||||
func saveDNSRecord(ctx context.Context, exec sqlExecer, value domain.DNSRecord) error {
|
||||
tags, err := encodeJSON(value.Tags)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode tags: %w", err)
|
||||
}
|
||||
var priority any
|
||||
if value.Priority != nil {
|
||||
priority = int64(*value.Priority)
|
||||
}
|
||||
_, err = exec.ExecContext(ctx, `INSERT INTO dns_records (
|
||||
id, provider_id, zone_id, type, name, unicode_name, content, priority,
|
||||
ttl, proxied, proxiable, comment, tags_json, managed, data_json, raw_json,
|
||||
modified_at, last_synced_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET provider_id=excluded.provider_id,
|
||||
zone_id=excluded.zone_id, type=excluded.type, name=excluded.name,
|
||||
unicode_name=excluded.unicode_name, content=excluded.content,
|
||||
priority=excluded.priority, ttl=excluded.ttl, proxied=excluded.proxied,
|
||||
proxiable=excluded.proxiable, comment=excluded.comment, tags_json=excluded.tags_json,
|
||||
managed=excluded.managed, data_json=excluded.data_json, raw_json=excluded.raw_json,
|
||||
modified_at=excluded.modified_at, last_synced_at=excluded.last_synced_at`,
|
||||
value.ID, value.ProviderID, value.ZoneID, string(value.Type), value.Name,
|
||||
value.UnicodeName, value.Content, priority, value.TTL, value.Proxied,
|
||||
value.Proxiable, value.Comment, tags, value.Managed, rawOrNil(value.Data),
|
||||
rawOrNil(value.Raw), encodeOptionalTime(value.ModifiedAt), encodeOptionalTime(value.LastSyncedAt))
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) ReplaceDNSRecords(ctx context.Context, zoneID string, values []domain.DNSRecord, syncedAt time.Time) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: begin DNS replacement: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM dns_records WHERE zone_id = ?", zoneID); err != nil {
|
||||
return fmt.Errorf("sqlite: clear DNS records: %w", err)
|
||||
}
|
||||
for _, value := range values {
|
||||
if value.ZoneID != zoneID {
|
||||
return fmt.Errorf("sqlite: DNS record %s belongs to zone %s, expected %s", value.ID, value.ZoneID, zoneID)
|
||||
}
|
||||
value.LastSyncedAt = &syncedAt
|
||||
if err := saveDNSRecord(ctx, tx, value); err != nil {
|
||||
return fmt.Errorf("sqlite: replace DNS record %s: %w", value.ID, err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO zone_dns_sync(zone_id, synced_at) VALUES (?, ?)
|
||||
ON CONFLICT(zone_id) DO UPDATE SET synced_at=excluded.synced_at`, zoneID, encodeTime(syncedAt)); err != nil {
|
||||
return fmt.Errorf("sqlite: save DNS sync time: %w", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("sqlite: commit DNS replacement: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const dnsColumns = `id, provider_id, zone_id, type, name, unicode_name, content,
|
||||
priority, ttl, proxied, proxiable, comment, tags_json, managed, data_json,
|
||||
raw_json, modified_at, last_synced_at`
|
||||
|
||||
func scanDNSRecord(scanner interface{ Scan(...any) error }) (domain.DNSRecord, error) {
|
||||
var value domain.DNSRecord
|
||||
var recordType, tags string
|
||||
var priority sql.NullInt64
|
||||
var data, raw []byte
|
||||
var modified, synced sql.NullString
|
||||
if err := scanner.Scan(&value.ID, &value.ProviderID, &value.ZoneID, &recordType,
|
||||
&value.Name, &value.UnicodeName, &value.Content, &priority, &value.TTL,
|
||||
&value.Proxied, &value.Proxiable, &value.Comment, &tags, &value.Managed,
|
||||
&data, &raw, &modified, &synced); err != nil {
|
||||
return value, err
|
||||
}
|
||||
value.Type = domain.RecordType(recordType)
|
||||
if priority.Valid {
|
||||
if priority.Int64 < 0 || priority.Int64 > math.MaxUint16 {
|
||||
return value, fmt.Errorf("invalid DNS priority %d", priority.Int64)
|
||||
}
|
||||
converted := uint16(priority.Int64)
|
||||
value.Priority = &converted
|
||||
}
|
||||
if err := decodeJSON(tags, &value.Tags); err != nil {
|
||||
return value, err
|
||||
}
|
||||
value.Data = copyRaw(data)
|
||||
value.Raw = copyRaw(raw)
|
||||
var err error
|
||||
if value.ModifiedAt, err = decodeOptionalTime(modified); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.LastSyncedAt, err = decodeOptionalTime(synced); err != nil {
|
||||
return value, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListDNSRecords(ctx context.Context, zoneID string) ([]domain.DNSRecord, error) {
|
||||
rows, err := r.db.QueryContext(ctx, "SELECT "+dnsColumns+` FROM dns_records
|
||||
WHERE zone_id = ? ORDER BY name COLLATE NOCASE, type, id`, zoneID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list DNS records: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.DNSRecord, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanDNSRecord(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan DNS record: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) SaveDNSRecord(ctx context.Context, value domain.DNSRecord) error {
|
||||
if err := saveDNSRecord(ctx, r.db, value); err != nil {
|
||||
return fmt.Errorf("sqlite: save DNS record: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteDNSRecord(ctx context.Context, id string) error {
|
||||
if _, err := r.db.ExecContext(ctx, "DELETE FROM dns_records WHERE id = ?", id); err != nil {
|
||||
return fmt.Errorf("sqlite: delete DNS record: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveTLSSettings(ctx context.Context, value domain.EdgeTLSSettings) error {
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO tls_settings (
|
||||
zone_id, mode, always_use_https, minimum_tls, tls_1_3, has_proxied_dns, last_synced_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(zone_id) DO UPDATE SET mode=excluded.mode,
|
||||
always_use_https=excluded.always_use_https, minimum_tls=excluded.minimum_tls,
|
||||
tls_1_3=excluded.tls_1_3, has_proxied_dns=excluded.has_proxied_dns,
|
||||
last_synced_at=excluded.last_synced_at`, value.ZoneID, value.Mode,
|
||||
value.AlwaysUseHTTPS, value.MinimumTLS, value.TLS13, value.HasProxiedDNS,
|
||||
encodeOptionalTime(value.LastSyncedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save TLS settings: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) GetTLSSettings(ctx context.Context, zoneID string) (domain.EdgeTLSSettings, error) {
|
||||
var value domain.EdgeTLSSettings
|
||||
var synced sql.NullString
|
||||
err := r.db.QueryRowContext(ctx, `SELECT zone_id, mode, always_use_https, minimum_tls,
|
||||
tls_1_3, has_proxied_dns, last_synced_at FROM tls_settings WHERE zone_id = ?`, zoneID).
|
||||
Scan(&value.ZoneID, &value.Mode, &value.AlwaysUseHTTPS, &value.MinimumTLS,
|
||||
&value.TLS13, &value.HasProxiedDNS, &synced)
|
||||
if err != nil {
|
||||
return value, fmt.Errorf("sqlite: get TLS settings: %w", err)
|
||||
}
|
||||
if value.LastSyncedAt, err = decodeOptionalTime(synced); err != nil {
|
||||
return value, fmt.Errorf("sqlite: decode TLS settings: %w", err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/MeghdadFadaee/domainops/internal/domain"
|
||||
)
|
||||
|
||||
func (r *Repository) SaveCredential(ctx context.Context, value domain.Credential) error {
|
||||
capabilities, err := encodeJSON(value.Capabilities)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: encode credential capabilities: %w", err)
|
||||
}
|
||||
_, err = r.db.ExecContext(ctx, `INSERT INTO credentials (
|
||||
id, provider, label, kind, account_hint, secret_ref, status, capabilities_json,
|
||||
created_at, last_verified_at, last_error
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
provider=excluded.provider, label=excluded.label, kind=excluded.kind,
|
||||
account_hint=excluded.account_hint, secret_ref=excluded.secret_ref,
|
||||
status=excluded.status, capabilities_json=excluded.capabilities_json,
|
||||
created_at=excluded.created_at, last_verified_at=excluded.last_verified_at,
|
||||
last_error=excluded.last_error`,
|
||||
value.ID, value.Provider, value.Label, string(value.Kind), value.AccountHint,
|
||||
value.SecretRef, string(value.Status), capabilities, encodeTime(value.CreatedAt),
|
||||
encodeOptionalTime(value.LastVerifiedAt), value.LastError)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save credential: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanCredential(scanner interface{ Scan(...any) error }) (domain.Credential, error) {
|
||||
var value domain.Credential
|
||||
var kind, status, capabilities, created string
|
||||
var verified sql.NullString
|
||||
if err := scanner.Scan(&value.ID, &value.Provider, &value.Label, &kind, &value.AccountHint,
|
||||
&value.SecretRef, &status, &capabilities, &created, &verified, &value.LastError); err != nil {
|
||||
return value, err
|
||||
}
|
||||
value.Kind = domain.CredentialKind(kind)
|
||||
value.Status = domain.CredentialStatus(status)
|
||||
if err := decodeJSON(capabilities, &value.Capabilities); err != nil {
|
||||
return value, err
|
||||
}
|
||||
var err error
|
||||
if value.CreatedAt, err = decodeTime(created); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.LastVerifiedAt, err = decodeOptionalTime(verified); err != nil {
|
||||
return value, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
const credentialColumns = `id, provider, label, kind, account_hint, secret_ref, status,
|
||||
capabilities_json, created_at, last_verified_at, last_error`
|
||||
|
||||
func (r *Repository) ListCredentials(ctx context.Context) ([]domain.Credential, error) {
|
||||
rows, err := r.db.QueryContext(ctx, "SELECT "+credentialColumns+" FROM credentials ORDER BY label COLLATE NOCASE, id")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list credentials: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.Credential, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanCredential(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan credential: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) GetCredential(ctx context.Context, id string) (domain.Credential, error) {
|
||||
value, err := scanCredential(r.db.QueryRowContext(ctx, "SELECT "+credentialColumns+" FROM credentials WHERE id = ?", id))
|
||||
if err != nil {
|
||||
return value, fmt.Errorf("sqlite: get credential: %w", err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteCredential(ctx context.Context, id string) error {
|
||||
if _, err := r.db.ExecContext(ctx, "DELETE FROM credentials WHERE id = ?", id); err != nil {
|
||||
return fmt.Errorf("sqlite: delete credential: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveCredentialZoneCapability(ctx context.Context, credentialID, zoneID, capability string, observedAt time.Time) error {
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO credential_zone_capabilities (
|
||||
credential_id, zone_id, capability, observed_at
|
||||
) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(credential_id, zone_id, capability) DO UPDATE SET observed_at=excluded.observed_at`,
|
||||
credentialID, zoneID, capability, encodeTime(observedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save credential zone capability: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) HasCredentialZoneCapability(ctx context.Context, credentialID, zoneID, capability string) (bool, error) {
|
||||
var exists bool
|
||||
err := r.db.QueryRowContext(ctx, `SELECT EXISTS (
|
||||
SELECT 1 FROM credential_zone_capabilities
|
||||
WHERE credential_id = ? AND zone_id = ? AND capability = ?
|
||||
)`, credentialID, zoneID, capability).Scan(&exists)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("sqlite: get credential zone capability: %w", err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (r *Repository) GetCredentialZoneCapability(ctx context.Context, credentialID, zoneID, capability string) (time.Time, bool, error) {
|
||||
var observedRaw string
|
||||
err := r.db.QueryRowContext(ctx, `SELECT observed_at FROM credential_zone_capabilities
|
||||
WHERE credential_id = ? AND zone_id = ? AND capability = ?`, credentialID, zoneID, capability).Scan(&observedRaw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return time.Time{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return time.Time{}, false, fmt.Errorf("sqlite: get credential zone capability observation: %w", err)
|
||||
}
|
||||
observedAt, err := decodeTime(observedRaw)
|
||||
if err != nil {
|
||||
return time.Time{}, false, fmt.Errorf("sqlite: decode credential zone capability observation: %w", err)
|
||||
}
|
||||
return observedAt, true, nil
|
||||
}
|
||||
|
||||
// InvalidateCredentialZoneCapability atomically removes exact per-zone
|
||||
// authority and detaches the credential if it currently owns that route. The
|
||||
// transaction prevents a crash between those two fail-closed state changes.
|
||||
func (r *Repository) InvalidateCredentialZoneCapability(ctx context.Context, credentialID, zoneID, capability string) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: begin credential zone capability invalidation: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM credential_zone_capabilities
|
||||
WHERE credential_id = ? AND zone_id = ? AND capability = ?`, credentialID, zoneID, capability); err != nil {
|
||||
return fmt.Errorf("sqlite: delete credential zone capability: %w", err)
|
||||
}
|
||||
if capability == "dns:read" {
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE zones SET preferred_credential_id = ''
|
||||
WHERE id = ? AND preferred_credential_id = ?`, zoneID, credentialID); err != nil {
|
||||
return fmt.Errorf("sqlite: detach invalid zone credential: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("sqlite: commit credential zone capability invalidation: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveAccounts(ctx context.Context, accounts []domain.RemoteAccount, links []domain.AccountCredential) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: begin account save: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for _, value := range accounts {
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO accounts (
|
||||
id, provider, provider_id, name, created_at, last_synced_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET provider=excluded.provider,
|
||||
provider_id=excluded.provider_id, name=excluded.name,
|
||||
created_at=excluded.created_at, last_synced_at=excluded.last_synced_at`,
|
||||
value.ID, value.Provider, value.ProviderID, value.Name, encodeTime(value.CreatedAt),
|
||||
encodeOptionalTime(value.LastSyncedAt)); err != nil {
|
||||
return fmt.Errorf("sqlite: save account %s: %w", value.ID, err)
|
||||
}
|
||||
}
|
||||
for _, value := range links {
|
||||
if value.Preferred {
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE account_credentials SET preferred = 0 WHERE account_id = ?", value.AccountID); err != nil {
|
||||
return fmt.Errorf("sqlite: reset preferred account credential: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO account_credentials(account_id, credential_id, preferred)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(account_id, credential_id) DO UPDATE SET preferred =
|
||||
CASE WHEN excluded.preferred = 1 THEN 1 ELSE account_credentials.preferred END`,
|
||||
value.AccountID, value.CredentialID, value.Preferred); err != nil {
|
||||
return fmt.Errorf("sqlite: save account credential: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("sqlite: commit account save: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanAccount(scanner interface{ Scan(...any) error }) (domain.RemoteAccount, error) {
|
||||
var value domain.RemoteAccount
|
||||
var created string
|
||||
var synced sql.NullString
|
||||
if err := scanner.Scan(&value.ID, &value.Provider, &value.ProviderID, &value.Name, &created, &synced); err != nil {
|
||||
return value, err
|
||||
}
|
||||
var err error
|
||||
if value.CreatedAt, err = decodeTime(created); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.LastSyncedAt, err = decodeOptionalTime(synced); err != nil {
|
||||
return value, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListAccounts(ctx context.Context) ([]domain.RemoteAccount, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `SELECT id, provider, provider_id, name, created_at, last_synced_at
|
||||
FROM accounts ORDER BY name COLLATE NOCASE, id`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list accounts: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.RemoteAccount, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanAccount(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan account: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) SaveZones(ctx context.Context, zones []domain.Zone) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: begin zone save: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for _, value := range zones {
|
||||
servers, err := encodeJSON(value.NameServers)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: encode zone name servers: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO zones (
|
||||
id, provider, provider_id, account_id, preferred_credential_id, name,
|
||||
unicode_name, status, paused, plan, name_servers_json, modified_at, last_synced_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET provider=excluded.provider,
|
||||
provider_id=excluded.provider_id, account_id=excluded.account_id,
|
||||
preferred_credential_id=excluded.preferred_credential_id, name=excluded.name,
|
||||
unicode_name=excluded.unicode_name, status=excluded.status, paused=excluded.paused,
|
||||
plan=excluded.plan, name_servers_json=excluded.name_servers_json,
|
||||
modified_at=excluded.modified_at, last_synced_at=excluded.last_synced_at`,
|
||||
value.ID, value.Provider, value.ProviderID, value.AccountID, value.PreferredCredentialID,
|
||||
value.Name, value.UnicodeName, string(value.Status), value.Paused, value.Plan,
|
||||
servers, encodeOptionalTime(value.ModifiedAt), encodeOptionalTime(value.LastSyncedAt)); err != nil {
|
||||
return fmt.Errorf("sqlite: save zone %s: %w", value.ID, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("sqlite: commit zone save: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const zoneColumns = `id, provider, provider_id, account_id, preferred_credential_id, name,
|
||||
unicode_name, status, paused, plan, name_servers_json, modified_at, last_synced_at`
|
||||
|
||||
func scanZone(scanner interface{ Scan(...any) error }) (domain.Zone, error) {
|
||||
var value domain.Zone
|
||||
var status, servers string
|
||||
var modified, synced sql.NullString
|
||||
if err := scanner.Scan(&value.ID, &value.Provider, &value.ProviderID, &value.AccountID,
|
||||
&value.PreferredCredentialID, &value.Name, &value.UnicodeName, &status, &value.Paused,
|
||||
&value.Plan, &servers, &modified, &synced); err != nil {
|
||||
return value, err
|
||||
}
|
||||
value.Status = domain.ZoneStatus(status)
|
||||
if err := decodeJSON(servers, &value.NameServers); err != nil {
|
||||
return value, err
|
||||
}
|
||||
var err error
|
||||
if value.ModifiedAt, err = decodeOptionalTime(modified); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.LastSyncedAt, err = decodeOptionalTime(synced); err != nil {
|
||||
return value, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListZones(ctx context.Context) ([]domain.Zone, error) {
|
||||
rows, err := r.db.QueryContext(ctx, "SELECT "+zoneColumns+" FROM zones ORDER BY name COLLATE NOCASE, id")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list zones: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.Zone, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanZone(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan zone: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) GetZone(ctx context.Context, id string) (domain.Zone, error) {
|
||||
value, err := scanZone(r.db.QueryRowContext(ctx, "SELECT "+zoneColumns+" FROM zones WHERE id = ?", id))
|
||||
if err != nil {
|
||||
return value, fmt.Errorf("sqlite: get zone: %w", err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
CREATE TABLE credentials (
|
||||
id TEXT PRIMARY KEY,
|
||||
provider TEXT NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
account_hint TEXT NOT NULL DEFAULT '',
|
||||
secret_ref TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
capabilities_json TEXT NOT NULL DEFAULT '[]',
|
||||
created_at TEXT NOT NULL,
|
||||
last_verified_at TEXT,
|
||||
last_error TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE accounts (
|
||||
id TEXT PRIMARY KEY,
|
||||
provider TEXT NOT NULL,
|
||||
provider_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
last_synced_at TEXT,
|
||||
UNIQUE(provider, provider_id)
|
||||
);
|
||||
|
||||
CREATE TABLE account_credentials (
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
credential_id TEXT NOT NULL REFERENCES credentials(id) ON DELETE CASCADE,
|
||||
preferred INTEGER NOT NULL DEFAULT 0 CHECK (preferred IN (0, 1)),
|
||||
PRIMARY KEY (account_id, credential_id)
|
||||
);
|
||||
CREATE INDEX account_credentials_credential_idx ON account_credentials(credential_id);
|
||||
|
||||
CREATE TABLE zones (
|
||||
id TEXT PRIMARY KEY,
|
||||
provider TEXT NOT NULL,
|
||||
provider_id TEXT NOT NULL,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
preferred_credential_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
unicode_name TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL,
|
||||
paused INTEGER NOT NULL DEFAULT 0 CHECK (paused IN (0, 1)),
|
||||
plan TEXT NOT NULL DEFAULT '',
|
||||
name_servers_json TEXT NOT NULL DEFAULT '[]',
|
||||
modified_at TEXT,
|
||||
last_synced_at TEXT,
|
||||
UNIQUE(provider, provider_id)
|
||||
);
|
||||
CREATE INDEX zones_account_idx ON zones(account_id);
|
||||
CREATE INDEX zones_name_idx ON zones(name);
|
||||
|
||||
CREATE TABLE dns_records (
|
||||
id TEXT PRIMARY KEY,
|
||||
provider_id TEXT NOT NULL,
|
||||
zone_id TEXT NOT NULL REFERENCES zones(id) ON DELETE CASCADE,
|
||||
type TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
unicode_name TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
priority INTEGER,
|
||||
ttl INTEGER NOT NULL,
|
||||
proxied INTEGER NOT NULL DEFAULT 0 CHECK (proxied IN (0, 1)),
|
||||
proxiable INTEGER NOT NULL DEFAULT 0 CHECK (proxiable IN (0, 1)),
|
||||
comment TEXT NOT NULL DEFAULT '',
|
||||
tags_json TEXT NOT NULL DEFAULT '[]',
|
||||
managed INTEGER NOT NULL DEFAULT 0 CHECK (managed IN (0, 1)),
|
||||
data_json BLOB,
|
||||
raw_json BLOB,
|
||||
modified_at TEXT,
|
||||
last_synced_at TEXT,
|
||||
UNIQUE(zone_id, provider_id)
|
||||
);
|
||||
CREATE INDEX dns_records_zone_idx ON dns_records(zone_id);
|
||||
CREATE INDEX dns_records_lookup_idx ON dns_records(zone_id, name, type);
|
||||
|
||||
CREATE TABLE zone_dns_sync (
|
||||
zone_id TEXT PRIMARY KEY REFERENCES zones(id) ON DELETE CASCADE,
|
||||
synced_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE tls_settings (
|
||||
zone_id TEXT PRIMARY KEY REFERENCES zones(id) ON DELETE CASCADE,
|
||||
mode TEXT NOT NULL,
|
||||
always_use_https INTEGER NOT NULL DEFAULT 0 CHECK (always_use_https IN (0, 1)),
|
||||
minimum_tls TEXT NOT NULL,
|
||||
tls_1_3 INTEGER NOT NULL DEFAULT 0 CHECK (tls_1_3 IN (0, 1)),
|
||||
has_proxied_dns INTEGER NOT NULL DEFAULT 0 CHECK (has_proxied_dns IN (0, 1)),
|
||||
last_synced_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE acme_accounts (
|
||||
id TEXT PRIMARY KEY,
|
||||
environment TEXT NOT NULL UNIQUE,
|
||||
directory_url TEXT NOT NULL,
|
||||
email TEXT NOT NULL,
|
||||
registration TEXT NOT NULL,
|
||||
secret_ref TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE certificate_lineages (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
zone_id TEXT,
|
||||
source TEXT NOT NULL,
|
||||
identifiers_json TEXT NOT NULL,
|
||||
key_algorithm TEXT NOT NULL,
|
||||
profile TEXT NOT NULL,
|
||||
acme_account_id TEXT,
|
||||
current_version_id TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX certificate_lineages_zone_idx ON certificate_lineages(zone_id);
|
||||
|
||||
CREATE TABLE certificate_versions (
|
||||
id TEXT PRIMARY KEY,
|
||||
lineage_id TEXT NOT NULL REFERENCES certificate_lineages(id) ON DELETE CASCADE,
|
||||
serial_number TEXT NOT NULL,
|
||||
fingerprint_sha256 TEXT NOT NULL,
|
||||
issuer TEXT NOT NULL,
|
||||
identifiers_json TEXT NOT NULL,
|
||||
not_before TEXT NOT NULL,
|
||||
not_after TEXT NOT NULL,
|
||||
certificate_path TEXT NOT NULL,
|
||||
chain_path TEXT NOT NULL DEFAULT '',
|
||||
private_key_ref TEXT NOT NULL,
|
||||
renewal_window_start TEXT,
|
||||
renewal_window_end TEXT,
|
||||
exported_at TEXT,
|
||||
export_path TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX certificate_versions_lineage_idx ON certificate_versions(lineage_id, created_at DESC);
|
||||
CREATE INDEX certificate_versions_expiry_idx ON certificate_versions(not_after);
|
||||
|
||||
CREATE TABLE endpoints (
|
||||
id TEXT PRIMARY KEY,
|
||||
zone_id TEXT NOT NULL REFERENCES zones(id) ON DELETE CASCADE,
|
||||
host TEXT NOT NULL,
|
||||
port INTEGER NOT NULL CHECK (port > 0 AND port <= 65535),
|
||||
enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1)),
|
||||
last_checked_at TEXT,
|
||||
resolved_addresses_json TEXT NOT NULL DEFAULT '[]',
|
||||
fingerprint_sha256 TEXT NOT NULL DEFAULT '',
|
||||
issuer TEXT NOT NULL DEFAULT '',
|
||||
not_after TEXT,
|
||||
valid_for_host INTEGER NOT NULL DEFAULT 0 CHECK (valid_for_host IN (0, 1)),
|
||||
trusted INTEGER NOT NULL DEFAULT 0 CHECK (trusted IN (0, 1)),
|
||||
last_error TEXT NOT NULL DEFAULT '',
|
||||
UNIQUE(host, port)
|
||||
);
|
||||
CREATE INDEX endpoints_zone_idx ON endpoints(zone_id);
|
||||
|
||||
CREATE TABLE health_issues (
|
||||
id TEXT PRIMARY KEY,
|
||||
owner_id TEXT NOT NULL,
|
||||
severity TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
resource_id TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
detail TEXT NOT NULL,
|
||||
action TEXT NOT NULL DEFAULT '',
|
||||
observed_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX health_issues_owner_idx ON health_issues(owner_id);
|
||||
CREATE INDEX health_issues_order_idx ON health_issues(severity, observed_at DESC);
|
||||
|
||||
CREATE TABLE jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
resource_id TEXT NOT NULL DEFAULT '',
|
||||
progress INTEGER NOT NULL DEFAULT 0 CHECK (progress >= 0 AND progress <= 100),
|
||||
message TEXT NOT NULL DEFAULT '',
|
||||
payload_json BLOB,
|
||||
error TEXT NOT NULL DEFAULT '',
|
||||
retry_at TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
started_at TEXT,
|
||||
finished_at TEXT,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX jobs_updated_idx ON jobs(updated_at DESC);
|
||||
CREATE INDEX jobs_recoverable_idx ON jobs(state, retry_at, updated_at);
|
||||
|
||||
CREATE TABLE challenge_journal (
|
||||
id TEXT PRIMARY KEY,
|
||||
job_id TEXT NOT NULL,
|
||||
zone_id TEXT NOT NULL,
|
||||
record_id TEXT NOT NULL,
|
||||
fqdn TEXT NOT NULL,
|
||||
value_hash TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
cleaned_at TEXT
|
||||
);
|
||||
CREATE INDEX challenge_journal_open_idx ON challenge_journal(cleaned_at, created_at);
|
||||
CREATE INDEX challenge_journal_job_idx ON challenge_journal(job_id);
|
||||
|
||||
CREATE TABLE audit_events (
|
||||
id TEXT PRIMARY KEY,
|
||||
actor TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
resource_id TEXT NOT NULL DEFAULT '',
|
||||
before_json BLOB,
|
||||
after_json BLOB,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX audit_events_created_idx ON audit_events(created_at DESC);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE challenge_journal ADD COLUMN credential_id TEXT NOT NULL DEFAULT '';
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE certificate_versions ADD COLUMN revoked_at TEXT;
|
||||
ALTER TABLE certificate_versions ADD COLUMN revocation_reason INTEGER;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE certificate_versions ADD COLUMN revocation_pending_at TEXT;
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE credential_zone_capabilities (
|
||||
credential_id TEXT NOT NULL REFERENCES credentials(id) ON DELETE CASCADE,
|
||||
zone_id TEXT NOT NULL REFERENCES zones(id) ON DELETE CASCADE,
|
||||
capability TEXT NOT NULL,
|
||||
observed_at TEXT NOT NULL,
|
||||
PRIMARY KEY (credential_id, zone_id, capability)
|
||||
);
|
||||
CREATE INDEX credential_zone_capabilities_zone_idx
|
||||
ON credential_zone_capabilities(zone_id, capability);
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE certificate_commit_journal (
|
||||
version_id TEXT PRIMARY KEY,
|
||||
lineage_id TEXT NOT NULL,
|
||||
secret_ref TEXT NOT NULL DEFAULT '',
|
||||
artifact_path TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX certificate_commit_journal_created_idx
|
||||
ON certificate_commit_journal(created_at);
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE acme_account_commit_journal (
|
||||
account_id TEXT PRIMARY KEY,
|
||||
secret_ref TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX acme_account_commit_journal_created_idx
|
||||
ON acme_account_commit_journal(created_at);
|
||||
@@ -0,0 +1,29 @@
|
||||
-- Older development schemas did not enforce the physical endpoint identity.
|
||||
-- Retain the most useful observation, remove duplicate-owned stale health
|
||||
-- issues, and then make host+port safe for ON CONFLICT routing reassignment.
|
||||
CREATE TEMP TABLE endpoint_deduplication AS
|
||||
SELECT id AS duplicate_id, keeper_id
|
||||
FROM (
|
||||
SELECT id,
|
||||
FIRST_VALUE(id) OVER (
|
||||
PARTITION BY host, port
|
||||
ORDER BY enabled DESC,
|
||||
CASE WHEN last_checked_at IS NULL THEN 1 ELSE 0 END,
|
||||
last_checked_at DESC,
|
||||
id
|
||||
) AS keeper_id
|
||||
FROM endpoints
|
||||
)
|
||||
WHERE id <> keeper_id;
|
||||
|
||||
DELETE FROM health_issues
|
||||
WHERE owner_id IN (SELECT duplicate_id FROM endpoint_deduplication)
|
||||
OR resource_id IN (SELECT duplicate_id FROM endpoint_deduplication);
|
||||
|
||||
DELETE FROM endpoints
|
||||
WHERE id IN (SELECT duplicate_id FROM endpoint_deduplication);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS endpoints_host_port_unique_idx
|
||||
ON endpoints(host, port);
|
||||
|
||||
DROP TABLE endpoint_deduplication;
|
||||
@@ -0,0 +1,476 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/MeghdadFadaee/domainops/internal/domain"
|
||||
)
|
||||
|
||||
func (r *Repository) SaveEndpoint(ctx context.Context, value domain.ObservedEndpoint) error {
|
||||
addresses, err := encodeJSON(value.ResolvedAddresses)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: encode endpoint addresses: %w", err)
|
||||
}
|
||||
_, err = r.db.ExecContext(ctx, `INSERT INTO endpoints (
|
||||
id, zone_id, host, port, enabled, last_checked_at, resolved_addresses_json,
|
||||
fingerprint_sha256, issuer, not_after, valid_for_host, trusted, last_error
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET zone_id=excluded.zone_id, host=excluded.host,
|
||||
port=excluded.port, enabled=excluded.enabled,
|
||||
last_checked_at=excluded.last_checked_at,
|
||||
resolved_addresses_json=excluded.resolved_addresses_json,
|
||||
fingerprint_sha256=excluded.fingerprint_sha256, issuer=excluded.issuer,
|
||||
not_after=excluded.not_after, valid_for_host=excluded.valid_for_host,
|
||||
trusted=excluded.trusted, last_error=excluded.last_error
|
||||
ON CONFLICT(host, port) DO UPDATE SET zone_id=excluded.zone_id,
|
||||
enabled=excluded.enabled, last_checked_at=excluded.last_checked_at,
|
||||
resolved_addresses_json=excluded.resolved_addresses_json,
|
||||
fingerprint_sha256=excluded.fingerprint_sha256, issuer=excluded.issuer,
|
||||
not_after=excluded.not_after, valid_for_host=excluded.valid_for_host,
|
||||
trusted=excluded.trusted, last_error=excluded.last_error`,
|
||||
value.ID, value.ZoneID, value.Host, value.Port, value.Enabled,
|
||||
encodeOptionalTime(value.LastCheckedAt), addresses, value.FingerprintSHA256,
|
||||
value.Issuer, encodeOptionalTime(value.NotAfter), value.ValidForHost,
|
||||
value.Trusted, value.LastError)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save endpoint: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanEndpoint(scanner interface{ Scan(...any) error }) (domain.ObservedEndpoint, error) {
|
||||
var value domain.ObservedEndpoint
|
||||
var checked, notAfter sql.NullString
|
||||
var addresses string
|
||||
if err := scanner.Scan(&value.ID, &value.ZoneID, &value.Host, &value.Port,
|
||||
&value.Enabled, &checked, &addresses, &value.FingerprintSHA256, &value.Issuer,
|
||||
¬After, &value.ValidForHost, &value.Trusted, &value.LastError); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if err := decodeJSON(addresses, &value.ResolvedAddresses); err != nil {
|
||||
return value, err
|
||||
}
|
||||
var err error
|
||||
if value.LastCheckedAt, err = decodeOptionalTime(checked); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.NotAfter, err = decodeOptionalTime(notAfter); err != nil {
|
||||
return value, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
const endpointColumns = `id, zone_id, host, port, enabled, last_checked_at,
|
||||
resolved_addresses_json, fingerprint_sha256, issuer, not_after,
|
||||
valid_for_host, trusted, last_error`
|
||||
|
||||
func (r *Repository) ListEndpoints(ctx context.Context) ([]domain.ObservedEndpoint, error) {
|
||||
rows, err := r.db.QueryContext(ctx, "SELECT "+endpointColumns+" FROM endpoints ORDER BY host COLLATE NOCASE, port, id")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list endpoints: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.ObservedEndpoint, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanEndpoint(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan endpoint: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) SaveHealthIssues(ctx context.Context, ownerID string, values []domain.HealthIssue) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: begin health replacement: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM health_issues WHERE owner_id = ?", ownerID); err != nil {
|
||||
return fmt.Errorf("sqlite: clear health issues: %w", err)
|
||||
}
|
||||
for _, value := range values {
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO health_issues (
|
||||
id, owner_id, severity, kind, resource_id, title, detail, action, observed_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, value.ID, ownerID,
|
||||
string(value.Severity), value.Kind, value.ResourceID, value.Title,
|
||||
value.Detail, value.Action, encodeTime(value.ObservedAt)); err != nil {
|
||||
return fmt.Errorf("sqlite: save health issue %s: %w", value.ID, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("sqlite: commit health replacement: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanHealthIssue(scanner interface{ Scan(...any) error }) (domain.HealthIssue, error) {
|
||||
var value domain.HealthIssue
|
||||
var severity, observed string
|
||||
if err := scanner.Scan(&value.ID, &severity, &value.Kind, &value.ResourceID,
|
||||
&value.Title, &value.Detail, &value.Action, &observed); err != nil {
|
||||
return value, err
|
||||
}
|
||||
value.Severity = domain.Severity(severity)
|
||||
var err error
|
||||
value.ObservedAt, err = decodeTime(observed)
|
||||
return value, err
|
||||
}
|
||||
|
||||
const healthColumns = `id, severity, kind, resource_id, title, detail, action, observed_at`
|
||||
const healthOrder = `CASE severity WHEN 'critical' THEN 0 WHEN 'warning' THEN 1 ELSE 2 END,
|
||||
observed_at DESC, id`
|
||||
|
||||
func listHealthIssues(ctx context.Context, queryer interface {
|
||||
QueryContext(context.Context, string, ...any) (*sql.Rows, error)
|
||||
}) ([]domain.HealthIssue, error) {
|
||||
rows, err := queryer.QueryContext(ctx, "SELECT "+healthColumns+" FROM health_issues ORDER BY "+healthOrder)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.HealthIssue, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanHealthIssue(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) ListHealthIssues(ctx context.Context) ([]domain.HealthIssue, error) {
|
||||
values, err := listHealthIssues(ctx, r.db)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list health issues: %w", err)
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveJob(ctx context.Context, value domain.Job) error {
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO jobs (
|
||||
id, kind, state, resource_id, progress, message, payload_json, error,
|
||||
retry_at, created_at, started_at, finished_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET kind=excluded.kind, state=excluded.state,
|
||||
resource_id=excluded.resource_id, progress=excluded.progress,
|
||||
message=excluded.message, payload_json=excluded.payload_json,
|
||||
error=excluded.error, retry_at=excluded.retry_at, created_at=excluded.created_at,
|
||||
started_at=excluded.started_at, finished_at=excluded.finished_at,
|
||||
updated_at=excluded.updated_at`, value.ID, value.Kind, string(value.State),
|
||||
value.ResourceID, value.Progress, value.Message, rawOrNil(value.Payload), value.Error,
|
||||
encodeOptionalTime(value.RetryAt), encodeTime(value.CreatedAt),
|
||||
encodeOptionalTime(value.StartedAt), encodeOptionalTime(value.FinishedAt),
|
||||
encodeTime(value.UpdatedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save job: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const jobColumns = `id, kind, state, resource_id, progress, message, payload_json,
|
||||
error, retry_at, created_at, started_at, finished_at, updated_at`
|
||||
|
||||
func scanJob(scanner interface{ Scan(...any) error }) (domain.Job, error) {
|
||||
var value domain.Job
|
||||
var state, created, updated string
|
||||
var payload []byte
|
||||
var retry, started, finished sql.NullString
|
||||
if err := scanner.Scan(&value.ID, &value.Kind, &state, &value.ResourceID,
|
||||
&value.Progress, &value.Message, &payload, &value.Error, &retry, &created,
|
||||
&started, &finished, &updated); err != nil {
|
||||
return value, err
|
||||
}
|
||||
value.State = domain.JobState(state)
|
||||
value.Payload = copyRaw(payload)
|
||||
var err error
|
||||
if value.CreatedAt, err = decodeTime(created); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.UpdatedAt, err = decodeTime(updated); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.RetryAt, err = decodeOptionalTime(retry); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.StartedAt, err = decodeOptionalTime(started); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.FinishedAt, err = decodeOptionalTime(finished); err != nil {
|
||||
return value, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) GetJob(ctx context.Context, id string) (domain.Job, error) {
|
||||
value, err := scanJob(r.db.QueryRowContext(ctx, "SELECT "+jobColumns+" FROM jobs WHERE id = ?", id))
|
||||
if err != nil {
|
||||
return value, fmt.Errorf("sqlite: get job: %w", err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListJobs(ctx context.Context, limit int) ([]domain.Job, error) {
|
||||
query := "SELECT " + jobColumns + " FROM jobs ORDER BY updated_at DESC, id"
|
||||
var args []any
|
||||
if limit > 0 {
|
||||
query += " LIMIT ?"
|
||||
args = append(args, limit)
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.Job, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanJob(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan job: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) ListRecoverableJobs(ctx context.Context) ([]domain.Job, error) {
|
||||
rows, err := r.db.QueryContext(ctx, "SELECT "+jobColumns+` FROM jobs
|
||||
WHERE state IN ('queued', 'running', 'waiting_for_dns')
|
||||
OR (state = 'failed' AND retry_at IS NOT NULL)
|
||||
ORDER BY created_at, id`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list recoverable jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.Job, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanJob(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan recoverable job: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
// ReconcileInterruptedJobs closes process-local work that cannot still be
|
||||
// running after a new DomainOps process has acquired the data-directory lock.
|
||||
// Journal recovery runs first; this final state transition prevents abandoned
|
||||
// jobs from remaining permanently active on the dashboard.
|
||||
func (r *Repository) ReconcileInterruptedJobs(ctx context.Context, now time.Time) (int64, error) {
|
||||
encodedNow := encodeTime(now.UTC())
|
||||
result, err := r.db.ExecContext(ctx, `UPDATE jobs
|
||||
SET state = 'failed',
|
||||
message = 'Interrupted by previous DomainOps shutdown',
|
||||
error = 'operation was interrupted; crash recovery completed but the operation itself was not resumed',
|
||||
retry_at = NULL,
|
||||
finished_at = ?,
|
||||
updated_at = ?
|
||||
WHERE state IN ('queued', 'running', 'waiting_for_dns')`, encodedNow, encodedNow)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("sqlite: reconcile interrupted jobs: %w", err)
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("sqlite: count reconciled interrupted jobs: %w", err)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveChallenge(ctx context.Context, value domain.ChallengeJournal) error {
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO challenge_journal (
|
||||
id, job_id, credential_id, zone_id, record_id, fqdn, value_hash, created_at, cleaned_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET job_id=excluded.job_id, credential_id=excluded.credential_id, zone_id=excluded.zone_id,
|
||||
record_id=excluded.record_id, fqdn=excluded.fqdn,
|
||||
value_hash=excluded.value_hash, created_at=excluded.created_at,
|
||||
cleaned_at=excluded.cleaned_at`, value.ID, value.JobID, value.CredentialID, value.ZoneID,
|
||||
value.RecordID, value.FQDN, value.ValueHash, encodeTime(value.CreatedAt),
|
||||
encodeOptionalTime(value.CleanedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: save challenge journal: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanChallenge(scanner interface{ Scan(...any) error }) (domain.ChallengeJournal, error) {
|
||||
var value domain.ChallengeJournal
|
||||
var created string
|
||||
var cleaned sql.NullString
|
||||
if err := scanner.Scan(&value.ID, &value.JobID, &value.CredentialID, &value.ZoneID, &value.RecordID,
|
||||
&value.FQDN, &value.ValueHash, &created, &cleaned); err != nil {
|
||||
return value, err
|
||||
}
|
||||
var err error
|
||||
if value.CreatedAt, err = decodeTime(created); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if value.CleanedAt, err = decodeOptionalTime(cleaned); err != nil {
|
||||
return value, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListOpenChallenges(ctx context.Context) ([]domain.ChallengeJournal, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `SELECT id, job_id, credential_id, zone_id, record_id, fqdn,
|
||||
value_hash, created_at, cleaned_at FROM challenge_journal
|
||||
WHERE cleaned_at IS NULL ORDER BY created_at, id`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list open challenges: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.ChallengeJournal, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanChallenge(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan challenge: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) MarkChallengeCleaned(ctx context.Context, id string, cleanedAt time.Time) error {
|
||||
if _, err := r.db.ExecContext(ctx, `UPDATE challenge_journal SET cleaned_at = ? WHERE id = ?`,
|
||||
encodeTime(cleanedAt), id); err != nil {
|
||||
return fmt.Errorf("sqlite: mark challenge cleaned: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) AppendAudit(ctx context.Context, value domain.AuditEvent) error {
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO audit_events (
|
||||
id, actor, action, resource_id, before_json, after_json, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)`, value.ID, value.Actor, value.Action,
|
||||
value.ResourceID, rawOrNil(value.Before), rawOrNil(value.After), encodeTime(value.CreatedAt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: append audit event: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanAudit(scanner interface{ Scan(...any) error }) (domain.AuditEvent, error) {
|
||||
var value domain.AuditEvent
|
||||
var before, after []byte
|
||||
var created string
|
||||
if err := scanner.Scan(&value.ID, &value.Actor, &value.Action, &value.ResourceID,
|
||||
&before, &after, &created); err != nil {
|
||||
return value, err
|
||||
}
|
||||
value.Before = copyRaw(before)
|
||||
value.After = copyRaw(after)
|
||||
var err error
|
||||
value.CreatedAt, err = decodeTime(created)
|
||||
return value, err
|
||||
}
|
||||
|
||||
func (r *Repository) ListAudit(ctx context.Context, limit int) ([]domain.AuditEvent, error) {
|
||||
query := `SELECT id, actor, action, resource_id, before_json, after_json, created_at
|
||||
FROM audit_events ORDER BY created_at DESC, id`
|
||||
var args []any
|
||||
if limit > 0 {
|
||||
query += " LIMIT ?"
|
||||
args = append(args, limit)
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: list audit events: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]domain.AuditEvent, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanAudit(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: scan audit event: %w", err)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) Dashboard(ctx context.Context, now time.Time) (domain.DashboardSnapshot, error) {
|
||||
snapshot := domain.DashboardSnapshot{GeneratedAt: now}
|
||||
tx, err := r.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||
if err != nil {
|
||||
return snapshot, fmt.Errorf("sqlite: begin dashboard snapshot: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
counts := []struct {
|
||||
query string
|
||||
value *int
|
||||
}{
|
||||
{"SELECT COUNT(*) FROM credentials", &snapshot.Credentials},
|
||||
{"SELECT COUNT(*) FROM accounts", &snapshot.Accounts},
|
||||
{"SELECT COUNT(*) FROM zones", &snapshot.Zones},
|
||||
{"SELECT COUNT(*) FROM dns_records", &snapshot.DNSRecords},
|
||||
{"SELECT COUNT(*) FROM certificate_lineages", &snapshot.Certificates},
|
||||
{`SELECT COUNT(*) FROM jobs WHERE state IN ('queued', 'running', 'waiting_for_dns')`, &snapshot.ActiveJobs},
|
||||
}
|
||||
for _, item := range counts {
|
||||
if err := tx.QueryRowContext(ctx, item.query).Scan(item.value); err != nil {
|
||||
return snapshot, fmt.Errorf("sqlite: count dashboard resources: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
rows, err := tx.QueryContext(ctx, `SELECT v.not_before, v.not_after, v.renewal_window_start
|
||||
FROM certificate_lineages l
|
||||
JOIN certificate_versions v ON v.id = l.current_version_id
|
||||
WHERE v.revoked_at IS NULL AND v.revocation_pending_at IS NULL`)
|
||||
if err != nil {
|
||||
return snapshot, fmt.Errorf("sqlite: load dashboard certificates: %w", err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var notBeforeRaw, notAfterRaw string
|
||||
var renewalRaw sql.NullString
|
||||
if err := rows.Scan(¬BeforeRaw, ¬AfterRaw, &renewalRaw); err != nil {
|
||||
rows.Close()
|
||||
return snapshot, fmt.Errorf("sqlite: scan dashboard certificate: %w", err)
|
||||
}
|
||||
notBefore, err := decodeTime(notBeforeRaw)
|
||||
if err != nil {
|
||||
rows.Close()
|
||||
return snapshot, fmt.Errorf("sqlite: decode dashboard certificate: %w", err)
|
||||
}
|
||||
notAfter, err := decodeTime(notAfterRaw)
|
||||
if err != nil {
|
||||
rows.Close()
|
||||
return snapshot, fmt.Errorf("sqlite: decode dashboard certificate: %w", err)
|
||||
}
|
||||
if !now.Before(notAfter) {
|
||||
snapshot.CertificatesExpired++
|
||||
continue
|
||||
}
|
||||
var dueAt time.Time
|
||||
if renewalRaw.Valid {
|
||||
dueAt, err = decodeTime(renewalRaw.String)
|
||||
if err != nil {
|
||||
rows.Close()
|
||||
return snapshot, fmt.Errorf("sqlite: decode renewal window: %w", err)
|
||||
}
|
||||
} else {
|
||||
dueAt = notBefore.Add(notAfter.Sub(notBefore) * 2 / 3)
|
||||
}
|
||||
if !now.Before(dueAt) {
|
||||
snapshot.CertificatesDue++
|
||||
}
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return snapshot, fmt.Errorf("sqlite: close dashboard certificates: %w", err)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return snapshot, fmt.Errorf("sqlite: iterate dashboard certificates: %w", err)
|
||||
}
|
||||
snapshot.Issues, err = listHealthIssues(ctx, tx)
|
||||
if err != nil {
|
||||
return snapshot, fmt.Errorf("sqlite: load dashboard issues: %w", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return snapshot, fmt.Errorf("sqlite: commit dashboard snapshot: %w", err)
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// Package sqlite implements DomainOps' durable local repository.
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/MeghdadFadaee/domainops/internal/store"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
const (
|
||||
directoryMode = 0o700
|
||||
databaseMode = 0o600
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
// Repository is a SQLite-backed store.Repository.
|
||||
type Repository struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
var _ store.Repository = (*Repository)(nil)
|
||||
|
||||
// New creates the database parent directory, opens path, and configures SQLite.
|
||||
// It intentionally does not run migrations; callers must call Migrate before use.
|
||||
func New(path string) (*Repository, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return nil, errors.New("sqlite: database path is empty")
|
||||
}
|
||||
|
||||
var dsn string
|
||||
if path == ":memory:" {
|
||||
dsn = "file:domainops-memory?mode=memory&cache=shared"
|
||||
} else {
|
||||
absolute, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: resolve database path: %w", err)
|
||||
}
|
||||
dir := filepath.Dir(absolute)
|
||||
if err := os.MkdirAll(dir, directoryMode); err != nil {
|
||||
return nil, fmt.Errorf("sqlite: create database directory: %w", err)
|
||||
}
|
||||
if err := os.Chmod(dir, directoryMode); err != nil {
|
||||
return nil, fmt.Errorf("sqlite: secure database directory: %w", err)
|
||||
}
|
||||
u := &url.URL{Scheme: "file", Path: filepath.ToSlash(absolute)}
|
||||
dsn = u.String()
|
||||
}
|
||||
|
||||
separator := "?"
|
||||
if strings.Contains(dsn, "?") {
|
||||
separator = "&"
|
||||
}
|
||||
// FULL synchronous mode is required for the certificate/challenge journals:
|
||||
// an acknowledged intent or final metadata commit must survive power loss
|
||||
// before filesystem activation or orphan cleanup can rely on it.
|
||||
dsn += separator + "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=synchronous(FULL)"
|
||||
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sqlite: open: %w", err)
|
||||
}
|
||||
db.SetMaxOpenConns(4)
|
||||
db.SetMaxIdleConns(4)
|
||||
db.SetConnMaxLifetime(0)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, fmt.Errorf("sqlite: connect: %w", err)
|
||||
}
|
||||
if path != ":memory:" {
|
||||
if err := os.Chmod(path, databaseMode); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, fmt.Errorf("sqlite: secure database file: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &Repository{db: db}, nil
|
||||
}
|
||||
|
||||
// Close closes the database and releases its resources.
|
||||
func (r *Repository) Close() error {
|
||||
if r == nil || r.db == nil {
|
||||
return nil
|
||||
}
|
||||
return r.db.Close()
|
||||
}
|
||||
|
||||
// Migrate applies all embedded migrations exactly once, in filename order.
|
||||
func (r *Repository) Migrate(ctx context.Context) error {
|
||||
if _, err := r.db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TEXT NOT NULL
|
||||
)`); err != nil {
|
||||
return fmt.Errorf("sqlite: initialize migrations: %w", err)
|
||||
}
|
||||
|
||||
entries, err := fs.ReadDir(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: read migrations: %w", err)
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||
continue
|
||||
}
|
||||
var applied int
|
||||
err := r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM schema_migrations WHERE version = ?", entry.Name()).Scan(&applied)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: inspect migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
if applied != 0 {
|
||||
continue
|
||||
}
|
||||
body, err := fs.ReadFile(migrationFiles, "migrations/"+entry.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: read migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sqlite: begin migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, string(body)); err == nil {
|
||||
_, err = tx.ExecContext(ctx, "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", entry.Name(), encodeTime(time.Now()))
|
||||
}
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
return fmt.Errorf("sqlite: apply migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("sqlite: commit migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/MeghdadFadaee/domainops/internal/domain"
|
||||
"github.com/MeghdadFadaee/domainops/internal/store"
|
||||
)
|
||||
|
||||
func openTestRepository(t *testing.T) *Repository {
|
||||
t.Helper()
|
||||
repository, err := New(filepath.Join(t.TempDir(), "state", "domainops.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = repository.Close() })
|
||||
if err := repository.Migrate(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repository.Migrate(context.Background()); err != nil {
|
||||
t.Fatalf("second migration must be idempotent: %v", err)
|
||||
}
|
||||
return repository
|
||||
}
|
||||
|
||||
func TestRepositoryUsesFullSynchronousDurability(t *testing.T) {
|
||||
r := openTestRepository(t)
|
||||
var synchronous int
|
||||
if err := r.db.QueryRow("PRAGMA synchronous").Scan(&synchronous); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if synchronous != 2 {
|
||||
t.Fatalf("PRAGMA synchronous = %d, want FULL (2)", synchronous)
|
||||
}
|
||||
}
|
||||
|
||||
func TestACMEAccountCommitClosesSecretIntentAtomically(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := openTestRepository(t)
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
intent := domain.ACMEAccountCommitIntent{AccountID: "acme-journal", SecretRef: "acme-account/acme-journal", CreatedAt: now}
|
||||
if err := r.SaveACMEAccountCommitIntent(ctx, intent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
account := domain.ACMEAccount{ID: intent.AccountID, Environment: "staging", DirectoryURL: "https://ca.invalid/directory", Email: "ops@example.com", Registration: `{}`, SecretRef: intent.SecretRef, CreatedAt: now}
|
||||
if err := r.CommitACMEAccount(ctx, account); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
intents, err := r.ListACMEAccountCommitIntents(ctx)
|
||||
if err != nil || len(intents) != 0 {
|
||||
t.Fatalf("ACME account intents = %#v, %v", intents, err)
|
||||
}
|
||||
loaded, err := r.GetACMEAccountByEnvironment(ctx, account.Environment)
|
||||
if err != nil || loaded.ID != account.ID || loaded.SecretRef != account.SecretRef {
|
||||
t.Fatalf("committed ACME account = %#v, %v", loaded, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestACMEAccountCommitConflictPreservesExistingAccountAndIntent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := openTestRepository(t)
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
existing := domain.ACMEAccount{ID: "acme-existing", Environment: "staging", DirectoryURL: "https://ca.invalid/directory", Email: "existing@example.com", Registration: `{}`, SecretRef: "acme-account/acme-existing", CreatedAt: now}
|
||||
if err := r.SaveACMEAccount(ctx, existing); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
intent := domain.ACMEAccountCommitIntent{AccountID: "acme-loser", SecretRef: "acme-account/acme-loser", CreatedAt: now.Add(time.Second)}
|
||||
if err := r.SaveACMEAccountCommitIntent(ctx, intent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
challenger := domain.ACMEAccount{ID: intent.AccountID, Environment: existing.Environment, DirectoryURL: "https://ca.invalid/directory", Email: "loser@example.com", Registration: `{}`, SecretRef: intent.SecretRef, CreatedAt: intent.CreatedAt}
|
||||
if err := r.CommitACMEAccount(ctx, challenger); !errors.Is(err, store.ErrACMEAccountConflict) {
|
||||
t.Fatalf("commit conflict = %v, want %v", err, store.ErrACMEAccountConflict)
|
||||
}
|
||||
loaded, err := r.GetACMEAccountByEnvironment(ctx, existing.Environment)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loaded.ID != existing.ID || loaded.SecretRef != existing.SecretRef || loaded.Email != existing.Email {
|
||||
t.Fatalf("existing account was replaced: %#v", loaded)
|
||||
}
|
||||
intents, err := r.ListACMEAccountCommitIntents(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(intents) != 1 || intents[0].AccountID != intent.AccountID {
|
||||
t.Fatalf("losing commit intent = %#v, want %#v", intents, intent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryInventoryDNSAndTLSRoundTrip(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := openTestRepository(t)
|
||||
now := time.Date(2026, 7, 11, 10, 0, 0, 0, time.UTC)
|
||||
verified := now.Add(time.Minute)
|
||||
credential := domain.Credential{
|
||||
ID: "cred_1", Provider: domain.ProviderCloudflare, Label: "Production",
|
||||
Kind: domain.CredentialUserToken, SecretRef: "secret_1", Status: domain.CredentialValid,
|
||||
Capabilities: []string{"dns:read", "dns:write"}, CreatedAt: now, LastVerifiedAt: &verified,
|
||||
}
|
||||
if err := r.SaveCredential(ctx, credential); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := []domain.RemoteAccount{{ID: "cfacct_a", Provider: domain.ProviderCloudflare, ProviderID: "a", Name: "Account A", CreatedAt: now}}
|
||||
links := []domain.AccountCredential{{AccountID: "cfacct_a", CredentialID: credential.ID, Preferred: true}}
|
||||
if err := r.SaveAccounts(ctx, accounts, links); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zone := domain.Zone{
|
||||
ID: "cfzone_z", Provider: domain.ProviderCloudflare, ProviderID: "z", AccountID: "cfacct_a",
|
||||
PreferredCredentialID: credential.ID, Name: "example.com", Status: domain.ZoneActive,
|
||||
Plan: "Free", NameServers: []string{"ns1.example", "ns2.example"}, LastSyncedAt: &now,
|
||||
}
|
||||
if err := r.SaveZones(ctx, []domain.Zone{zone}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.SaveCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:write", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if observed, err := r.HasCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:write"); err != nil || !observed {
|
||||
t.Fatalf("credential zone capability = %v, %v", observed, err)
|
||||
}
|
||||
if observedAt, observed, err := r.GetCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:write"); err != nil || !observed || !observedAt.Equal(now) {
|
||||
t.Fatalf("credential zone capability observation = %v, %v, %v", observedAt, observed, err)
|
||||
}
|
||||
if observed, err := r.HasCredentialZoneCapability(ctx, credential.ID, zone.ID, "tls:write"); err != nil || observed {
|
||||
t.Fatalf("unobserved zone capability = %v, %v", observed, err)
|
||||
}
|
||||
if err := r.SaveCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:read", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.InvalidateCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:read"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if observed, err := r.HasCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:read"); err != nil || observed {
|
||||
t.Fatalf("invalidated DNS-read capability = %v, %v", observed, err)
|
||||
}
|
||||
if observed, err := r.HasCredentialZoneCapability(ctx, credential.ID, zone.ID, "dns:write"); err != nil || !observed {
|
||||
t.Fatalf("unrelated DNS-write capability changed = %v, %v", observed, err)
|
||||
}
|
||||
if detached, err := r.GetZone(ctx, zone.ID); err != nil || detached.PreferredCredentialID != "" {
|
||||
t.Fatalf("invalidated preferred route = %#v, %v", detached, err)
|
||||
}
|
||||
priority := uint16(10)
|
||||
records := []domain.DNSRecord{
|
||||
{ID: "cfrecord_1", ProviderID: "1", ZoneID: zone.ID, Type: domain.RecordA, Name: "example.com", Content: "192.0.2.1", TTL: 1, Proxied: true, Proxiable: true, Tags: []string{"owner:test"}},
|
||||
{ID: "cfrecord_2", ProviderID: "2", ZoneID: zone.ID, Type: domain.RecordMX, Name: "example.com", Content: "mail.example.com", TTL: 3600, Priority: &priority},
|
||||
}
|
||||
if err := r.ReplaceDNSRecords(ctx, zone.ID, records, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := r.ListDNSRecords(ctx, zone.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(loaded) != 2 || loaded[0].ZoneID != zone.ID {
|
||||
t.Fatalf("loaded records = %#v", loaded)
|
||||
}
|
||||
if err := r.ReplaceDNSRecords(ctx, zone.ID, records[:1], now.Add(time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err = r.ListDNSRecords(ctx, zone.ID)
|
||||
if err != nil || len(loaded) != 1 {
|
||||
t.Fatalf("replacement = %#v, %v", loaded, err)
|
||||
}
|
||||
|
||||
settings := domain.EdgeTLSSettings{ZoneID: zone.ID, Mode: "strict", AlwaysUseHTTPS: true, MinimumTLS: "1.2", TLS13: true, HasProxiedDNS: true, LastSyncedAt: &now}
|
||||
if err := r.SaveTLSSettings(ctx, settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gotSettings, err := r.GetTLSSettings(ctx, zone.ID)
|
||||
if err != nil || gotSettings.Mode != "strict" || !gotSettings.TLS13 {
|
||||
t.Fatalf("TLS = %#v, %v", gotSettings, err)
|
||||
}
|
||||
|
||||
gotCredential, err := r.GetCredential(ctx, credential.ID)
|
||||
if err != nil || gotCredential.SecretRef != "secret_1" || len(gotCredential.Capabilities) != 2 {
|
||||
t.Fatalf("credential = %#v, %v", gotCredential, err)
|
||||
}
|
||||
gotZone, err := r.GetZone(ctx, zone.ID)
|
||||
if err != nil || gotZone.Name != zone.Name || len(gotZone.NameServers) != 2 {
|
||||
t.Fatalf("zone = %#v, %v", gotZone, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryCertificatesJobsHealthAndDashboard(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := openTestRepository(t)
|
||||
now := time.Date(2026, 7, 11, 10, 0, 0, 0, time.UTC)
|
||||
credential := domain.Credential{ID: "cred", Provider: domain.ProviderCloudflare, Label: "CF", Kind: domain.CredentialUserToken, SecretRef: "secret", Status: domain.CredentialValid, CreatedAt: now}
|
||||
if err := r.SaveCredential(ctx, credential); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
account := domain.RemoteAccount{ID: "account", Provider: domain.ProviderCloudflare, ProviderID: "remote", Name: "Remote", CreatedAt: now}
|
||||
if err := r.SaveAccounts(ctx, []domain.RemoteAccount{account}, []domain.AccountCredential{{AccountID: account.ID, CredentialID: credential.ID, Preferred: true}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zone := domain.Zone{ID: "zone", Provider: domain.ProviderCloudflare, ProviderID: "remote-zone", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "example.com", Status: domain.ZoneActive}
|
||||
if err := r.SaveZones(ctx, []domain.Zone{zone}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
acme := domain.ACMEAccount{ID: "acme", Environment: "production", DirectoryURL: "https://ca.invalid/directory", Email: "ops@example.com", Registration: `{}`, SecretRef: "acme-secret", CreatedAt: now}
|
||||
if err := r.SaveACMEAccount(ctx, acme); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loaded, err := r.GetACMEAccountByEnvironment(ctx, "production"); err != nil || loaded.SecretRef != acme.SecretRef {
|
||||
t.Fatalf("ACME = %#v, %v", loaded, err)
|
||||
}
|
||||
|
||||
lineage := domain.CertificateLineage{ID: "lineage", Name: "example.com", ZoneID: zone.ID, Source: domain.CertificateManaged, Identifiers: []string{"example.com", "*.example.com"}, KeyAlgorithm: domain.KeyECDSAP256, Profile: "classic", ACMEAccountID: acme.ID, CreatedAt: now, UpdatedAt: now}
|
||||
if err := r.SaveCertificateLineage(ctx, lineage); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
due := now.Add(-time.Hour)
|
||||
version := domain.CertificateVersion{ID: "version", LineageID: lineage.ID, SerialNumber: "01", FingerprintSHA256: "abc", Issuer: "Test CA", Identifiers: lineage.Identifiers, NotBefore: now.Add(-60 * 24 * time.Hour), NotAfter: now.Add(30 * 24 * time.Hour), CertificatePath: "/tmp/cert.pem", ChainPath: "/tmp/chain.pem", PrivateKeyRef: "key", RenewalWindowStart: &due, CreatedAt: now}
|
||||
if err := r.SaveCertificateVersion(ctx, version); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
revokedAt := now.Add(-2 * time.Hour)
|
||||
pendingAt := now.Add(-3 * time.Hour)
|
||||
reason := uint(1)
|
||||
revokedVersion := version
|
||||
revokedVersion.ID, revokedVersion.SerialNumber = "revoked-version", "02"
|
||||
revokedVersion.RevocationPendingAt, revokedVersion.RevokedAt, revokedVersion.RevocationReason = &pendingAt, &revokedAt, &reason
|
||||
if err := r.SaveCertificateVersion(ctx, revokedVersion); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
versions, err := r.ListCertificateVersions(ctx, lineage.ID)
|
||||
if err != nil || len(versions) != 2 || versions[0].RevocationPendingAt == nil || versions[0].RevokedAt == nil || versions[0].RevocationReason == nil || *versions[0].RevocationReason != reason {
|
||||
t.Fatalf("revocation round trip = %#v, %v", versions, err)
|
||||
}
|
||||
lineage.CurrentVersionID = version.ID
|
||||
if err := r.SaveCertificateLineage(ctx, lineage); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
endpoint := domain.ObservedEndpoint{ID: "endpoint", ZoneID: zone.ID, Host: "example.com", Port: 443, Enabled: true, FingerprintSHA256: "def", LastCheckedAt: &now}
|
||||
if err := r.SaveEndpoint(ctx, endpoint); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
issue := domain.HealthIssue{ID: "issue", Severity: domain.SeverityWarning, Kind: "stale", ResourceID: endpoint.ID, Title: "Certificate differs", Detail: "Observed fingerprint differs", ObservedAt: now}
|
||||
if err := r.SaveHealthIssues(ctx, endpoint.ID, []domain.HealthIssue{issue}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job := domain.Job{ID: "job", Kind: "certificate.issue", State: domain.JobRunning, Progress: 50, Message: "Waiting", Payload: json.RawMessage(`{"safe":true}`), CreatedAt: now, StartedAt: &now, UpdatedAt: now}
|
||||
if err := r.SaveJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
challenge := domain.ChallengeJournal{ID: "challenge", JobID: job.ID, CredentialID: credential.ID, ZoneID: zone.ID, RecordID: "txt", FQDN: "_acme-challenge.example.com", ValueHash: "hash", CreatedAt: now}
|
||||
if err := r.SaveChallenge(ctx, challenge); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.AppendAudit(ctx, domain.AuditEvent{ID: "audit", Actor: "test", Action: "dns.patch", ResourceID: "record", Before: json.RawMessage(`{"a":1}`), After: json.RawMessage(`{"a":2}`), CreatedAt: now}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
snapshot, err := r.Dashboard(ctx, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.Accounts != 1 || snapshot.Zones != 1 || snapshot.Certificates != 1 || snapshot.CertificatesDue != 1 || snapshot.ActiveJobs != 1 || len(snapshot.Issues) != 1 {
|
||||
t.Fatalf("dashboard = %#v", snapshot)
|
||||
}
|
||||
recoverable, err := r.ListRecoverableJobs(ctx)
|
||||
if err != nil || len(recoverable) != 1 {
|
||||
t.Fatalf("recoverable = %#v, %v", recoverable, err)
|
||||
}
|
||||
open, err := r.ListOpenChallenges(ctx)
|
||||
if err != nil || len(open) != 1 || open[0].CredentialID != credential.ID {
|
||||
t.Fatalf("open challenges = %#v, %v", open, err)
|
||||
}
|
||||
if err := r.MarkChallengeCleaned(ctx, challenge.ID, now.Add(time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
open, err = r.ListOpenChallenges(ctx)
|
||||
if err != nil || len(open) != 0 {
|
||||
t.Fatalf("cleaned challenges = %#v, %v", open, err)
|
||||
}
|
||||
audit, err := r.ListAudit(ctx, 10)
|
||||
if err != nil || len(audit) != 1 || string(audit[0].Before) != `{"a":1}` {
|
||||
t.Fatalf("audit = %#v, %v", audit, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcileInterruptedJobsMarksOnlyActiveStatesFailed(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repository := openTestRepository(t)
|
||||
started := time.Date(2026, 7, 12, 10, 0, 0, 0, time.UTC)
|
||||
states := []domain.JobState{
|
||||
domain.JobQueued,
|
||||
domain.JobRunning,
|
||||
domain.JobWaitingForDNS,
|
||||
domain.JobSucceeded,
|
||||
domain.JobFailed,
|
||||
}
|
||||
for _, state := range states {
|
||||
job := domain.Job{ID: "job-" + string(state), Kind: "test", State: state, Message: string(state), CreatedAt: started, UpdatedAt: started}
|
||||
if state == domain.JobFailed {
|
||||
retry := started.Add(time.Hour)
|
||||
job.RetryAt = &retry
|
||||
}
|
||||
if err := repository.SaveJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
finished := started.Add(5 * time.Minute)
|
||||
count, err := repository.ReconcileInterruptedJobs(ctx, finished)
|
||||
if err != nil || count != 3 {
|
||||
t.Fatalf("reconciled count = %d, %v; want 3", count, err)
|
||||
}
|
||||
for _, state := range states {
|
||||
job, err := repository.GetJob(ctx, "job-"+string(state))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch state {
|
||||
case domain.JobQueued, domain.JobRunning, domain.JobWaitingForDNS:
|
||||
if job.State != domain.JobFailed || job.FinishedAt == nil || !job.FinishedAt.Equal(finished) || job.RetryAt != nil || !strings.Contains(job.Error, "interrupted") {
|
||||
t.Fatalf("active %s job after reconcile = %#v", state, job)
|
||||
}
|
||||
default:
|
||||
if job.State != state {
|
||||
t.Fatalf("terminal %s job changed to %s", state, job.State)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveEndpointReusesUniqueHostPortAcrossZoneReassignment(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repository := openTestRepository(t)
|
||||
now := time.Date(2026, 7, 12, 11, 0, 0, 0, time.UTC)
|
||||
credential := domain.Credential{ID: "cred-endpoint", Provider: domain.ProviderCloudflare, Label: "CF", Kind: domain.CredentialUserToken, SecretRef: "secret", Status: domain.CredentialValid, CreatedAt: now}
|
||||
if err := repository.SaveCredential(ctx, credential); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
account := domain.RemoteAccount{ID: "account-endpoint", Provider: domain.ProviderCloudflare, ProviderID: "account-endpoint", Name: "Endpoints", CreatedAt: now}
|
||||
if err := repository.SaveAccounts(ctx, []domain.RemoteAccount{account}, []domain.AccountCredential{{AccountID: account.ID, CredentialID: credential.ID}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zones := []domain.Zone{
|
||||
{ID: "zone-old", Provider: domain.ProviderCloudflare, ProviderID: "zone-old", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "example.com", Status: domain.ZoneUnknown},
|
||||
{ID: "zone-new", Provider: domain.ProviderCloudflare, ProviderID: "zone-new", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "www.example.com", Status: domain.ZoneActive},
|
||||
}
|
||||
if err := repository.SaveZones(ctx, zones); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := domain.ObservedEndpoint{ID: "endpoint-old", ZoneID: zones[0].ID, Host: "www.example.com", Port: 443, Enabled: true, FingerprintSHA256: "old"}
|
||||
if err := repository.SaveEndpoint(ctx, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reassigned := domain.ObservedEndpoint{ID: "endpoint-new", ZoneID: zones[1].ID, Host: "www.example.com", Port: 443, Enabled: true, FingerprintSHA256: "new"}
|
||||
if err := repository.SaveEndpoint(ctx, reassigned); err != nil {
|
||||
t.Fatalf("host/port reassignment conflicted: %v", err)
|
||||
}
|
||||
endpoints, err := repository.ListEndpoints(ctx)
|
||||
if err != nil || len(endpoints) != 1 {
|
||||
t.Fatalf("reassigned endpoints = %#v, %v", endpoints, err)
|
||||
}
|
||||
if endpoints[0].ID != old.ID || endpoints[0].ZoneID != zones[1].ID || endpoints[0].FingerprintSHA256 != "new" {
|
||||
t.Fatalf("retained endpoint after reassignment = %#v", endpoints[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestEndpointHostPortMigrationDeduplicatesLegacyDatabase(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repository, err := New(filepath.Join(t.TempDir(), "legacy.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer repository.Close()
|
||||
initial, err := migrationFiles.ReadFile("migrations/001_initial.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacy := strings.Replace(string(initial), " last_error TEXT NOT NULL DEFAULT '',\n UNIQUE(host, port)\n", " last_error TEXT NOT NULL DEFAULT ''\n", 1)
|
||||
if legacy == string(initial) {
|
||||
t.Fatal("legacy schema fixture did not remove endpoint uniqueness")
|
||||
}
|
||||
if _, err := repository.db.ExecContext(ctx, legacy); err != nil {
|
||||
t.Fatalf("create legacy initial schema: %v", err)
|
||||
}
|
||||
if _, err := repository.db.ExecContext(ctx, `CREATE TABLE schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TEXT NOT NULL
|
||||
)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyMigrations := []string{
|
||||
"001_initial.sql",
|
||||
"002_challenge_credential.sql",
|
||||
"003_certificate_revocation.sql",
|
||||
"004_revocation_intent.sql",
|
||||
"005_zone_capabilities.sql",
|
||||
"006_certificate_commit_journal.sql",
|
||||
"007_acme_account_commit_journal.sql",
|
||||
}
|
||||
for _, name := range legacyMigrations {
|
||||
if name != "001_initial.sql" {
|
||||
body, readErr := migrationFiles.ReadFile("migrations/" + name)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if _, execErr := repository.db.ExecContext(ctx, string(body)); execErr != nil {
|
||||
t.Fatalf("apply legacy migration %s: %v", name, execErr)
|
||||
}
|
||||
}
|
||||
if _, err := repository.db.ExecContext(ctx, "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", name, encodeTime(time.Now())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
credential := domain.Credential{ID: "legacy-cred", Provider: domain.ProviderCloudflare, Label: "Legacy", Kind: domain.CredentialUserToken, SecretRef: "secret", Status: domain.CredentialValid, CreatedAt: now}
|
||||
if err := repository.SaveCredential(ctx, credential); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
account := domain.RemoteAccount{ID: "legacy-account", Provider: domain.ProviderCloudflare, ProviderID: "legacy-account", Name: "Legacy", CreatedAt: now}
|
||||
if err := repository.SaveAccounts(ctx, []domain.RemoteAccount{account}, []domain.AccountCredential{{AccountID: account.ID, CredentialID: credential.ID}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zones := []domain.Zone{
|
||||
{ID: "legacy-zone-a", Provider: domain.ProviderCloudflare, ProviderID: "legacy-zone-a", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "example.com", Status: domain.ZoneActive},
|
||||
{ID: "legacy-zone-b", Provider: domain.ProviderCloudflare, ProviderID: "legacy-zone-b", AccountID: account.ID, PreferredCredentialID: credential.ID, Name: "www.example.com", Status: domain.ZoneActive},
|
||||
}
|
||||
if err := repository.SaveZones(ctx, zones); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
insertEndpoint := `INSERT INTO endpoints (
|
||||
id, zone_id, host, port, enabled, resolved_addresses_json,
|
||||
fingerprint_sha256, issuer, valid_for_host, trusted, last_error
|
||||
) VALUES (?, ?, 'www.example.com', 443, ?, '[]', '', '', 0, 0, '')`
|
||||
if _, err := repository.db.ExecContext(ctx, insertEndpoint, "legacy-keeper", zones[0].ID, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := repository.db.ExecContext(ctx, insertEndpoint, "legacy-duplicate", zones[1].ID, false); err != nil {
|
||||
t.Fatalf("legacy schema unexpectedly enforced uniqueness: %v", err)
|
||||
}
|
||||
for _, endpointID := range []string{"legacy-keeper", "legacy-duplicate"} {
|
||||
if _, err := repository.db.ExecContext(ctx, `INSERT INTO health_issues (
|
||||
id, owner_id, severity, kind, resource_id, title, detail, action, observed_at
|
||||
) VALUES (?, ?, 'warning', 'legacy', ?, 'Legacy', 'Legacy issue', '', ?)`, "issue-"+endpointID, endpointID, endpointID, encodeTime(now)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := repository.Migrate(ctx); err != nil {
|
||||
t.Fatalf("upgrade legacy endpoint schema: %v", err)
|
||||
}
|
||||
endpoints, err := repository.ListEndpoints(ctx)
|
||||
if err != nil || len(endpoints) != 1 || endpoints[0].ID != "legacy-keeper" {
|
||||
t.Fatalf("deduplicated endpoints = %#v, %v", endpoints, err)
|
||||
}
|
||||
issues, err := repository.ListHealthIssues(ctx)
|
||||
if err != nil || len(issues) != 1 || issues[0].ResourceID != "legacy-keeper" {
|
||||
t.Fatalf("deduplicated health issues = %#v, %v", issues, err)
|
||||
}
|
||||
if _, err := repository.db.ExecContext(ctx, insertEndpoint, "legacy-third", zones[1].ID, true); err == nil {
|
||||
t.Fatal("upgraded schema accepted duplicate host/port")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryFilePermissions(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "private", "domainops.db")
|
||||
r, err := New(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("database mode = %o", info.Mode().Perm())
|
||||
}
|
||||
dir, err := os.Stat(filepath.Dir(path))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dir.Mode().Perm() != 0o700 {
|
||||
t.Fatalf("database directory mode = %o", dir.Mode().Perm())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user