This is an automated email from the ASF dual-hosted git repository. yasithdev pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit fe3fffdc939102e04c7385d54f9bbf6abed7d827 Author: Lahiru Jayathilake <[email protected]> AuthorDate: Fri Nov 13 18:51:06 2026 -0500 Read the signer CA from OpenBao and take serials from Postgres (#744) * Load the CA at startup and create it only when allowed * Use only ed25519 CA keys in OpenSSH format * Read the CA from a configurable path * Ensure the stored CA public key matches the private key * Take certificate serials from a Postgres sequence * Remove the unused CA rotation settings * Remove per-stage timing from sign responses * Replace signer metrics with log lines for refused requests * Record certificate issue and revoke in the Custos audit log * Updated the readme * Prevent replacing an existing CA in Vault * Log CA creation only once its fingerprint is known --- connectors/Signer/internal/handlers.go | 48 +++- connectors/Signer/internal/handlers_test.go | 34 +++ dev-ops/compose/prometheus/prometheus.yml | 7 - dev-ops/compose/signer/config.yaml | 8 +- extensions/SSH-Certificate-Signer/README.md | 72 +++-- .../SSH-Certificate-Signer/config.example.yaml | 9 +- extensions/SSH-Certificate-Signer/go.mod | 9 - extensions/SSH-Certificate-Signer/go.sum | 24 -- .../internal/audit/logger.go | 8 + .../internal/cert/rsa_ecdsa_signing_test.go | 172 ------------ .../SSH-Certificate-Signer/internal/cert/signer.go | 2 +- .../internal/cert/signer_test.go | 41 ++- .../internal/cert/ssh_key.go | 124 +++------ .../internal/cert/ssh_key_test.go | 158 +++-------- .../internal/config/config.go | 25 +- .../internal/handler/ca_public_key.go | 16 +- .../internal/handler/sign.go | 160 +++-------- .../internal/handler/sign_test.go | 30 +-- .../internal/metrics/metrics.go | 45 ---- .../internal/server/middleware.go | 4 +- .../internal/server/routes.go | 6 - .../internal/store/issuance_log.go | 9 + .../internal/vault/client.go | 293 ++++----------------- .../internal/vault/client_test.go | 59 ----- extensions/SSH-Certificate-Signer/main.go | 39 ++- .../migrations/001_initial_schema.up.sql | 3 + 26 files changed, 395 insertions(+), 1010 deletions(-) diff --git a/connectors/Signer/internal/handlers.go b/connectors/Signer/internal/handlers.go index 3b7dfa95e..3932bc095 100644 --- a/connectors/Signer/internal/handlers.go +++ b/connectors/Signer/internal/handlers.go @@ -27,6 +27,7 @@ import ( "log/slog" "net/http" "net/url" + "strconv" "strings" "time" @@ -39,16 +40,22 @@ import ( const Type = "signer" +const ( + AuditCertificateIssued = "SSH_CERTIFICATE_ISSUED" + AuditCertificateRevoked = "SSH_CERTIFICATE_REVOKED" +) + const maxRequestBytes = 16 << 10 var errServiceTokenRefused = errors.New("signer refused the service token") -// CoreAccounts is what the connector reads from core to decide who can generate. +// CoreAccounts is what the connector needs from core, who can generate, and the audit log. type CoreAccounts interface { GetComputeClusterUserByPair(ctx context.Context, clusterID, userID string) (*models.ComputeClusterUser, error) ListAllocationsForUser(ctx context.Context, userID string) ([]models.ComputeAllocationMembership, error) GetComputeAllocation(ctx context.Context, id string) (*models.ComputeAllocation, error) GetUser(ctx context.Context, id string) (*models.User, error) + CreateAuditEvent(ctx context.Context, e *models.AuditEvent) (*models.AuditEvent, error) } type Config struct { @@ -151,6 +158,39 @@ func (h *Handlers) relay(w http.ResponseWriter, r *http.Request, method, path st copyResponse(w, resp) } +// relayAndAudit relays the call and records eventType in the audit log once the signer has done it. +func (h *Handlers) relayAndAudit(w http.ResponseWriter, r *http.Request, path string, body any, eventType string, details map[string]any) { + resp, err := h.callSigner(r.Context(), http.MethodPost, path, body) + if err != nil { + signerUnavailable(w) + return + } + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + signerUnavailable(w) + return + } + if resp.StatusCode == http.StatusOK { + // The certificate is already issued or revoked by now, so a failed write is only logged, and the caller still gets the result. + var result struct { + SerialNumber int64 `json:"serial_number"` + } + err := json.Unmarshal(respBody, &result) + if err == nil { + payload, _ := json.Marshal(details) + _, err = h.core.CreateAuditEvent(r.Context(), &models.AuditEvent{EventType: eventType, EntityType: "ssh_certificate", + EntityID: strconv.FormatInt(result.SerialNumber, 10), Source: Type, Details: string(payload)}) + } + if err != nil { + slog.Error("signer: writing the audit event failed", "event_type", eventType, "error", err) + } + } + w.Header().Set("Content-Type", resp.Header.Get("Content-Type")) + w.WriteHeader(resp.StatusCode) + w.Write(respBody) +} + func (h *Handlers) listAllCertificates(w http.ResponseWriter, r *http.Request) { h.relay(w, r, http.MethodGet, "/api/v1/certificates?"+r.URL.RawQuery, nil) } @@ -168,7 +208,8 @@ func (h *Handlers) revoke(w http.ResponseWriter, r *http.Request) { return } revokedBy := identity.CallerFromContext(r.Context()).Requester() - h.relay(w, r, http.MethodPost, certificatePath(r)+"/revoke", map[string]string{"reason": req.Reason, "revoked_by": revokedBy}) + h.relayAndAudit(w, r, certificatePath(r)+"/revoke", map[string]string{"reason": req.Reason, "revoked_by": revokedBy}, + AuditCertificateRevoked, map[string]any{"revoked_by": revokedBy, "reason": req.Reason}) } func (h *Handlers) listOwnCertificates(w http.ResponseWriter, r *http.Request) { @@ -268,12 +309,13 @@ func (h *Handlers) issueCertificate(w http.ResponseWriter, r *http.Request, user return } if code != "" { + slog.Info("signer: certificate refused", "code", code, "user_id", userID, "requested_by", sign["requested_by"]) refuse(w, http.StatusForbidden, code, "This account cannot generate a certificate") return } sign["principal"] = username sign["ttl_seconds"] = h.cfg.TTLSeconds - h.relay(w, r, http.MethodPost, "/api/v1/sign", sign) + h.relayAndAudit(w, r, "/api/v1/sign", sign, AuditCertificateIssued, map[string]any{"user_id": userID, "principal": username, "requested_by": sign["requested_by"]}) } // loginName returns the username to sign for. diff --git a/connectors/Signer/internal/handlers_test.go b/connectors/Signer/internal/handlers_test.go index a1c1edcdf..94475d07d 100644 --- a/connectors/Signer/internal/handlers_test.go +++ b/connectors/Signer/internal/handlers_test.go @@ -67,6 +67,12 @@ type fakeCore struct { account *models.ComputeClusterUser memberships []models.ComputeAllocationMembership allocation models.ComputeAllocation + audited []models.AuditEvent +} + +func (f *fakeCore) CreateAuditEvent(_ context.Context, e *models.AuditEvent) (*models.AuditEvent, error) { + f.audited = append(f.audited, *e) + return e, nil } func (f *fakeCore) GetComputeClusterUserByPair(context.Context, string, string) (*models.ComputeClusterUser, error) { @@ -165,6 +171,34 @@ func TestGenerate_SignsForTheCallersOwnAccount(t *testing.T) { } } +// Make sure each issued certificate leaves an audit row under its serial, naming who asked. +func TestGenerate_RecordsTheIssueInTheAuditLog(t *testing.T) { + srv, _ := mockSignerServer(t, http.StatusOK, `{"serial_number":42}`) + core := readyCore() + + serveWith(core, srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates", strings.NewReader(`{"public_key":"k"}`))) + + if len(core.audited) != 1 { + t.Fatalf("audited %d events", len(core.audited)) + } + got := core.audited[0] + if got.EventType != AuditCertificateIssued || got.EntityID != "42" || !strings.Contains(got.Details, `"requested_by":"user/user-1"`) { + t.Fatalf("audited %+v", got) + } +} + +// Make sure no audit row is written when the signer refuses to issue the certificate. +func TestGenerate_SignerRefusalIsNotAudited(t *testing.T) { + srv, _ := mockSignerServer(t, http.StatusForbidden, `{"error":"principal_denied"}`) + core := readyCore() + + rec := serveWith(core, srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates", strings.NewReader(`{"public_key":"k"}`))) + + if rec.Code != http.StatusForbidden || len(core.audited) != 0 { + t.Fatalf("got %d, audited %+v", rec.Code, core.audited) + } +} + // Only with an active account and allocation can generate certificates. func TestGenerate_RefusesWithoutAccountOrAllocation(t *testing.T) { expired := func(core *fakeCore) { core.memberships[0].EndTime = time.Now().Add(-time.Minute) } diff --git a/dev-ops/compose/prometheus/prometheus.yml b/dev-ops/compose/prometheus/prometheus.yml index 7b7c3a80c..dd7f89d6d 100644 --- a/dev-ops/compose/prometheus/prometheus.yml +++ b/dev-ops/compose/prometheus/prometheus.yml @@ -26,10 +26,3 @@ scrape_configs: - targets: ['host.docker.internal:8083'] labels: service: 'access-amie' - - - job_name: 'custos-signer' - metrics_path: '/metrics' - static_configs: - - targets: ['host.docker.internal:8084'] - labels: - service: 'custos-signer' diff --git a/dev-ops/compose/signer/config.yaml b/dev-ops/compose/signer/config.yaml index 2eb982afa..e16acc05c 100644 --- a/dev-ops/compose/signer/config.yaml +++ b/dev-ops/compose/signer/config.yaml @@ -43,9 +43,7 @@ signer: login_host: localhost login_port: 2222 ca: - rotation: - period_hours: 2160 - overlap_hours: 2 + create_if_missing: true policy: max_ttl_seconds: 86400 allowed_key_types: @@ -59,7 +57,3 @@ signer: logging: level: info format: text - -metrics: - enabled: true - path: /metrics diff --git a/extensions/SSH-Certificate-Signer/README.md b/extensions/SSH-Certificate-Signer/README.md index 40dd747ae..1836ea5c9 100644 --- a/extensions/SSH-Certificate-Signer/README.md +++ b/extensions/SSH-Certificate-Signer/README.md @@ -22,7 +22,7 @@ Custos Signer is an SSH certificate authority. It issues short-lived OpenSSH user certificates. The signer is internal and has one trusted caller, the Custos server, through its -[Signer connector](../../connectors/Signer/README.md). Users and apps talk to Custos, and Custos decides who may have a +[Signer connector](../../connectors/Signer/README.md). Users talk to Custos, and Custos decides who may have a certificate. Do not expose the signer to the public. Whoever holds its service token can get a certificate for any user that is not reserved. @@ -53,12 +53,17 @@ The certificate names who it is for. The CA signature covers all of it. | Key ID | `<email>:<requested_by>`. sshd writes it to the login log. | | Extension `[email protected]` | The user's subject | | Extension `[email protected]` | The user's email | -| Extension `[email protected]` | Who asked. Custos sends `user/<id>` or `app/<id>`. | +| Extension `[email protected]` | Who asked. Custos sends `user/<id>`. | A request can also set `source_address`, a comma-separated list of IP addresses or CIDR blocks. It goes in the certificate's `source-address` critical option, and sshd then accepts the certificate only from those addresses. -A deployment has one Ed25519 CA. It is generated in Vault by the first request that reads it. +A deployment has one Ed25519 CA, stored in Vault in OpenSSH format, the same format `ssh-keygen -t ed25519` writes. The +signer reads it at startup and refuses to start without it, unless `signer.ca.create_if_missing` is set, in which case +it creates one and writes a `ca_created` audit log entry. At startup, it also checks that the stored public key matches +the private key. + +Serial numbers come from the PostgreSQL sequence `certificate_serial_seq`, so a serial is never handed out twice. ## Prerequisites @@ -84,33 +89,31 @@ The rest of this section is the manual setup. ### Database ```sql -CREATE -DATABASE custos_signer; +CREATE DATABASE custos_signer; ``` -If using the project's Docker Compose, the `custos_signer` database is created automatically by -`dev-ops/compose/dbinit/init-db.sh`. - -Migrations are managed separately from the server. Migrations are read from `migrations/`, so run the signer from -this directory. Apply them explicitly: +Migrations are read from `migrations/`, so run the signer from this directory: ```bash ./custos-signer migrate --config config.yaml ``` -This applies any pending migrations and exits. It's idempotent — safe to run repeatedly. The `migrate` subcommand tracks -applied versions in a `schema_migrations` table and only applies what's new. +It applies any pending migrations and exits, and is safe to run again. Applied versions are kept in +`schema_migrations`. -You can also apply SQL directly: +The initial migration creates: -```bash -psql -U admin -d custos_signer < migrations/001_initial_schema.up.sql -``` +- `certificate_issuance_logs`, the record of every issued certificate +- `revocation_events`, the record of every revocation +- `certificate_serial_seq`, the sequence serial numbers come from -The initial migration creates two tables: +After restoring the database from a backup, increase the serial counter before starting the signer. The backup +does not have the serials issued after it was taken, so without this the signer would reuse them: -- `certificate_issuance_logs` — audit log for certificate issuances -- `revocation_events` — audit log for certificate revocations +```sql +SELECT setval('certificate_serial_seq', + COALESCE((SELECT MAX(serial_number) FROM certificate_issuance_logs), 0) + 100000); +``` ### Vault @@ -118,11 +121,30 @@ The initial migration creates two tables: vault secrets enable -path=ssh-ca kv-v2 ``` -The path must match `vault.mount_path`. The signer creates CA keys on demand. No manual key setup is required. +The path must match `vault.mount_path`. Store the CA key before starting the signer, or set +`signer.ca.create_if_missing` to let it create one. The CA is one secret at `vault.ca_key_path` (default `ca/current`): + +| Key | Value | +|---------------|--------------------------------------------------------------------------| +| `private_key` | The CA private key, `-----BEGIN OPENSSH PRIVATE KEY-----`. Ed25519 only. | +| `public_key` | The matching public key line, `ssh-ed25519 AAAA...` | +| `created_at` | Optional. When the CA was created, in RFC 3339 (`2026-11-12T10:00:00Z`). | + +```bash +ssh-keygen -t ed25519 -f ca -N "" -C custos-ca +vault kv put ssh-ca/ca/current private_key=@ca [email protected] created_at=$(date -u +%Y-%m-%dT%H:%M:%SZ) +``` + +The signer's token only needs to read. Write is needed only while `create_if_missing` is on: + +```hcl +path "ssh-ca/data/ca/current" { capabilities = ["read"] } +``` -Ensure the configured token has read/write access to `ssh-ca/data/*`. +For a Vault served over TLS with a private CA, set `BAO_CACERT` (or `VAULT_CACERT`) to the CA certificate file. -For `principal_validator: ldap`, store the LDAP settings at `ssh-ca/validation`: +For `principal_validator: ldap`, store the LDAP settings at `ssh-ca/validation`, and give the token read on +`ssh-ca/data/validation` too: | Key | Value | |---------------------------------------------------|-------------------------------------------------| @@ -224,7 +246,6 @@ The service handles SIGTERM and SIGINT for graceful shutdown: | `GET` | `/api/v1/certificates/{serial}` | One certificate | | `POST` | `/api/v1/certificates/{serial}/revoke` | Revoke an active certificate. `revoked_by` is required and `reason` can be empty | | `GET` | `/api/v1/health` | Health check, no token | -| `GET` | `/metrics` | Prometheus metrics when `metrics.enabled`, no token | Every route with a token takes `Authorization: Bearer <service token>`. @@ -266,7 +287,7 @@ curl -s -X POST http://localhost:8084/api/v1/sign \ curl -s -X POST http://localhost:8084/api/v1/certificates/42/revoke \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $SIGNER_SERVICE_TOKEN" \ - -d '{"reason": "User deprovisioned", "revoked_by": "[email protected]"}' | jq . + -d '{"reason": "User deprovisioned", "revoked_by": "user/8f3a"}' | jq . ``` ## Troubleshooting @@ -279,6 +300,9 @@ curl -s -X POST http://localhost:8084/api/v1/certificates/42/revoke \ | HTTP 401 on any route | Wrong service token | Set the same `SIGNER_SERVICE_TOKEN` on the signer and the caller | | HTTP 403 `reserved_username` | The username is in `reserved_usernames` | Certificates are not issued for these names | | HTTP 503 "CA key storage unavailable" | Vault down during signing | Check Vault status and network connectivity | +| Exits with "no CA key in vault" | No CA at `vault.ca_key_path` | Fix the path. A new CA is not trusted by the login nodes | +| Exits with "check-and-set parameter" | The CA's latest version in Vault is deleted | Undelete that version. The signer never replaces an existing CA | +| HTTP 500 on every sign | `certificate_serial_seq` is missing | `CREATE SEQUENCE certificate_serial_seq`, then the `setval` above | ## License diff --git a/extensions/SSH-Certificate-Signer/config.example.yaml b/extensions/SSH-Certificate-Signer/config.example.yaml index 05bd7791b..77bb75fe2 100644 --- a/extensions/SSH-Certificate-Signer/config.example.yaml +++ b/extensions/SSH-Certificate-Signer/config.example.yaml @@ -35,6 +35,7 @@ vault: address: http://localhost:8200 # env: VAULT_ADDRESS token: root-token # env: VAULT_TOKEN mount_path: ssh-ca # KV v2 mount path + ca_key_path: ca/current # secret with private_key, public_key and optional created_at timeout_seconds: 10 signer: @@ -52,9 +53,7 @@ signer: login_host: login.example.org # returned with each certificate login_port: 22 ca: - rotation: - period_hours: 2160 # 90 days - overlap_hours: 2 + create_if_missing: false # true creates a CA when none is stored. policy: max_ttl_seconds: 86400 # 24 hours allowed_key_types: @@ -69,7 +68,3 @@ signer: logging: level: info # debug, info, warn, error format: json # json or text - -metrics: - enabled: true - path: /metrics diff --git a/extensions/SSH-Certificate-Signer/go.mod b/extensions/SSH-Certificate-Signer/go.mod index 52efed5fb..8c96e24d8 100644 --- a/extensions/SSH-Certificate-Signer/go.mod +++ b/extensions/SSH-Certificate-Signer/go.mod @@ -9,16 +9,13 @@ require ( github.com/golang-migrate/migrate/v4 v4.20.1 github.com/jackc/pgx/v5 v5.11.0 github.com/openbao/openbao/api/v2 v2.7.1 - github.com/prometheus/client_golang v1.25.0 golang.org/x/crypto v0.58.0 gopkg.in/yaml.v3 v3.0.1 ) require ( github.com/Azure/go-ntlmssp v0.1.1 // indirect - github.com/beorn7/perks v1.0.1 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect github.com/go-jose/go-jose/v4 v4.1.6 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect @@ -35,13 +32,8 @@ require ( github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect - github.com/klauspost/compress v1.20.3 // indirect github.com/kr/text v0.2.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/prometheus/client_model v0.6.3 // indirect - github.com/prometheus/common v0.72.1 // indirect - github.com/prometheus/procfs v0.22.0 // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/ryanuber/go-glob v1.0.0 // indirect golang.org/x/net v0.61.0 // indirect @@ -49,5 +41,4 @@ require ( golang.org/x/sys v0.49.0 // indirect golang.org/x/text v0.43.0 // indirect golang.org/x/time v0.16.0 // indirect - google.golang.org/protobuf v1.36.12 // indirect ) diff --git a/extensions/SSH-Certificate-Signer/go.sum b/extensions/SSH-Certificate-Signer/go.sum index d758e9702..8bb26f702 100644 --- a/extensions/SSH-Certificate-Signer/go.sum +++ b/extensions/SSH-Certificate-Signer/go.sum @@ -8,8 +8,6 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktpoUAgOJK3OTFc/xug0PCXYCqU0FgDKI= github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= @@ -55,8 +53,6 @@ github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPE github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/golang-migrate/migrate/v4 v4.20.1 h1:2N/ToVTKrKl58ynBpgeVJ4In7VcLCjWTZtm4eP1LxhU= github.com/golang-migrate/migrate/v4 v4.20.1/go.mod h1:DDPgKVb4ovSWc4FwSPfV2Uz1160f4XBiTHTrAJtljmM= -github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= -github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -103,14 +99,10 @@ github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE= -github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= -github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= @@ -129,8 +121,6 @@ github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/openbao/openbao/api/v2 v2.7.1 h1:moqdSJdKr4Bpb5c/qsUY5ZuA/TIQChVigu0qHgo8GXo= github.com/openbao/openbao/api/v2 v2.7.1/go.mod h1:uXbMoyH2pjSvNyTepinUvLde8pOJB82EuhUCfOKnKbo= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= @@ -140,14 +130,6 @@ github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgr github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= -github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= -github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= -github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= -github.com/prometheus/common v0.72.1 h1:ZAiQed/nk8IIcsdzb2TlJu23NEUDyDLQ9TXTN2WRK6Y= -github.com/prometheus/common v0.72.1/go.mod h1:1IoBY4IRaJnhs2ESjNzjilP1cJ/P8pimGoomq7zRXrA= -github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics= -github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= @@ -167,10 +149,6 @@ go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSY go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= -go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= -go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= -go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= @@ -187,8 +165,6 @@ golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= -google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= -google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/extensions/SSH-Certificate-Signer/internal/audit/logger.go b/extensions/SSH-Certificate-Signer/internal/audit/logger.go index b2b64bfe2..763b6d7a7 100644 --- a/extensions/SSH-Certificate-Signer/internal/audit/logger.go +++ b/extensions/SSH-Certificate-Signer/internal/audit/logger.go @@ -94,3 +94,11 @@ func (l *Logger) LogIssuance(ctx context.Context, entry *IssuanceEntry) error { return nil } + +func (l *Logger) LogCACreated(ctx context.Context, caFingerprint string) { + l.slogger.WarnContext(ctx, "CA created", + "event_type", "ca_created", + "timestamp", time.Now().UTC().Format(time.RFC3339), + "ca_fingerprint", caFingerprint, + ) +} diff --git a/extensions/SSH-Certificate-Signer/internal/cert/rsa_ecdsa_signing_test.go b/extensions/SSH-Certificate-Signer/internal/cert/rsa_ecdsa_signing_test.go deleted file mode 100644 index 1c1a6f258..000000000 --- a/extensions/SSH-Certificate-Signer/internal/cert/rsa_ecdsa_signing_test.go +++ /dev/null @@ -1,172 +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 cert - -import ( - "crypto/ecdsa" - "crypto/ed25519" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "testing" - - "golang.org/x/crypto/ssh" -) - -func generateRSACA(t *testing.T) []byte { - t.Helper() - key, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Fatal(err) - } - privBytes, err := x509.MarshalPKCS8PrivateKey(key) - if err != nil { - t.Fatal(err) - } - return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) -} - -func generateECDSACA(t *testing.T) []byte { - t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - privBytes, err := x509.MarshalPKCS8PrivateKey(key) - if err != nil { - t.Fatal(err) - } - return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) -} - -func generateRSAUserKey(t *testing.T) ssh.PublicKey { - t.Helper() - key, _ := rsa.GenerateKey(rand.Reader, 2048) - sshPub, _ := ssh.NewPublicKey(&key.PublicKey) - return sshPub -} - -func generateECDSAUserKey(t *testing.T) ssh.PublicKey { - t.Helper() - key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - sshPub, _ := ssh.NewPublicKey(&key.PublicKey) - return sshPub -} - -func TestSignCertificate_RSAKeyWithRSACA(t *testing.T) { - caPEM := generateRSACA(t) - userKey := generateRSAUserKey(t) - - result, err := SignCertificate(&SignRequest{ - PublicKey: userKey, - CAPrivateKeyPEM: caPEM, - Serial: 10, - Principal: "rsauser", - UserEmail: "[email protected]", - TTLSeconds: 3600, - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - parsedKey, err := ssh.ParsePublicKey(result.CertBytes) - if err != nil { - t.Fatalf("failed to parse cert: %v", err) - } - cert := parsedKey.(*ssh.Certificate) - if cert.Serial != 10 { - t.Errorf("expected serial 10, got %d", cert.Serial) - } -} - -func TestSignCertificate_ECDSAKeyWithECDSACA(t *testing.T) { - caPEM := generateECDSACA(t) - userKey := generateECDSAUserKey(t) - - result, err := SignCertificate(&SignRequest{ - PublicKey: userKey, - CAPrivateKeyPEM: caPEM, - Serial: 20, - Principal: "ecuser", - UserEmail: "[email protected]", - TTLSeconds: 3600, - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - parsedKey, err := ssh.ParsePublicKey(result.CertBytes) - if err != nil { - t.Fatalf("failed to parse cert: %v", err) - } - cert := parsedKey.(*ssh.Certificate) - if cert.Serial != 20 { - t.Errorf("expected serial 20, got %d", cert.Serial) - } -} - -// Sign an Ed25519 user key with an RSA CA -func TestSignCertificate_Ed25519KeyWithRSACA(t *testing.T) { - caPEM := generateRSACA(t) - pub, _, _ := ed25519.GenerateKey(rand.Reader) - sshPub, _ := ssh.NewPublicKey(pub) - - result, err := SignCertificate(&SignRequest{ - PublicKey: sshPub, - CAPrivateKeyPEM: caPEM, - Serial: 30, - Principal: "crossuser", - UserEmail: "[email protected]", - TTLSeconds: 3600, - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - parsedKey, err := ssh.ParsePublicKey(result.CertBytes) - if err != nil { - t.Fatalf("failed to parse cert: %v", err) - } - cert := parsedKey.(*ssh.Certificate) - if cert.Serial != 30 { - t.Errorf("expected serial 30, got %d", cert.Serial) - } -} - -// Sign an Ed25519 user key with ECDSA CA -func TestSignCertificate_Ed25519KeyWithECDSACA(t *testing.T) { - caPEM := generateECDSACA(t) - pub, _, _ := ed25519.GenerateKey(rand.Reader) - sshPub, _ := ssh.NewPublicKey(pub) - - result, err := SignCertificate(&SignRequest{ - PublicKey: sshPub, - CAPrivateKeyPEM: caPEM, - Serial: 40, - Principal: "ecdsacauser", - UserEmail: "[email protected]", - TTLSeconds: 3600, - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if result.Serial != 40 { - t.Errorf("expected serial 40, got %d", result.Serial) - } -} diff --git a/extensions/SSH-Certificate-Signer/internal/cert/signer.go b/extensions/SSH-Certificate-Signer/internal/cert/signer.go index 45ac3b838..2576aa54a 100644 --- a/extensions/SSH-Certificate-Signer/internal/cert/signer.go +++ b/extensions/SSH-Certificate-Signer/internal/cert/signer.go @@ -56,7 +56,7 @@ type SignResult struct { } func SignCertificate(req *SignRequest) (*SignResult, error) { - _, sshSigner, err := ParseCAPrivateKey(req.CAPrivateKeyPEM) + sshSigner, err := ParseCAPrivateKey(req.CAPrivateKeyPEM) if err != nil { return nil, fmt.Errorf("parsing CA key: %w", err) } diff --git a/extensions/SSH-Certificate-Signer/internal/cert/signer_test.go b/extensions/SSH-Certificate-Signer/internal/cert/signer_test.go index 92df5b87f..653fbf679 100644 --- a/extensions/SSH-Certificate-Signer/internal/cert/signer_test.go +++ b/extensions/SSH-Certificate-Signer/internal/cert/signer_test.go @@ -16,10 +16,11 @@ package cert import ( + "crypto/ecdsa" "crypto/ed25519" + "crypto/elliptic" "crypto/rand" - "crypto/x509" - "encoding/pem" + "crypto/rsa" "testing" "time" @@ -32,17 +33,11 @@ func generateTestEd25519CA(t *testing.T) ([]byte, ssh.PublicKey) { if err != nil { t.Fatal(err) } - privBytes, err := x509.MarshalPKCS8PrivateKey(priv) - if err != nil { - t.Fatal(err) - } - privPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) - sshPub, err := ssh.NewPublicKey(pub) if err != nil { t.Fatal(err) } - return privPEM, sshPub + return openSSHPrivateKey(t, priv), sshPub } func generateTestEd25519UserKey(t *testing.T) ssh.PublicKey { @@ -193,3 +188,31 @@ func TestSignCertificate_WithCriticalOptions(t *testing.T) { t.Errorf("expected critical option source-address=10.0.0.0/8, got %v", cert.Permissions.CriticalOptions) } } + +// Make sure the ed25519 CA still signs RSA and ECDSA user keys, since users may bring either. +func TestSignCertificate_SignsRSAAndECDSAUserKeys(t *testing.T) { + caPrivPEM, _ := generateTestEd25519CA(t) + rsaKey, _ := rsa.GenerateKey(rand.Reader, 2048) + p256, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + p384, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + p521, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) + + for name, key := range map[string]any{ + "rsa": &rsaKey.PublicKey, + "ecdsa-p256": &p256.PublicKey, + "ecdsa-p384": &p384.PublicKey, + "ecdsa-p521": &p521.PublicKey, + } { + userKey, _ := ssh.NewPublicKey(key) + if _, err := SignCertificate(&SignRequest{ + PublicKey: userKey, + CAPrivateKeyPEM: caPrivPEM, + Serial: 10, + Principal: "jdoe", + UserEmail: "[email protected]", + TTLSeconds: 3600, + }); err != nil { + t.Errorf("%s user key: %v", name, err) + } + } +} diff --git a/extensions/SSH-Certificate-Signer/internal/cert/ssh_key.go b/extensions/SSH-Certificate-Signer/internal/cert/ssh_key.go index 7fe163f0a..89465be60 100644 --- a/extensions/SSH-Certificate-Signer/internal/cert/ssh_key.go +++ b/extensions/SSH-Certificate-Signer/internal/cert/ssh_key.go @@ -17,12 +17,9 @@ package cert import ( - "crypto" - "crypto/rsa" - "crypto/x509" + "bytes" "encoding/pem" "fmt" - "io" "strings" "golang.org/x/crypto/ssh" @@ -58,108 +55,53 @@ func SSHPublicKeyFingerprint(key ssh.PublicKey) string { return ssh.FingerprintSHA256(key) } -func ParseCAPrivateKey(pemData []byte) (crypto.Signer, ssh.Signer, error) { - block, _ := pem.Decode(pemData) - if block == nil { - return nil, nil, fmt.Errorf("failed to decode PEM block") +// ParseCAPrivateKey reads the CA private key. Only ed25519 keys in OpenSSH format are accepted. +func ParseCAPrivateKey(data []byte) (ssh.Signer, error) { + if block, _ := pem.Decode(data); block == nil || block.Type != "OPENSSH PRIVATE KEY" { + return nil, fmt.Errorf("CA private key must be in OpenSSH format") } - - var signer crypto.Signer - switch block.Type { - case "PRIVATE KEY": - key, err := x509.ParsePKCS8PrivateKey(block.Bytes) - if err != nil { - return nil, nil, fmt.Errorf("parsing PKCS8 private key: %w", err) - } - var ok bool - signer, ok = key.(crypto.Signer) - if !ok { - return nil, nil, fmt.Errorf("private key does not implement crypto.Signer") - } - case "EC PRIVATE KEY": - key, err := x509.ParseECPrivateKey(block.Bytes) - if err != nil { - return nil, nil, fmt.Errorf("parsing EC private key: %w", err) - } - signer = key - case "RSA PRIVATE KEY": - key, err := x509.ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - return nil, nil, fmt.Errorf("parsing RSA private key: %w", err) - } - signer = key - default: - return nil, nil, fmt.Errorf("unsupported PEM block type: %s", block.Type) + signer, err := ssh.ParsePrivateKey(data) + if err != nil { + return nil, fmt.Errorf("parsing CA private key: %w", err) } - - var sshSigner ssh.Signer - var err error - - // For RSA keys, use SHA-256 signer - if _, ok := signer.(*rsa.PrivateKey); ok { - sshSigner, err = ssh.NewSignerFromKey(signer) - if err != nil { - return nil, nil, fmt.Errorf("creating SSH signer: %w", err) - } - // Wrap to use rsa-sha2-256 algorithm - algorithmSigner, ok := sshSigner.(ssh.AlgorithmSigner) - if ok { - sshSigner = &rsaSHA256Signer{inner: algorithmSigner} - } - } else { - sshSigner, err = ssh.NewSignerFromKey(signer) - if err != nil { - return nil, nil, fmt.Errorf("creating SSH signer: %w", err) - } + if signer.PublicKey().Type() != ssh.KeyAlgoED25519 { + return nil, fmt.Errorf("CA key must be ed25519, got %s", signer.PublicKey().Type()) } - - return signer, sshSigner, nil -} - -// rsaSHA256Signer wraps an SSH AlgorithmSigner to always use rsa-sha2-256. -type rsaSHA256Signer struct { - inner ssh.AlgorithmSigner -} - -func (s *rsaSHA256Signer) PublicKey() ssh.PublicKey { - return s.inner.PublicKey() + return signer, nil } -func (s *rsaSHA256Signer) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) { - return s.inner.SignWithAlgorithm(rand, data, ssh.KeyAlgoRSASHA256) -} - -func ParseCAPublicKey(pemData []byte) (ssh.PublicKey, error) { - block, _ := pem.Decode(pemData) - if block == nil { - return nil, fmt.Errorf("failed to decode PEM block") - } - - pubKey, err := x509.ParsePKIXPublicKey(block.Bytes) +// ParseCAPublicKey reads the CA public key in OpenSSH format. +func ParseCAPublicKey(data []byte) (ssh.PublicKey, error) { + pub, err := ParseSSHPublicKey(string(data)) if err != nil { - return nil, fmt.Errorf("parsing public key: %w", err) + return nil, fmt.Errorf("parsing CA public key: %w", err) } - - sshPub, err := ssh.NewPublicKey(pubKey) - if err != nil { - return nil, fmt.Errorf("converting to SSH public key: %w", err) + if pub.Type() != ssh.KeyAlgoED25519 { + return nil, fmt.Errorf("CA key must be ed25519, got %s", pub.Type()) } - return sshPub, nil + return pub, nil } -// PEMToOpenSSH converts a PEM public key to OpenSSH format, suitable for trusted-user-ca-keys files. -func PEMToOpenSSH(publicKeyPEM []byte) (string, error) { - sshPub, err := ParseCAPublicKey(publicKeyPEM) +// CheckCAKeysMatch returns an error unless publicKey belongs to privateKey. +func CheckCAKeysMatch(privateKey, publicKey []byte) error { + signer, err := ParseCAPrivateKey(privateKey) if err != nil { - return "", err + return err + } + pub, err := ParseCAPublicKey(publicKey) + if err != nil { + return err + } + if !bytes.Equal(signer.PublicKey().Marshal(), pub.Marshal()) { + return fmt.Errorf("CA public key does not match the private key") } - return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(sshPub))), nil + return nil } -func CAFingerprint(publicKeyPEM []byte) (string, error) { - sshPub, err := ParseCAPublicKey(publicKeyPEM) +func CAFingerprint(publicKey []byte) (string, error) { + pub, err := ParseCAPublicKey(publicKey) if err != nil { return "", err } - return ssh.FingerprintSHA256(sshPub), nil + return ssh.FingerprintSHA256(pub), nil } diff --git a/extensions/SSH-Certificate-Signer/internal/cert/ssh_key_test.go b/extensions/SSH-Certificate-Signer/internal/cert/ssh_key_test.go index e42ccf4c6..38b94dc45 100644 --- a/extensions/SSH-Certificate-Signer/internal/cert/ssh_key_test.go +++ b/extensions/SSH-Certificate-Signer/internal/cert/ssh_key_test.go @@ -23,7 +23,6 @@ import ( "crypto/rsa" "crypto/x509" "encoding/pem" - "strings" "testing" "golang.org/x/crypto/ssh" @@ -116,141 +115,68 @@ func TestSSHPublicKeyFingerprint(t *testing.T) { } } -func TestParseCAPrivateKey_Ed25519(t *testing.T) { - _, priv, _ := ed25519.GenerateKey(rand.Reader) - privBytes, _ := x509.MarshalPKCS8PrivateKey(priv) - privPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) - - signer, sshSigner, err := ParseCAPrivateKey(privPEM) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if signer == nil || sshSigner == nil { - t.Fatal("expected non-nil signers") - } -} - -func TestParseCAPrivateKey_RSA(t *testing.T) { - rsaKey, _ := rsa.GenerateKey(rand.Reader, 2048) - privBytes, _ := x509.MarshalPKCS8PrivateKey(rsaKey) - privPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) - - _, sshSigner, err := ParseCAPrivateKey(privPEM) +// openSSHPrivateKey encodes key the way ssh-keygen writes it. +func openSSHPrivateKey(t *testing.T, key any) []byte { + t.Helper() + block, err := ssh.MarshalPrivateKey(key, "") if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if sshSigner == nil { - t.Fatal("expected non-nil SSH signer") + t.Fatal(err) } + return pem.EncodeToMemory(block) } -func TestParseCAPrivateKey_ECDSA(t *testing.T) { - ecKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - privBytes, _ := x509.MarshalPKCS8PrivateKey(ecKey) - privPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) - - _, sshSigner, err := ParseCAPrivateKey(privPEM) - if err != nil { +// Make sure an ed25519 CA key in OpenSSH format, as ssh-keygen writes it, is accepted. +func TestParseCAPrivateKey_AcceptsOpenSSHEd25519(t *testing.T) { + _, priv, _ := ed25519.GenerateKey(rand.Reader) + if _, err := ParseCAPrivateKey(openSSHPrivateKey(t, priv)); err != nil { t.Fatalf("unexpected error: %v", err) } - if sshSigner == nil { - t.Fatal("expected non-nil SSH signer") - } -} - -func TestParseCAPrivateKey_InvalidPEM(t *testing.T) { - _, _, err := ParseCAPrivateKey([]byte("not a PEM")) - if err == nil { - t.Error("expected error for invalid PEM") - } } -func TestCAFingerprint(t *testing.T) { - pub, _, _ := ed25519.GenerateKey(rand.Reader) - pubBytes, _ := x509.MarshalPKIXPublicKey(pub) - pubPEM := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes}) +// Make sure a CA key in PEM format or of a type other than ed25519 is refused. +func TestParseCAPrivateKey_RefusesOtherFormatsAndTypes(t *testing.T) { + _, ed25519Key, _ := ed25519.GenerateKey(rand.Reader) + pkcs8, _ := x509.MarshalPKCS8PrivateKey(ed25519Key) + rsaKey, _ := rsa.GenerateKey(rand.Reader, 2048) - fp, err := CAFingerprint(pubPEM) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if fp == "" || fp[:7] != "SHA256:" { - t.Errorf("expected SHA256: fingerprint, got %s", fp) + for name, key := range map[string][]byte{ + "ed25519 in PEM": pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}), + "rsa in OpenSSH": openSSHPrivateKey(t, rsaKey), + "not a key at all": []byte("not a key"), + } { + if _, err := ParseCAPrivateKey(key); err == nil { + t.Errorf("%s: accepted", name) + } } } -func TestPEMToOpenSSH_Ed25519(t *testing.T) { +// Make sure the CA public key is read as an ed25519 OpenSSH line and a key of another type is refused. +func TestParseCAPublicKey_NeedsEd25519Line(t *testing.T) { pub, _, _ := ed25519.GenerateKey(rand.Reader) - pubBytes, _ := x509.MarshalPKIXPublicKey(pub) - pubPEM := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes}) - - openssh, err := PEMToOpenSSH(pubPEM) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if !strings.HasPrefix(openssh, "ssh-ed25519 ") { - t.Errorf("expected ssh-ed25519 prefix, got %q", openssh) - } - - // Should be parseable back - parsed, err := ParseSSHPublicKey(openssh) - if err != nil { - t.Fatalf("failed to re-parse OpenSSH key: %v", err) - } - if parsed.Type() != "ssh-ed25519" { - t.Errorf("expected ssh-ed25519, got %s", parsed.Type()) + sshPub, _ := ssh.NewPublicKey(pub) + if _, err := ParseCAPublicKey(ssh.MarshalAuthorizedKey(sshPub)); err != nil { + t.Errorf("ed25519 line: %v", err) } -} -func TestPEMToOpenSSH_RSA(t *testing.T) { rsaKey, _ := rsa.GenerateKey(rand.Reader, 2048) - pubBytes, _ := x509.MarshalPKIXPublicKey(&rsaKey.PublicKey) - pubPEM := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes}) - - openssh, err := PEMToOpenSSH(pubPEM) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if !strings.HasPrefix(openssh, "ssh-rsa ") { - t.Errorf("expected ssh-rsa prefix, got %q", openssh) + rsaPub, _ := ssh.NewPublicKey(&rsaKey.PublicKey) + if _, err := ParseCAPublicKey(ssh.MarshalAuthorizedKey(rsaPub)); err == nil { + t.Error("rsa line: accepted") } } -func TestPEMToOpenSSH_ECDSA(t *testing.T) { - ecKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - pubBytes, _ := x509.MarshalPKIXPublicKey(&ecKey.PublicKey) - pubPEM := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes}) - - openssh, err := PEMToOpenSSH(pubPEM) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if !strings.HasPrefix(openssh, "ecdsa-sha2-nistp256 ") { - t.Errorf("expected ecdsa-sha2-nistp256 prefix, got %q", openssh) - } -} - -func TestPEMToOpenSSH_InvalidPEM(t *testing.T) { - _, err := PEMToOpenSSH([]byte("not valid PEM")) - if err == nil { - t.Error("expected error for invalid PEM") - } -} - -func TestPEMToOpenSSH_NoTrailingNewline(t *testing.T) { - pub, _, _ := ed25519.GenerateKey(rand.Reader) - pubBytes, _ := x509.MarshalPKIXPublicKey(pub) - pubPEM := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes}) +// Make sure the stored CA public key must belong to the private key. +func TestCheckCAKeysMatch(t *testing.T) { + pub, priv, _ := ed25519.GenerateKey(rand.Reader) + sshPub, _ := ssh.NewPublicKey(pub) + otherPub, _, _ := ed25519.GenerateKey(rand.Reader) + otherSSHPub, _ := ssh.NewPublicKey(otherPub) + privateKey := openSSHPrivateKey(t, priv) - openssh, err := PEMToOpenSSH(pubPEM) - if err != nil { - t.Fatalf("unexpected error: %v", err) + if err := CheckCAKeysMatch(privateKey, ssh.MarshalAuthorizedKey(sshPub)); err != nil { + t.Errorf("matching keys: %v", err) } - - if strings.HasSuffix(openssh, "\n") { - t.Error("PEMToOpenSSH should not include trailing newline") + if err := CheckCAKeysMatch(privateKey, ssh.MarshalAuthorizedKey(otherSSHPub)); err == nil { + t.Error("keys of different CAs: accepted") } } diff --git a/extensions/SSH-Certificate-Signer/internal/config/config.go b/extensions/SSH-Certificate-Signer/internal/config/config.go index 46b7553dd..9a4b40376 100644 --- a/extensions/SSH-Certificate-Signer/internal/config/config.go +++ b/extensions/SSH-Certificate-Signer/internal/config/config.go @@ -34,7 +34,6 @@ type Config struct { Vault VaultConfig `yaml:"vault"` Signer SignerConfig `yaml:"signer"` Logging LoggingConfig `yaml:"logging"` - Metrics MetricsConfig `yaml:"metrics"` } type ServerConfig struct { @@ -59,6 +58,7 @@ type VaultConfig struct { Address string `yaml:"address"` Token string `yaml:"token"` MountPath string `yaml:"mount_path"` + CAKeyPath string `yaml:"ca_key_path"` TimeoutSeconds int `yaml:"timeout_seconds"` } @@ -73,12 +73,7 @@ type SignerConfig struct { } type CAConfig struct { - Rotation RotationConfig `yaml:"rotation"` -} - -type RotationConfig struct { - PeriodHours int `yaml:"period_hours"` - OverlapHours int `yaml:"overlap_hours"` + CreateIfMissing bool `yaml:"create_if_missing"` } type PolicyConfig struct { @@ -97,11 +92,6 @@ type LoggingConfig struct { Format string `yaml:"format"` } -type MetricsConfig struct { - Enabled bool `yaml:"enabled"` - Path string `yaml:"path"` -} - func DefaultConfig() *Config { return &Config{ Server: ServerConfig{ @@ -124,17 +114,12 @@ func DefaultConfig() *Config { Address: "http://localhost:8200", Token: "", MountPath: "ssh-ca", + CAKeyPath: "ca/current", TimeoutSeconds: 10, }, Signer: SignerConfig{ ReservedUsernames: []string{"root"}, LoginPort: 22, - CA: CAConfig{ - Rotation: RotationConfig{ - PeriodHours: 2160, - OverlapHours: 2, - }, - }, Policy: PolicyConfig{ MaxTTLSeconds: 86400, AllowedKeyTypes: []string{"ed25519", "rsa", "ecdsa"}, @@ -148,10 +133,6 @@ func DefaultConfig() *Config { Level: "info", Format: "json", }, - Metrics: MetricsConfig{ - Enabled: true, - Path: "/metrics", - }, } } diff --git a/extensions/SSH-Certificate-Signer/internal/handler/ca_public_key.go b/extensions/SSH-Certificate-Signer/internal/handler/ca_public_key.go index e4f24e65f..bde472ded 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/ca_public_key.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/ca_public_key.go @@ -21,6 +21,8 @@ import ( "net/http" "strings" + "golang.org/x/crypto/ssh" + "github.com/apache/airavata-custos/signer/internal/cert" vaultpkg "github.com/apache/airavata-custos/signer/internal/vault" ) @@ -51,23 +53,21 @@ func (h *CAPublicKeyHandler) Handle(w http.ResponseWriter, r *http.Request) { return } - opensshKey, err := cert.PEMToOpenSSH(currentKey.PublicKey) + caPublicKey, err := cert.ParseCAPublicKey(currentKey.PublicKey) if err != nil { - h.logger.Error("failed to convert CA key to OpenSSH format", "error", err) - writeError(w, http.StatusInternalServerError, "internal_error", "Failed to convert CA key") + h.logger.Error("failed to parse CA public key", "error", err) + writeError(w, http.StatusInternalServerError, "internal_error", "Failed to read CA key") return } + opensshKey := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(caPublicKey))) // If the client accepts JSON, return structured response accept := r.Header.Get("Accept") if strings.Contains(accept, "application/json") { - fingerprint, _ := cert.CAFingerprint(currentKey.PublicKey) - algorithm := cert.NormalizeKeyType(strings.SplitN(opensshKey, " ", 2)[0]) - resp := CAPublicKeyJSONResponse{ PublicKey: opensshKey, - Fingerprint: fingerprint, - Algorithm: algorithm, + Fingerprint: ssh.FingerprintSHA256(caPublicKey), + Algorithm: cert.NormalizeKeyType(caPublicKey.Type()), } w.Header().Set("Content-Type", "application/json") diff --git a/extensions/SSH-Certificate-Signer/internal/handler/sign.go b/extensions/SSH-Certificate-Signer/internal/handler/sign.go index 24c21ed6e..5c35a34bf 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,11 @@ 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" ) @@ -57,17 +54,16 @@ type SignRequest struct { } type SignResponse struct { - Certificate string `json:"certificate"` - SerialNumber int64 `json:"serial_number"` - ValidAfter int64 `json:"valid_after"` - ValidBefore int64 `json:"valid_before"` - CAFingerprint string `json:"ca_fingerprint"` - LoginHost string `json:"login_host"` - LoginPort int `json:"login_port"` - Principal string `json:"principal"` - ForceCommand string `json:"force_command,omitempty"` - GrantedExtensions []string `json:"granted_extensions"` - TimingMicros map[string]int64 `json:"timing_micros,omitempty"` + Certificate string `json:"certificate"` + SerialNumber int64 `json:"serial_number"` + ValidAfter int64 `json:"valid_after"` + ValidBefore int64 `json:"valid_before"` + CAFingerprint string `json:"ca_fingerprint"` + LoginHost string `json:"login_host"` + LoginPort int `json:"login_port"` + Principal string `json:"principal"` + ForceCommand string `json:"force_command,omitempty"` + GrantedExtensions []string `json:"granted_extensions"` } type SignSettings struct { @@ -81,6 +77,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 +87,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 +96,7 @@ func NewSignHandler( policyEnforcer: policyEnforcer, principalValidator: principalValidator, vaultClient: vaultClient, + db: db, auditLogger: auditLogger, settings: settings, logger: logger, @@ -105,78 +104,62 @@ 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. - timings := map[string]int64{} - stageStart := startTime - mark := func(stage string) { - now := time.Now() - timings[stage] += now.Sub(stageStart).Microseconds() - stageStart = now - } - - defer func() { - metrics.SignDurationSeconds.Observe(time.Since(startTime).Seconds()) - }() - var req SignRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() + h.logRefusal(&req, "invalid_request") writeError(w, http.StatusBadRequest, "invalid_request", "Invalid request body") return } if !principalRegex.MatchString(req.Principal) { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() + h.logRefusal(&req, "invalid_request") writeError(w, http.StatusBadRequest, "invalid_request", "Invalid principal format: must match ^[a-z_][a-z0-9_-]{0,31}$") return } // Checked before the validator, so it holds whichever validator is on. if slices.ContainsFunc(h.settings.ReservedUsernames, func(name string) bool { return strings.EqualFold(name, req.Principal) }) { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() + h.logRefusal(&req, "reserved_username") writeError(w, http.StatusForbidden, "reserved_username", "This username cannot be signed for") return } if req.UserEmail == "" || req.UserSub == "" || req.RequestedBy == "" { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() + h.logRefusal(&req, "invalid_request") writeError(w, http.StatusBadRequest, "invalid_request", "Missing required field: user_email, user_sub and requested_by") return } if !validAttributes(&req) { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() + h.logRefusal(&req, "invalid_request") writeError(w, http.StatusBadRequest, "invalid_request", "user_email, user_sub, requested_by or force_command is not valid") return } if req.SourceAddress != "" && !validSourceAddress(req.SourceAddress) { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() + h.logRefusal(&req, "invalid_request") writeError(w, http.StatusBadRequest, "invalid_request", "source_address must be a comma-separated list of IP addresses or CIDR blocks") return } sshPubKey, err := cert.ParseSSHPublicKey(req.PublicKey) if err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() + h.logRefusal(&req, "invalid_public_key") writeError(w, http.StatusBadRequest, "invalid_public_key", "Invalid SSH public key format") return } - mark("parse_request_us") if err := h.policyEnforcer.Enforce(req.TTLSeconds, sshPubKey.Type()); err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() if policyErr, ok := err.(*policy.PolicyError); ok { + h.logRefusal(&req, policyErr.Code) writeError(w, http.StatusBadRequest, policyErr.Code, policyErr.Message) return } + h.logger.Error("policy enforcement failed", "error", err) writeError(w, http.StatusInternalServerError, "internal_error", "Policy enforcement error") return } - mark("policy_enforcement_us") grantedExts, err := cert.ResolveExtensions(h.settings.DeniedExtensions, req.ExcludeExtensions) if err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() + h.logRefusal(&req, "invalid_request") writeError(w, http.StatusBadRequest, "invalid_request", err.Error()) return } @@ -185,46 +168,33 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { valResult, err := h.principalValidator.Validate(r.Context(), req.Principal, req.UserSub) if err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() if valErr, ok := err.(*validation.ValidationError); ok { + h.logRefusal(&req, "principal_denied") httputil.WriteJSONErrorWithExtra(w, http.StatusForbidden, "principal_denied", valErr.Message, map[string]string{ "reason_code": valErr.ReasonCode, }) return } + h.logger.Error("principal validation failed", "error", err) writeError(w, http.StatusInternalServerError, "internal_error", "Principal validation error") return } - mark("principal_validation_us") validatedPrincipal := valResult.ValidatedPrincipal caKeyPair, err := h.vaultClient.GetCurrentCAKey(r.Context()) if err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() - metrics.VaultOperationsTotal.WithLabelValues("get_ca_key", "error").Inc() h.logger.Error("failed to get CA key", "error", err) writeError(w, http.StatusServiceUnavailable, "internal_error", "CA key storage unavailable") return } - 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") criticalOpts := map[string]string{} if req.ForceCommand != "" { @@ -249,12 +219,10 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { signResult, err := cert.SignCertificate(signReq) if err != nil { - metrics.SignRequestsTotal.WithLabelValues("error").Inc() h.logger.Error("failed to sign certificate", "error", err) writeError(w, http.StatusInternalServerError, "internal_error", "Failed to sign certificate") return } - mark("cert_signing_us") pubKeyFP := cert.SSHPublicKeyFingerprint(sshPubKey) @@ -274,64 +242,12 @@ 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 { + h.logger.Error("failed to write audit log", "error", err) + writeError(w, http.StatusInternalServerError, "internal_error", "Failed to record issuance") + return } - metrics.SignRequestsTotal.WithLabelValues("success").Inc() - timings["total_us"] = time.Since(startTime).Microseconds() - resp := SignResponse{ Certificate: signResult.AuthorizedKey, SerialNumber: serial, @@ -343,7 +259,6 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { Principal: validatedPrincipal, ForceCommand: req.ForceCommand, GrantedExtensions: grantedExtNames, - TimingMicros: timings, } w.Header().Set("Content-Type", "application/json") @@ -351,6 +266,11 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(resp) } +// logRefusal records a turned-down request. Issued certificates are stored, refusals are not. +func (h *SignHandler) logRefusal(req *SignRequest, code string) { + h.logger.Warn("sign request refused", "code", code, "principal", req.Principal, "user_sub", req.UserSub, "requested_by", req.RequestedBy) +} + // These values reach the key ID in the login log. A control character could forge // a log line, and ":" could make two key IDs the same. func validAttributes(req *SignRequest) bool { @@ -377,12 +297,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/metrics/metrics.go b/extensions/SSH-Certificate-Signer/internal/metrics/metrics.go deleted file mode 100644 index 201a41039..000000000 --- a/extensions/SSH-Certificate-Signer/internal/metrics/metrics.go +++ /dev/null @@ -1,45 +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 metrics defines Prometheus metric collectors. -package metrics - -import ( - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promauto" -) - -var ( - SignRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{ - Name: "signer_sign_requests_total", - Help: "Total number of signing requests", - }, []string{"status"}) - - SignDurationSeconds = promauto.NewHistogram(prometheus.HistogramOpts{ - Name: "signer_sign_duration_seconds", - Help: "Duration of signing requests in seconds", - Buckets: prometheus.DefBuckets, - }) - - AuthFailuresTotal = promauto.NewCounterVec(prometheus.CounterOpts{ - Name: "signer_auth_failures_total", - Help: "Total number of authentication failures", - }, []string{"reason"}) - - VaultOperationsTotal = promauto.NewCounterVec(prometheus.CounterOpts{ - Name: "signer_vault_operations_total", - Help: "Total number of Vault operations", - }, []string{"operation", "status"}) -) diff --git a/extensions/SSH-Certificate-Signer/internal/server/middleware.go b/extensions/SSH-Certificate-Signer/internal/server/middleware.go index 16738e93a..91cd523c1 100644 --- a/extensions/SSH-Certificate-Signer/internal/server/middleware.go +++ b/extensions/SSH-Certificate-Signer/internal/server/middleware.go @@ -17,11 +17,11 @@ package server import ( "crypto/subtle" + "log/slog" "net/http" "strings" "github.com/apache/airavata-custos/signer/internal/httputil" - "github.com/apache/airavata-custos/signer/internal/metrics" ) // ServiceTokenMiddleware admits only the one trusted caller. @@ -30,7 +30,7 @@ func ServiceTokenMiddleware(token string) func(http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 { - metrics.AuthFailuresTotal.WithLabelValues("invalid_token").Inc() + slog.Warn("request with an invalid service token", "path", r.URL.Path, "remote_addr", r.RemoteAddr) httputil.WriteJSONError(w, http.StatusUnauthorized, "unauthorized", "Invalid service token") return } diff --git a/extensions/SSH-Certificate-Signer/internal/server/routes.go b/extensions/SSH-Certificate-Signer/internal/server/routes.go index ba740e0fe..bf41a7f47 100644 --- a/extensions/SSH-Certificate-Signer/internal/server/routes.go +++ b/extensions/SSH-Certificate-Signer/internal/server/routes.go @@ -19,7 +19,6 @@ import ( "net/http" "github.com/go-chi/chi/v5" - "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/apache/airavata-custos/signer/internal/config" ) @@ -42,11 +41,6 @@ func NewRouter(cfg *config.Config, handlers Handlers) *chi.Mux { // Health endpoint (no auth) r.Get("/api/v1/health", handlers.Health) - // Metrics endpoint (no auth) - if cfg.Metrics.Enabled { - r.Handle(cfg.Metrics.Path, promhttp.Handler()) - } - r.Group(func(r chi.Router) { r.Use(ServiceTokenMiddleware(cfg.Signer.ServiceToken)) 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 ab07f6346..962faf203 100644 --- a/extensions/SSH-Certificate-Signer/internal/vault/client.go +++ b/extensions/SSH-Certificate-Signer/internal/vault/client.go @@ -20,58 +20,33 @@ import ( "context" "crypto/ed25519" "crypto/rand" - "crypto/x509" "encoding/json" "encoding/pem" "errors" "fmt" - "strconv" - "strings" "time" vaultapi "github.com/openbao/openbao/api/v2" + "golang.org/x/crypto/ssh" "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") - -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 -} +var ErrCANotFound = errors.New("no CA key in vault") type CAKeyPair struct { - PrivateKey []byte // PEM-encoded private key - PublicKey []byte // PEM-encoded public key - Algorithm string // e.g., "ed25519" - CreatedAt string -} - -type CAMetadata struct { - SerialCounter int64 - LastRotationAt string - NextRotationAt string - RotationPeriodH int - OverlapHours int + 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 Client struct { - client *vaultapi.Client - mountPath 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 @@ -83,9 +58,9 @@ func NewClient(cfg config.VaultConfig, rotationCfg config.RotationConfig) (*Clie client.SetToken(cfg.Token) return &Client{ - client: client, - mountPath: cfg.MountPath, - rotationCfg: rotationCfg, + client: client, + mountPath: cfg.MountPath, + caKeyPath: cfg.CAKeyPath, }, nil } @@ -97,224 +72,58 @@ func (c *Client) Healthy(ctx context.Context) error { return nil } -// The deployment has one CA. Its keys and serial counter are stored here. -// TODO CA from file path support -const caPath = "ca" - -func (c *Client) kvPath(parts ...string) string { - path := c.mountPath + "/data" - for _, p := range parts { - path += "/" + p - } - return path +// kvPath turns a secret path into its KV v2 API path, {mount}/data/{secretPath}. +func (c *Client) kvPath(secretPath string) string { + return c.mountPath + "/data/" + secretPath } -// GetCurrentCAKey returns the current CA key, auto-creating one if it doesn't exist. +// GetCurrentCAKey reads the CA keys from the private_key and public_key fields at the configured path. +// TODO CA from file path support func (c *Client) GetCurrentCAKey(ctx context.Context) (*CAKeyPair, error) { - kp, err := c.readCAKey(ctx, "current") + kvPath := c.kvPath(c.caKeyPath) + secret, err := c.client.Logical().ReadWithContext(ctx, kvPath) if err != nil { - return nil, err - } - if kp != nil { - return kp, nil + return nil, fmt.Errorf("reading vault path %s: %w", kvPath, err) } - - kp, err = generateEd25519CAKey() - if err != nil { - return nil, err - } - - if err := c.writeCAKey(ctx, "current", kp); err != nil { - return nil, 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 + var data map[string]any + if secret != nil { + data, _ = secret.Data["data"].(map[string]any) } - if meta == nil { - if err := c.initMetadata(ctx); err != nil { - return 0, err - } - return 1, nil + privateKey, _ := data["private_key"].(string) + publicKey, _ := data["public_key"].(string) + createdAt, _ := data["created_at"].(string) + if privateKey == "" { + return nil, fmt.Errorf("%w at %s", ErrCANotFound, kvPath) } - - newSerial := meta.SerialCounter + 1 - meta.SerialCounter = newSerial - if err := c.writeMetadataCAS(ctx, meta, version); err != nil { - return 0, err + // Not ErrCANotFound, so a missing public key never makes the signer replace an existing CA. + if publicKey == "" { + return nil, fmt.Errorf("CA public key missing at %s", kvPath) } - return newSerial, nil + return &CAKeyPair{PrivateKey: []byte(privateKey), PublicKey: []byte(publicKey), CreatedAt: createdAt}, nil } -func (c *Client) readCAKey(ctx context.Context, slot string) (*CAKeyPair, error) { - path := c.kvPath(caPath, slot) - secret, err := c.client.Logical().ReadWithContext(ctx, path) +// GenerateCAKey generates a new CA key and stores it as the current one. +// TODO - also publish the new public key to the login nodes' trusted CA file. +func (c *Client) GenerateCAKey(ctx context.Context) (*CAKeyPair, error) { + kp, err := generateEd25519CAKey() if err != nil { - return nil, fmt.Errorf("reading vault path %s: %w", path, err) - } - if secret == nil || secret.Data == nil { - return nil, nil - } - - data, ok := secret.Data["data"].(map[string]interface{}) - if !ok || data == nil { - return nil, nil - } - - kp := &CAKeyPair{} - if v, ok := data["private_key"].(string); ok { - kp.PrivateKey = []byte(v) - } - if v, ok := data["public_key"].(string); ok { - kp.PublicKey = []byte(v) - } - if v, ok := data["algorithm"].(string); ok { - kp.Algorithm = v - } - if v, ok := data["created_at"].(string); ok { - kp.CreatedAt = v - } - - if len(kp.PrivateKey) == 0 { - return nil, nil + return nil, err } - return kp, nil -} -func (c *Client) writeCAKey(ctx context.Context, slot string, kp *CAKeyPair) error { - path := c.kvPath(caPath, slot) - data := map[string]interface{}{ - "data": map[string]interface{}{ + kvPath := c.kvPath(c.caKeyPath) + // cas 0 makes the write fail if anything is already stored, so an existing CA is never replaced. + data := map[string]any{ + "options": map[string]any{"cas": 0}, + "data": map[string]any{ "private_key": string(kp.PrivateKey), "public_key": string(kp.PublicKey), - "algorithm": kp.Algorithm, "created_at": kp.CreatedAt, }, } - _, err := c.client.Logical().WriteWithContext(ctx, path, data) - if err != nil { - return fmt.Errorf("writing vault path %s: %w", path, err) - } - return nil -} - -func (c *Client) readMetadataWithVersion(ctx context.Context) (*CAMetadata, int, error) { - path := c.kvPath(caPath, "metadata") - 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 { - path := c.kvPath(caPath, "metadata") - 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, path, data) - if err != nil { - return fmt.Errorf("writing vault metadata: %w", err) + if _, err := c.client.Logical().WriteWithContext(ctx, kvPath, data); err != nil { + return nil, fmt.Errorf("writing vault path %s: %w", kvPath, err) } - return nil -} - -func (c *Client) writeMetadataCAS(ctx context.Context, meta *CAMetadata, cas int) error { - path := c.kvPath(caPath, "metadata") - data := map[string]interface{}{ - "options": map[string]interface{}{ - "cas": cas, - }, - "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, path, 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) + return kp, nil } func generateEd25519CAKey() (*CAKeyPair, error) { @@ -323,22 +132,18 @@ func generateEd25519CAKey() (*CAKeyPair, error) { return nil, fmt.Errorf("generating ed25519 key: %w", err) } - privBytes, err := x509.MarshalPKCS8PrivateKey(priv) + privBlock, err := ssh.MarshalPrivateKey(priv, "") if err != nil { return nil, fmt.Errorf("marshaling private key: %w", err) } - privPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) - - pubBytes, err := x509.MarshalPKIXPublicKey(pub) + sshPub, err := ssh.NewPublicKey(pub) if err != nil { return nil, fmt.Errorf("marshaling public key: %w", err) } - pubPEM := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes}) return &CAKeyPair{ - PrivateKey: privPEM, - PublicKey: pubPEM, - Algorithm: "ed25519", + PrivateKey: pem.EncodeToMemory(privBlock), + PublicKey: ssh.MarshalAuthorizedKey(sshPub), CreatedAt: time.Now().UTC().Format(time.RFC3339), }, 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 0d07eea78..3e3f8c0cc 100644 --- a/extensions/SSH-Certificate-Signer/main.go +++ b/extensions/SSH-Certificate-Signer/main.go @@ -16,6 +16,7 @@ package main import ( + "context" "errors" "fmt" "log/slog" @@ -24,6 +25,7 @@ import ( "time" "github.com/apache/airavata-custos/signer/internal/audit" + "github.com/apache/airavata-custos/signer/internal/cert" "github.com/apache/airavata-custos/signer/internal/config" "github.com/apache/airavata-custos/signer/internal/handler" "github.com/apache/airavata-custos/signer/internal/policy" @@ -141,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) @@ -151,6 +153,13 @@ func runServer(cfg *config.Config, logger *slog.Logger, autoMigrate bool) { policyEnforcer := policy.NewEnforcer(cfg.Signer.Policy.MaxTTLSeconds, cfg.Signer.Policy.AllowedKeyTypes) auditLogger := audit.NewLogger(db, logger) + caFingerprint, err := loadCA(context.Background(), vaultClient, cfg.Signer.CA.CreateIfMissing, auditLogger) + if err != nil { + logger.Error("failed to load CA", "error", err) + os.Exit(1) + } + logger.Info("CA loaded", "ca_fingerprint", caFingerprint) + cacheTTL := time.Duration(cfg.Signer.Validation.CacheTTLSeconds) * time.Second ldapConnector := validation.NewDefaultLDAPConnector() principalValidator := validation.NewValidatorDispatcher( @@ -162,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, @@ -190,6 +199,32 @@ func runServer(cfg *config.Config, logger *slog.Logger, autoMigrate bool) { } } +// loadCA makes sure the CA exists before the signer serves requests and returns its fingerprint. +func loadCA(ctx context.Context, vaultClient *vault.Client, createIfMissing bool, auditLogger *audit.Logger) (string, error) { + kp, err := vaultClient.GetCurrentCAKey(ctx) + if errors.Is(err, vault.ErrCANotFound) { + if !createIfMissing { + return "", fmt.Errorf("%w: store the CA key, or set signer.ca.create_if_missing to create one", err) + } + if kp, err = vaultClient.GenerateCAKey(ctx); err != nil { + return "", err + } + fingerprint, err := cert.CAFingerprint(kp.PublicKey) + if err != nil { + return "", err + } + auditLogger.LogCACreated(ctx, fingerprint) + return fingerprint, nil + } + if err != nil { + return "", err + } + if err := cert.CheckCAKeysMatch(kp.PrivateKey, kp.PublicKey); err != nil { + return "", err + } + return cert.CAFingerprint(kp.PublicKey) +} + func setupLogger(cfg config.LoggingConfig) *slog.Logger { var level slog.Level switch strings.ToLower(cfg.Level) { 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,
