This is an automated email from the ASF dual-hosted git repository. lahirujayathilake pushed a commit to branch ssh-certs in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit e31423c3632ab65bf1623e30fb7226e836167d8f Author: lahiruj <[email protected]> AuthorDate: Thu Nov 12 19:16:10 2026 -0500 Take certificate serials from a Postgres sequence --- .../internal/handler/sign.go | 88 ++--------- .../internal/handler/sign_test.go | 30 +--- .../internal/store/issuance_log.go | 9 ++ .../internal/vault/client.go | 175 +-------------------- .../internal/vault/client_test.go | 59 ------- extensions/SSH-Certificate-Signer/main.go | 4 +- .../migrations/001_initial_schema.up.sql | 3 + 7 files changed, 33 insertions(+), 335 deletions(-) diff --git a/extensions/SSH-Certificate-Signer/internal/handler/sign.go b/extensions/SSH-Certificate-Signer/internal/handler/sign.go index 24c21ed6e..2fa3fd3fc 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/sign.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/sign.go @@ -17,7 +17,6 @@ package handler import ( "encoding/json" - "errors" "log/slog" "net/http" "net/netip" @@ -27,13 +26,12 @@ import ( "time" "unicode" - "github.com/jackc/pgx/v5/pgconn" - "github.com/apache/airavata-custos/signer/internal/audit" "github.com/apache/airavata-custos/signer/internal/cert" "github.com/apache/airavata-custos/signer/internal/httputil" "github.com/apache/airavata-custos/signer/internal/metrics" "github.com/apache/airavata-custos/signer/internal/policy" + "github.com/apache/airavata-custos/signer/internal/store" "github.com/apache/airavata-custos/signer/internal/validation" vaultpkg "github.com/apache/airavata-custos/signer/internal/vault" ) @@ -81,6 +79,7 @@ type SignHandler struct { policyEnforcer *policy.Enforcer principalValidator *validation.ValidatorDispatcher vaultClient *vaultpkg.Client + db *store.DB auditLogger *audit.Logger settings SignSettings logger *slog.Logger @@ -90,6 +89,7 @@ func NewSignHandler( policyEnforcer *policy.Enforcer, principalValidator *validation.ValidatorDispatcher, vaultClient *vaultpkg.Client, + db *store.DB, auditLogger *audit.Logger, settings SignSettings, logger *slog.Logger, @@ -98,6 +98,7 @@ func NewSignHandler( policyEnforcer: policyEnforcer, principalValidator: principalValidator, vaultClient: vaultClient, + db: db, auditLogger: auditLogger, settings: settings, logger: logger, @@ -106,8 +107,7 @@ func NewSignHandler( func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { startTime := time.Now() - // Per-component timing for the response. Accumulating lets the - // duplicate-serial retry path add into the same stages. + // Per-component timing for the response. timings := map[string]int64{} stageStart := startTime mark := func(stage string) { @@ -210,21 +210,14 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { metrics.VaultOperationsTotal.WithLabelValues("get_ca_key", "success").Inc() mark("vault_key_fetch_us") - serial, err := h.vaultClient.IncrementSerialCounter(r.Context()) + serial, err := h.db.NextSerial(r.Context()) if err != nil { metrics.SignRequestsTotal.WithLabelValues("error").Inc() - metrics.VaultOperationsTotal.WithLabelValues("increment_serial", "error").Inc() - if errors.Is(err, vaultpkg.ErrSerialConflict) { - h.logger.Warn("serial counter conflict", "error", err) - writeError(w, http.StatusConflict, "serial_conflict", "Serial number allocation conflict, retry the request") - return - } - h.logger.Error("failed to increment serial counter", "error", err) + h.logger.Error("failed to allocate serial number", "error", err) writeError(w, http.StatusInternalServerError, "internal_error", "Failed to allocate serial number") return } - metrics.VaultOperationsTotal.WithLabelValues("increment_serial", "success").Inc() - mark("vault_serial_us") + mark("serial_us") criticalOpts := map[string]string{} if req.ForceCommand != "" { @@ -274,60 +267,13 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { SourceAddress: stringPtrIfNonEmpty(req.SourceAddress), } - auditErr := h.auditLogger.LogIssuance(r.Context(), auditEntry) - mark("audit_log_us") - if err := auditErr; err != nil { - if !isDuplicateKeyError(err) { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() - h.logger.Error("failed to write audit log", "error", err) - writeError(w, http.StatusInternalServerError, "internal_error", "Failed to record issuance") - return - } - - // Duplicate serial — retry with a fresh serial - h.logger.Warn("duplicate serial detected, retrying with fresh serial", "serial", serial) - - retrySerial, err := h.vaultClient.IncrementSerialCounter(r.Context()) - if err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() - metrics.VaultOperationsTotal.WithLabelValues("increment_serial", "error").Inc() - if errors.Is(err, vaultpkg.ErrSerialConflict) { - h.logger.Warn("serial counter conflict", "error", err) - writeError(w, http.StatusConflict, "serial_conflict", "Serial number allocation conflict, retry the request") - return - } - writeError(w, http.StatusInternalServerError, "internal_error", "Failed to allocate serial number") - return - } - metrics.VaultOperationsTotal.WithLabelValues("increment_serial", "success").Inc() - mark("vault_serial_us") - - signReq.Serial = uint64(retrySerial) - retryResult, err := cert.SignCertificate(signReq) - if err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() - h.logger.Error("failed to sign certificate on retry", "error", err) - writeError(w, http.StatusInternalServerError, "internal_error", "Failed to sign certificate") - return - } - mark("cert_signing_us") - - serial = retrySerial - signResult = retryResult - auditEntry.SerialNumber = retrySerial - auditEntry.KeyID = retryResult.KeyID - auditEntry.CAFingerprint = retryResult.CAFingerprint - auditEntry.ValidAfter = time.Unix(int64(retryResult.ValidAfter), 0).UTC() - auditEntry.ValidBefore = time.Unix(int64(retryResult.ValidBefore), 0).UTC() - - if err := h.auditLogger.LogIssuance(r.Context(), auditEntry); err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() - h.logger.Error("failed to write audit log on retry", "error", err) - writeError(w, http.StatusInternalServerError, "internal_error", "Failed to record issuance") - return - } - mark("audit_log_us") + if err := h.auditLogger.LogIssuance(r.Context(), auditEntry); err != nil { + metrics.SignRequestsTotal.WithLabelValues("error").Inc() + h.logger.Error("failed to write audit log", "error", err) + writeError(w, http.StatusInternalServerError, "internal_error", "Failed to record issuance") + return } + mark("audit_log_us") metrics.SignRequestsTotal.WithLabelValues("success").Inc() timings["total_us"] = time.Since(startTime).Microseconds() @@ -377,12 +323,6 @@ func validSourceAddress(list string) bool { return true } -// isDuplicateKeyError detects a unique-constraint violation (SQLSTATE 23505). -func isDuplicateKeyError(err error) bool { - var pgErr *pgconn.PgError - return errors.As(err, &pgErr) && pgErr.Code == "23505" -} - func stringPtrIfNonEmpty(s string) *string { if s == "" { return nil diff --git a/extensions/SSH-Certificate-Signer/internal/handler/sign_test.go b/extensions/SSH-Certificate-Signer/internal/handler/sign_test.go index 1da6d21f3..81e1f24bc 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/sign_test.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/sign_test.go @@ -17,20 +17,16 @@ package handler import ( "encoding/json" - "errors" - "fmt" "log/slog" "net/http" "net/http/httptest" "strings" "testing" - - "github.com/jackc/pgx/v5/pgconn" ) func signError(t *testing.T, body string) (int, string) { t.Helper() - h := NewSignHandler(nil, nil, nil, nil, SignSettings{ReservedUsernames: []string{"root"}}, slog.Default()) + h := NewSignHandler(nil, nil, nil, nil, nil, SignSettings{ReservedUsernames: []string{"root"}}, slog.Default()) rec := httptest.NewRecorder() h.Handle(rec, httptest.NewRequest(http.MethodPost, "/api/v1/sign", strings.NewReader(body))) var got struct { @@ -121,27 +117,3 @@ func TestPrincipalRegex(t *testing.T) { }) } } - -func TestIsDuplicateKeyError(t *testing.T) { - tests := []struct { - name string - err error - want bool - }{ - {"nil error", nil, false}, - {"generic error", errors.New("connection refused"), false}, - {"unique violation", &pgconn.PgError{Code: "23505", Message: "duplicate key value violates unique constraint \"serial_number\""}, true}, - {"wrapped unique violation", fmt.Errorf("failed to insert: %w", &pgconn.PgError{Code: "23505"}), true}, - {"other pg error", &pgconn.PgError{Code: "23503", Message: "foreign key violation"}, false}, - {"plain message no match", errors.New("duplicate key value violates unique constraint"), false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := isDuplicateKeyError(tt.err) - if got != tt.want { - t.Errorf("isDuplicateKeyError(%v) = %v, want %v", tt.err, got, tt.want) - } - }) - } -} diff --git a/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go b/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go index 6da122c22..7bc1844b1 100644 --- a/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go +++ b/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go @@ -38,6 +38,15 @@ type IssuanceLog struct { SourceAddress *string } +// NextSerial returns a new certificate serial. A serial is never handed out twice, even when signing fails. +func (d *DB) NextSerial(ctx context.Context) (int64, error) { + var serial int64 + if err := d.QueryRowContext(ctx, `SELECT nextval('certificate_serial_seq')`).Scan(&serial); err != nil { + return 0, fmt.Errorf("allocating serial: %w", err) + } + return serial, nil +} + // InsertIssuanceLog writes a certificate issuance entry. Fails on duplicate serial_number. func (d *DB) InsertIssuanceLog(ctx context.Context, log *IssuanceLog) error { grantedExtensions := log.GrantedExtensions diff --git a/extensions/SSH-Certificate-Signer/internal/vault/client.go b/extensions/SSH-Certificate-Signer/internal/vault/client.go index 085ae6f55..2cc32b8b7 100644 --- a/extensions/SSH-Certificate-Signer/internal/vault/client.go +++ b/extensions/SSH-Certificate-Signer/internal/vault/client.go @@ -24,9 +24,6 @@ import ( "encoding/pem" "errors" "fmt" - "path" - "strconv" - "strings" "time" vaultapi "github.com/openbao/openbao/api/v2" @@ -35,47 +32,21 @@ import ( "github.com/apache/airavata-custos/signer/internal/config" ) -// ErrSerialConflict marks a lost CAS race on the serial counter, not a store failure. -var ErrSerialConflict = errors.New("serial counter conflict") - var ErrCANotFound = errors.New("no CA key in vault") -func isCASMismatch(err error) bool { - var respErr *vaultapi.ResponseError - if !errors.As(err, &respErr) { - return false - } - for _, msg := range respErr.Errors { - if strings.Contains(msg, "check-and-set parameter did not match") { - return true - } - } - return false -} - type CAKeyPair struct { PrivateKey []byte // OpenSSH private key PublicKey []byte // OpenSSH public key line, as in authorized_keys CreatedAt string // RFC 3339, empty when the stored CA has none } -type CAMetadata struct { - SerialCounter int64 - LastRotationAt string - NextRotationAt string - RotationPeriodH int - OverlapHours int -} - type Client struct { - client *vaultapi.Client - mountPath string - caKeyPath string - caMetadataPath string - rotationCfg config.RotationConfig + client *vaultapi.Client + mountPath string + caKeyPath string } -func NewClient(cfg config.VaultConfig, rotationCfg config.RotationConfig) (*Client, error) { +func NewClient(cfg config.VaultConfig) (*Client, error) { vaultCfg := vaultapi.DefaultConfig() vaultCfg.Address = cfg.Address vaultCfg.Timeout = time.Duration(cfg.TimeoutSeconds) * time.Second @@ -90,9 +61,6 @@ func NewClient(cfg config.VaultConfig, rotationCfg config.RotationConfig) (*Clie client: client, mountPath: cfg.MountPath, caKeyPath: cfg.CAKeyPath, - // The serial counter and rotation settings stay next to the CA key. - caMetadataPath: path.Join(path.Dir(cfg.CAKeyPath), "metadata"), - rotationCfg: rotationCfg, }, nil } @@ -151,144 +119,9 @@ func (c *Client) GenerateCAKey(ctx context.Context) (*CAKeyPair, error) { if _, err := c.client.Logical().WriteWithContext(ctx, kvPath, data); err != nil { return nil, fmt.Errorf("writing vault path %s: %w", kvPath, err) } - - if err := c.initMetadata(ctx); err != nil { - return nil, err - } - return kp, nil } -// IncrementSerialCounter atomically reads, increments, and writes the serial -// counter using Vault KV v2 CAS (Check-and-Set) to prevent lost updates. -func (c *Client) IncrementSerialCounter(ctx context.Context) (int64, error) { - meta, version, err := c.readMetadataWithVersion(ctx) - if err != nil { - return 0, err - } - if meta == nil { - if err := c.initMetadata(ctx); err != nil { - return 0, err - } - return 1, nil - } - - newSerial := meta.SerialCounter + 1 - meta.SerialCounter = newSerial - if err := c.writeMetadataCAS(ctx, meta, version); err != nil { - return 0, err - } - return newSerial, nil -} - -func (c *Client) readMetadataWithVersion(ctx context.Context) (*CAMetadata, int, error) { - path := c.kvPath(c.caMetadataPath) - secret, err := c.client.Logical().ReadWithContext(ctx, path) - if err != nil { - return nil, 0, fmt.Errorf("reading vault metadata: %w", err) - } - if secret == nil || secret.Data == nil { - return nil, 0, nil - } - - // Extract KV v2 version from metadata. - // The Vault Go client decodes numbers as json.Number, not float64. - version := 0 - if md, ok := secret.Data["metadata"].(map[string]interface{}); ok { - if v, ok := md["version"].(json.Number); ok { - if n, err := v.Int64(); err == nil { - version = int(n) - } - } - } - - data, ok := secret.Data["data"].(map[string]interface{}) - if !ok || data == nil { - return nil, 0, nil - } - - meta := &CAMetadata{} - if v, ok := data["serial_counter"].(string); ok { - meta.SerialCounter, _ = strconv.ParseInt(v, 10, 64) - } - if v, ok := data["serial_counter"].(float64); ok { - meta.SerialCounter = int64(v) - } - if v, ok := data["last_rotation_at"].(string); ok { - meta.LastRotationAt = v - } - if v, ok := data["next_rotation_at"].(string); ok { - meta.NextRotationAt = v - } - if v, ok := data["rotation_period_hours"].(string); ok { - meta.RotationPeriodH, _ = strconv.Atoi(v) - } - if v, ok := data["rotation_period_hours"].(float64); ok { - meta.RotationPeriodH = int(v) - } - if v, ok := data["overlap_hours"].(string); ok { - meta.OverlapHours, _ = strconv.Atoi(v) - } - if v, ok := data["overlap_hours"].(float64); ok { - meta.OverlapHours = int(v) - } - return meta, version, nil -} - -func (c *Client) writeMetadata(ctx context.Context, meta *CAMetadata) error { - kvPath := c.kvPath(c.caMetadataPath) - data := map[string]interface{}{ - "data": map[string]interface{}{ - "serial_counter": strconv.FormatInt(meta.SerialCounter, 10), - "last_rotation_at": meta.LastRotationAt, - "next_rotation_at": meta.NextRotationAt, - "rotation_period_hours": strconv.Itoa(meta.RotationPeriodH), - "overlap_hours": strconv.Itoa(meta.OverlapHours), - }, - } - _, err := c.client.Logical().WriteWithContext(ctx, kvPath, data) - if err != nil { - return fmt.Errorf("writing vault metadata: %w", err) - } - return nil -} - -func (c *Client) writeMetadataCAS(ctx context.Context, meta *CAMetadata, cas int) error { - kvPath := c.kvPath(c.caMetadataPath) - data := map[string]any{ - "options": map[string]any{ - "cas": cas, - }, - "data": map[string]any{ - "serial_counter": strconv.FormatInt(meta.SerialCounter, 10), - "last_rotation_at": meta.LastRotationAt, - "next_rotation_at": meta.NextRotationAt, - "rotation_period_hours": strconv.Itoa(meta.RotationPeriodH), - "overlap_hours": strconv.Itoa(meta.OverlapHours), - }, - } - _, err := c.client.Logical().WriteWithContext(ctx, kvPath, data) - if err != nil { - if isCASMismatch(err) { - return fmt.Errorf("%w (CAS=%d): %v", ErrSerialConflict, cas, err) - } - return fmt.Errorf("writing vault metadata (CAS=%d): %w", cas, err) - } - return nil -} - -func (c *Client) initMetadata(ctx context.Context) error { - now := time.Now().UTC() - meta := &CAMetadata{ - SerialCounter: 0, - LastRotationAt: now.Format(time.RFC3339), - NextRotationAt: now.Add(time.Duration(c.rotationCfg.PeriodHours) * time.Hour).Format(time.RFC3339), - RotationPeriodH: c.rotationCfg.PeriodHours, - OverlapHours: c.rotationCfg.OverlapHours, - } - return c.writeMetadata(ctx, meta) -} - func generateEd25519CAKey() (*CAKeyPair, error) { pub, priv, err := ed25519.GenerateKey(rand.Reader) if err != nil { diff --git a/extensions/SSH-Certificate-Signer/internal/vault/client_test.go b/extensions/SSH-Certificate-Signer/internal/vault/client_test.go deleted file mode 100644 index 769eedb00..000000000 --- a/extensions/SSH-Certificate-Signer/internal/vault/client_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package vault - -import ( - "errors" - "fmt" - "testing" - - vaultapi "github.com/openbao/openbao/api/v2" -) - -func TestIsCASMismatch(t *testing.T) { - casErr := &vaultapi.ResponseError{ - StatusCode: 400, - Errors: []string{"check-and-set parameter did not match the current version"}, - } - if !isCASMismatch(casErr) { - t.Error("CAS mismatch response not detected") - } - if !isCASMismatch(fmt.Errorf("wrapped: %w", casErr)) { - t.Error("wrapped CAS mismatch response not detected") - } - - for _, msg := range []string{ - "permission denied", - "check-and-set parameter required for this call", - "error parsing check-and-set parameter", - } { - other := &vaultapi.ResponseError{StatusCode: 400, Errors: []string{msg}} - if isCASMismatch(other) { - t.Errorf("misclassified as conflict: %q", msg) - } - } - if isCASMismatch(errors.New("connection refused")) { - t.Error("plain error misclassified as conflict") - } -} - -func TestSerialConflictWrapping(t *testing.T) { - // same shape writeMetadataCAS produces - err := fmt.Errorf("%w (CAS=7): %v", ErrSerialConflict, errors.New("underlying")) - if !errors.Is(err, ErrSerialConflict) { - t.Error("wrapped conflict not matched by errors.Is") - } -} diff --git a/extensions/SSH-Certificate-Signer/main.go b/extensions/SSH-Certificate-Signer/main.go index d5951d69c..09c6f29e4 100644 --- a/extensions/SSH-Certificate-Signer/main.go +++ b/extensions/SSH-Certificate-Signer/main.go @@ -143,7 +143,7 @@ func runServer(cfg *config.Config, logger *slog.Logger, autoMigrate bool) { runMigrate(cfg, logger) } - vaultClient, err := vault.NewClient(cfg.Vault, cfg.Signer.CA.Rotation) + vaultClient, err := vault.NewClient(cfg.Vault) if err != nil { logger.Error("failed to create vault client", "error", err) os.Exit(1) @@ -171,7 +171,7 @@ func runServer(cfg *config.Config, logger *slog.Logger, autoMigrate bool) { "source", cfg.Signer.Validation.PrincipalValidator, "cache_ttl_seconds", cfg.Signer.Validation.CacheTTLSeconds) - signHandler := handler.NewSignHandler(policyEnforcer, principalValidator, vaultClient, auditLogger, handler.SignSettings{ + signHandler := handler.NewSignHandler(policyEnforcer, principalValidator, vaultClient, db, auditLogger, handler.SignSettings{ ReservedUsernames: cfg.Signer.ReservedUsernames, DeniedExtensions: cfg.Signer.Policy.DeniedExtensions, LoginHost: cfg.Signer.LoginHost, diff --git a/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql b/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql index 1d19b8a90..575fd1a3e 100644 --- a/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql +++ b/extensions/SSH-Certificate-Signer/migrations/001_initial_schema.up.sql @@ -45,6 +45,9 @@ CREATE INDEX IF NOT EXISTS idx_issuance_ca_fingerprint ON certificate_issuance_l CREATE INDEX IF NOT EXISTS idx_issuance_issued_at ON certificate_issuance_logs (issued_at); CREATE INDEX IF NOT EXISTS idx_issuance_valid_range ON certificate_issuance_logs (valid_after, valid_before); +-- Certificate serials. A serial is never handed out twice. +CREATE SEQUENCE IF NOT EXISTS certificate_serial_seq; + CREATE TABLE IF NOT EXISTS revocation_events ( id BIGINT GENERATED BY DEFAULT AS IDENTITY,
