This is an automated email from the ASF dual-hosted git repository. lahirujayathilake pushed a commit to branch ssh-certs-rate-limit in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit b00849f168bc921deff3d5b4bc46941c130b0cfa Author: lahiruj <[email protected]> AuthorDate: Fri Nov 13 01:16:01 2026 -0500 Limit how many certificates one user can get per hour --- connectors/Signer/README.md | 24 +++++++++---------- dev-ops/compose/signer-e2e.sh | 28 ++++++++++------------ extensions/SSH-Certificate-Signer/README.md | 7 ++++-- .../SSH-Certificate-Signer/config.example.yaml | 3 +++ .../internal/config/config.go | 20 ++++++++++++---- .../internal/handler/sign.go | 23 ++++++++++++++---- .../internal/store/issuance_log.go | 11 +++++++++ extensions/SSH-Certificate-Signer/main.go | 10 ++++---- 8 files changed, 83 insertions(+), 43 deletions(-) diff --git a/connectors/Signer/README.md b/connectors/Signer/README.md index 9c4d7a2bc..922ed3e0f 100644 --- a/connectors/Signer/README.md +++ b/connectors/Signer/README.md @@ -26,16 +26,16 @@ to the signer. To offer the signer without the rest of Custos, enable only this ## Routes -| Route | Needs | Does | -|-----------------------------------------------------------|-----------------------------|---------------------------------------------------------------| -| `GET /connectors/signer/certificates` | `signer:certificates:read` | All certificates | -| `GET /connectors/signer/certificates/{serial}` | `signer:certificates:read` | Any certificate | -| `POST /connectors/signer/certificates/{serial}/revoke` | `signer:certificates:write` | Revoke any certificate, recorded as `user/<admin id>` | -| `GET /connectors/signer/me/certificates` | Signed in | The caller's own certificates | -| `POST /connectors/signer/me/certificates` | Signed in | Generate a certificate for the caller's account | -| `GET /connectors/signer/me/certificates/{serial}` | Signed in | One of the caller's own certificates | -| `POST /connectors/signer/me/certificates/{serial}/revoke` | Signed in | Revoke one of the caller's own, recorded as `user/<id>` | -| `GET /connectors/signer/status` | `signer:certificates:read` | Whether the signer answers its health route, and how fast | +| Route | Needs | Does | +|-----------------------------------------------------------|-----------------------------|-----------------------------------------------------------| +| `GET /connectors/signer/certificates` | `signer:certificates:read` | All certificates | +| `GET /connectors/signer/certificates/{serial}` | `signer:certificates:read` | Any certificate | +| `POST /connectors/signer/certificates/{serial}/revoke` | `signer:certificates:write` | Revoke any certificate, recorded as `user/<admin id>` | +| `GET /connectors/signer/me/certificates` | Signed in | The caller's own certificates | +| `POST /connectors/signer/me/certificates` | Signed in | Generate a certificate for the caller's account | +| `GET /connectors/signer/me/certificates/{serial}` | Signed in | One of the caller's own certificates | +| `POST /connectors/signer/me/certificates/{serial}/revoke` | Signed in | Revoke one of the caller's own, recorded as `user/<id>` | +| `GET /connectors/signer/status` | `signer:certificates:read` | Whether the signer answers its health route, and how fast | The certificate lists are keyset-paged: pass `limit` and the last `next_cursor` as `cursor`. Someone else's certificate on a `me` route is a 404. @@ -46,8 +46,8 @@ active allocation on that cluster. The username comes from the cluster account, caller's verified token, never from the request. A refusal has an `error` code: `user_not_active`, `no_cluster_account`, `cluster_account_not_ready`, -`no_active_allocation`, `signer_unavailable`, or from the signer `reserved_username`, `invalid_public_key` and -`key_type_not_allowed`. +`no_active_allocation`, `signer_unavailable`, or from the signer `reserved_username`, `invalid_public_key`, +`key_type_not_allowed` and `too_many_certificates`. Service accounts can't use these routes. A person generates a certificate and hands it to the tool that needs it. diff --git a/dev-ops/compose/signer-e2e.sh b/dev-ops/compose/signer-e2e.sh index 4c543c3d7..5e3993828 100755 --- a/dev-ops/compose/signer-e2e.sh +++ b/dev-ops/compose/signer-e2e.sh @@ -32,8 +32,9 @@ SERVICE_TOKEN="${SIGNER_SERVICE_TOKEN:-dev-service-token-not-for-production}" SSH_PORT="${SSH_PORT:-2222}" PRINCIPAL="${PRINCIPAL:-testuser}" USER_EMAIL="[email protected]" -USER_SUB="http://idp.example.edu/users/testuser" -REQUESTED_BY="app/e2e" +# A new subject per run, so a rerun is not refused by the per-user limit. +USER_SUB="http://idp.example.edu/users/testuser-$(date +%s)" +REQUESTED_BY="user/e2e" WORK_DIR=$(mktemp -d) trap 'rm -rf "$WORK_DIR"' EXIT @@ -188,20 +189,15 @@ else fi docker compose exec -T sshd-login ssh-keygen -kf /etc/ssh/revoked_keys.krl -# --- serial races: the signer detects them by matching OpenBao's CAS -# message, so pin the mapping here; a reword upstream would surface as a -# 500 instead of a 409. Passes when no race occurs. -codes=$(for _ in $(seq 1 20); do - curl -s -o /dev/null -w "%{http_code}\n" "$SIGNER_URL/api/v1/sign" \ - -H "Authorization: Bearer $SERVICE_TOKEN" \ - -H "Content-Type: application/json" \ - -d "$(sign_body "$PRINCIPAL" 300)" & -done | sort -u | tr '\n' ' ') -if [ -n "$(echo "$codes" | tr ' ' '\n' | grep -v -E '^(200|409)?$')" ] || ! echo "$codes" | grep -qw 200; then - check "concurrent serial conflicts return 409, not 500 (saw: $codes)" 1 -else - check "concurrent serial conflicts return 409, not 500 (saw: $codes)" 0 -fi +# --- per-user limit: keep signing for this user until the signer refuses +code=200 +signs=0 +while [ "$code" = "200" ] && [ "$signs" -lt 50 ]; do + code=$(sign "$PRINCIPAL" 300) + signs=$((signs+1)) +done +[ "$code" = "429" ] && grep -q too_many_certificates "$WORK_DIR/resp.json" +check "per-user limit refuses with 429 too_many_certificates (HTTP $code after $signs more signs)" $? echo echo "$PASS passed, $FAIL failed" diff --git a/extensions/SSH-Certificate-Signer/README.md b/extensions/SSH-Certificate-Signer/README.md index 1836ea5c9..293faf415 100644 --- a/extensions/SSH-Certificate-Signer/README.md +++ b/extensions/SSH-Certificate-Signer/README.md @@ -38,8 +38,10 @@ not interpret `requested_by`. 2. It refuses a username in `signer.reserved_usernames`, whichever validator is on. 3. It enforces the deployment's maximum TTL and allowed key types, and grants the standard extensions minus those denied. -4. It runs the validator set in `signer.validation.principal_validator`, below. -5. It signs with the CA key from Vault and logs the issuance in `certificate_issuance_logs`. +4. It refuses a user who already has `certificate_limit.max_per_user` certificates in the last + `certificate_limit.window_seconds` (default 5 an hour). +5. It runs the validator set in `signer.validation.principal_validator`, below. +6. It signs with the CA key from Vault and logs the issuance in `certificate_issuance_logs`. | `principal_validator` | Principal check | |-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------| @@ -299,6 +301,7 @@ curl -s -X POST http://localhost:8084/api/v1/certificates/42/revoke \ | Migrations not found | The working directory is not this one | Run the signer from `extensions/SSH-Certificate-Signer` | | 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 429 `too_many_certificates` | The user reached the per-user limit | Wait for the window to pass, or raise `certificate_limit` | | 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 | diff --git a/extensions/SSH-Certificate-Signer/config.example.yaml b/extensions/SSH-Certificate-Signer/config.example.yaml index 77bb75fe2..bcb9b8d9d 100644 --- a/extensions/SSH-Certificate-Signer/config.example.yaml +++ b/extensions/SSH-Certificate-Signer/config.example.yaml @@ -61,6 +61,9 @@ signer: - rsa - ecdsa denied_extensions: [] # any of the standard ssh extensions + certificate_limit: + max_per_user: 5 # certificates one user can get in the window below + window_seconds: 3600 validation: principal_validator: none # "none", or "ldap" for the site's own check cache_ttl_seconds: 300 # Vault credential cache TTL for validators diff --git a/extensions/SSH-Certificate-Signer/internal/config/config.go b/extensions/SSH-Certificate-Signer/internal/config/config.go index 9a4b40376..148aa67ed 100644 --- a/extensions/SSH-Certificate-Signer/internal/config/config.go +++ b/extensions/SSH-Certificate-Signer/internal/config/config.go @@ -77,9 +77,15 @@ type CAConfig struct { } type PolicyConfig struct { - MaxTTLSeconds int `yaml:"max_ttl_seconds"` - AllowedKeyTypes []string `yaml:"allowed_key_types"` - DeniedExtensions []string `yaml:"denied_extensions"` + MaxTTLSeconds int `yaml:"max_ttl_seconds"` + AllowedKeyTypes []string `yaml:"allowed_key_types"` + DeniedExtensions []string `yaml:"denied_extensions"` + CertificateLimit CertificateLimitConfig `yaml:"certificate_limit"` +} + +type CertificateLimitConfig struct { + MaxPerUser int `yaml:"max_per_user"` + WindowSeconds int `yaml:"window_seconds"` } type ValidationConfig struct { @@ -121,8 +127,9 @@ func DefaultConfig() *Config { ReservedUsernames: []string{"root"}, LoginPort: 22, Policy: PolicyConfig{ - MaxTTLSeconds: 86400, - AllowedKeyTypes: []string{"ed25519", "rsa", "ecdsa"}, + MaxTTLSeconds: 86400, + AllowedKeyTypes: []string{"ed25519", "rsa", "ecdsa"}, + CertificateLimit: CertificateLimitConfig{MaxPerUser: 5, WindowSeconds: 3600}, }, Validation: ValidationConfig{ PrincipalValidator: "none", @@ -168,6 +175,9 @@ func (c *Config) Validate() error { if c.Signer.LoginHost == "" { return fmt.Errorf("login_host is required") } + if limit := c.Signer.Policy.CertificateLimit; limit.MaxPerUser < 1 || limit.WindowSeconds < 1 { + return fmt.Errorf("certificate_limit max_per_user and window_seconds must be at least 1") + } return nil } diff --git a/extensions/SSH-Certificate-Signer/internal/handler/sign.go b/extensions/SSH-Certificate-Signer/internal/handler/sign.go index 5c35a34bf..6c733a7bb 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/sign.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/sign.go @@ -67,10 +67,12 @@ type SignResponse struct { } type SignSettings struct { - ReservedUsernames []string - DeniedExtensions []string - LoginHost string - LoginPort int + ReservedUsernames []string + DeniedExtensions []string + LoginHost string + LoginPort int + CertificateLimit int + CertificateLimitWindow time.Duration } type SignHandler struct { @@ -166,6 +168,19 @@ func (h *SignHandler) Handle(w http.ResponseWriter, r *http.Request) { extensionsMap := cert.ExtensionsToMap(grantedExts) grantedExtNames := cert.ExtensionNames(grantedExts) + // Requests that arrive together can each pass this count, so a user can go a few over the limit. + issued, err := h.db.CountRecentCertificates(r.Context(), req.UserSub, h.settings.CertificateLimitWindow) + if err != nil { + h.logger.Error("failed to count recent certificates", "error", err) + writeError(w, http.StatusInternalServerError, "internal_error", "Failed to check the certificate limit") + return + } + if issued >= h.settings.CertificateLimit { + h.logRefusal(&req, "too_many_certificates") + writeError(w, http.StatusTooManyRequests, "too_many_certificates", "Too many certificates for this user. Try again later.") + return + } + valResult, err := h.principalValidator.Validate(r.Context(), req.Principal, req.UserSub) if err != nil { if valErr, ok := err.(*validation.ValidationError); ok { diff --git a/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go b/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go index 7bc1844b1..62a1c776a 100644 --- a/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go +++ b/extensions/SSH-Certificate-Signer/internal/store/issuance_log.go @@ -47,6 +47,17 @@ func (d *DB) NextSerial(ctx context.Context) (int64, error) { return serial, nil } +// CountRecentCertificates returns how many certificates the user was issued within the window. +// The cutoff uses the database clock, the same one that stamps issued_at. +func (d *DB) CountRecentCertificates(ctx context.Context, userSub string, window time.Duration) (int, error) { + var count int + if err := d.QueryRowContext(ctx, `SELECT COUNT(*) FROM certificate_issuance_logs WHERE user_sub = $1 AND issued_at > now() - make_interval(secs => $2)`, + userSub, window.Seconds()).Scan(&count); err != nil { + return 0, fmt.Errorf("counting certificates: %w", err) + } + return count, 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/main.go b/extensions/SSH-Certificate-Signer/main.go index 3e3f8c0cc..9cc399171 100644 --- a/extensions/SSH-Certificate-Signer/main.go +++ b/extensions/SSH-Certificate-Signer/main.go @@ -172,10 +172,12 @@ func runServer(cfg *config.Config, logger *slog.Logger, autoMigrate bool) { "cache_ttl_seconds", cfg.Signer.Validation.CacheTTLSeconds) signHandler := handler.NewSignHandler(policyEnforcer, principalValidator, vaultClient, db, auditLogger, handler.SignSettings{ - ReservedUsernames: cfg.Signer.ReservedUsernames, - DeniedExtensions: cfg.Signer.Policy.DeniedExtensions, - LoginHost: cfg.Signer.LoginHost, - LoginPort: cfg.Signer.LoginPort, + ReservedUsernames: cfg.Signer.ReservedUsernames, + DeniedExtensions: cfg.Signer.Policy.DeniedExtensions, + LoginHost: cfg.Signer.LoginHost, + LoginPort: cfg.Signer.LoginPort, + CertificateLimit: cfg.Signer.Policy.CertificateLimit.MaxPerUser, + CertificateLimitWindow: time.Duration(cfg.Signer.Policy.CertificateLimit.WindowSeconds) * time.Second, }, logger) caPublicKeyHandler := handler.NewCAPublicKeyHandler(vaultClient, logger) healthHandler := handler.NewHealthHandler(db, vaultClient)
