mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 20:51:30 +00:00
b3cc7cbdb2
D-008 was a three-part drift in the policy engine that made the
D-005/D-006 remediation cosmetic below the DB layer:
(a) migrations/seed.sql INSERTed rules with pre-D-005 lowercase
types ('ownership', 'environment', 'lifetime', 'renewal_window')
that the handler validator rejects on Create/Update but that
raw SQL INSERTs bypassed entirely. At runtime evaluateRule's
switch fell through to the default "unknown policy rule type"
error branch on every demo rule × every cert × every cycle,
flooding logs while emitting zero violations.
(b) migrations/seed_demo.sql persisted lowercase severity values
('critical', 'error', 'warning') on policy_violations rows.
INSERT succeeded because that column had no CHECK, but any
frontend comparing against the canonical PolicySeverity enum
mis-categorized every seeded violation.
(c) evaluateRule hardcoded Severity: PolicySeverityWarning on
every emitted violation and ignored rule.Config entirely —
so the D-006 per-rule severity column (000013) and every
per-arm Config JSON ({allowed_issuer_ids, allowed_domains,
required_keys, allowed, lead_time_days, max_days}) was dead
data below the evaluation layer.
This commit lands (a)+(b)+(c) atomically. Shipping any subset
leaves the feature half-working.
## Changes
Domain (internal/domain/policy.go):
* Add PolicyTypeCertificateLifetime as the 6th TitleCase canonical.
Pre-D-008 the seeded "max-certificate-lifetime" rule had no engine
arm — routing it through RenewalLeadTime would conflate "how
close to expiry before we renew" with "how long can the cert
possibly be", two distinct semantics. The new type accepts
config {"max_days": int} and flags certs whose
NotAfter - NotBefore exceeds the cap.
Handler validator (internal/api/handler/validation.go):
* ValidatePolicyType allowlist grown to 6 canonicals
(AllowedIssuers, AllowedDomains, RequiredMetadata,
AllowedEnvironments, RenewalLeadTime, CertificateLifetime).
OpenAPI (api/openapi.yaml):
* PolicyType enum grown to match domain.
Frontend (web/src/api/types.ts, types.test.ts):
* POLICY_TYPES tuple gains CertificateLifetime; pin test asserts
all 6 canonicals and rejects casing drift.
Migration 000014 (policy_violations severity CHECK):
* Named CHECK constraint (policy_violations_severity_check)
mirroring 000013's allowlist, defense-in-depth at the DB layer
against future drift from bypassed writes (migrations, psql
sessions, future callers). Symmetric down migration drops by
name.
Seed data:
* migrations/seed.sql rewritten to emit TitleCase canonicals with
per-arm config JSON that actually exercises the config-consuming
paths (not the missing-field backstops):
- pr-require-owner → RequiredMetadata {"required_keys":["owner"]} Warning
- pr-allowed-environments → AllowedEnvironments {"allowed":["production","staging","development"]} Error
- pr-max-certificate-lifetime → CertificateLifetime {"max_days":90} Critical
- pr-min-renewal-window → RenewalLeadTime {"lead_time_days":14} Warning
Severities are now differentiated per rule (D-006 intent).
* migrations/seed_demo.sql violation rows flipped to TitleCase
severity ('Critical', 'Error', 'Warning') so migration 000014
applies cleanly on upgrade paths.
Engine rewrite (internal/service/policy.go):
* evaluateRule rewritten. All six arms now:
1. Parse rule.Config into the per-arm typed struct.
2. Bad JSON → log at ValidateCertificate boundary and skip
this rule (no co-located poisoning of other rules in the
same batch).
3. Empty/null Config → emit the pre-D-008 missing-field
violation (backwards compat invariant — operators who
haven't reconfigured still see the same output).
4. Violations emitted carry rule.Severity (no more hardcoded
Warning); D-006 column is now load-bearing.
* CertificateLifetime arm reads NotBefore/NotAfter from the
certificate's latest version via CertRepo. Injected via
PolicyService.SetCertRepo() setter — avoids churning ~36
NewPolicyService call sites while keeping the lifetime arm
optional (degrades to a log+skip if the setter is not wired).
Server wiring (cmd/server/main.go):
* policyService.SetCertRepo(certRepo) wired after construction.
Tests (internal/service/policy_test.go):
* 25 new subtests across 5 groups:
- TestEvaluateRule_SeverityPassThrough (6): every rule type
emits violations carrying rule.Severity, not hardcoded.
- TestEvaluateRule_ConfigConsumed (12): every per-arm Config
path exercised positive + negative.
- TestEvaluateRule_EmptyConfig_BackCompat (3): empty/null
Config still emits pre-D-008 missing-field violations.
- TestEvaluateRule_BadConfig_SkipsRule: malformed JSON logs
and skips cleanly without poisoning neighbors.
- TestEvaluateRule_CertificateLifetime_RepoScenarios (3):
ok when repo wired, log+skip when not, handles missing
NotBefore/NotAfter edges.
Provenance: D-008 surfaced during D-005/D-006 remediation review
in eef1db0. That commit added persistence and CI pins for the
severity field but did not re-verify the evaluation layer
consumed it; this finding and fix close the audit-process gap.
146 lines
4.4 KiB
Go
146 lines
4.4 KiB
Go
package handler
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"net/mail"
|
|
"strings"
|
|
)
|
|
|
|
// ValidationError represents a validation error with field-level details.
|
|
type ValidationError struct {
|
|
Field string
|
|
Message string
|
|
}
|
|
|
|
// ValidateCommonName validates a certificate common name.
|
|
// Accepts hostnames (TLS), IP addresses, and email addresses (S/MIME).
|
|
func ValidateCommonName(cn string) error {
|
|
if cn == "" {
|
|
return ValidationError{Field: "common_name", Message: "common_name is required"}
|
|
}
|
|
if len(cn) > 253 {
|
|
return ValidationError{Field: "common_name", Message: "common_name must be 253 characters or fewer"}
|
|
}
|
|
// If CN contains @, validate as email address (S/MIME certificates)
|
|
if strings.Contains(cn, "@") {
|
|
if _, err := mail.ParseAddress(cn); err != nil {
|
|
return ValidationError{Field: "common_name", Message: fmt.Sprintf("invalid email format for S/MIME common name: %v", err)}
|
|
}
|
|
return nil
|
|
}
|
|
// Basic hostname validation: allow alphanumeric, dots, hyphens
|
|
if err := isValidHostname(cn); err != nil {
|
|
return ValidationError{Field: "common_name", Message: fmt.Sprintf("invalid hostname format: %v", err)}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ValidateRequired checks if a string field is present and non-empty.
|
|
func ValidateRequired(field, value string) error {
|
|
if value == "" {
|
|
return ValidationError{Field: field, Message: fmt.Sprintf("%s is required", field)}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ValidateStringLength checks if a string is within acceptable length bounds.
|
|
func ValidateStringLength(field, value string, maxLen int) error {
|
|
if len(value) > maxLen {
|
|
return ValidationError{Field: field, Message: fmt.Sprintf("%s must be %d characters or fewer", field, maxLen)}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ValidateCSRPEM validates a certificate signing request PEM block.
|
|
func ValidateCSRPEM(csrPEM string) error {
|
|
if csrPEM == "" {
|
|
return ValidationError{Field: "csr_pem", Message: "csr_pem is required"}
|
|
}
|
|
if !strings.HasPrefix(strings.TrimSpace(csrPEM), "-----BEGIN CERTIFICATE REQUEST-----") {
|
|
return ValidationError{Field: "csr_pem", Message: "csr_pem must be a valid PEM-encoded certificate request"}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ValidatePolicyType checks if a policy rule type is valid.
|
|
func ValidatePolicyType(policyType interface{}) error {
|
|
validTypes := map[string]bool{
|
|
"AllowedIssuers": true,
|
|
"AllowedDomains": true,
|
|
"RequiredMetadata": true,
|
|
"AllowedEnvironments": true,
|
|
"RenewalLeadTime": true,
|
|
"CertificateLifetime": true,
|
|
}
|
|
typeStr := fmt.Sprintf("%v", policyType)
|
|
if !validTypes[typeStr] {
|
|
return ValidationError{Field: "type", Message: "type must be one of: AllowedIssuers, AllowedDomains, RequiredMetadata, AllowedEnvironments, RenewalLeadTime, CertificateLifetime"}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ValidatePolicySeverity checks if a severity level is valid.
|
|
func ValidatePolicySeverity(severity interface{}) error {
|
|
validSeverities := map[string]bool{
|
|
"Warning": true,
|
|
"Error": true,
|
|
"Critical": true,
|
|
}
|
|
sevStr := fmt.Sprintf("%v", severity)
|
|
if !validSeverities[sevStr] {
|
|
return ValidationError{Field: "severity", Message: "severity must be one of: Warning, Error, Critical"}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// isValidHostname performs basic validation on a hostname.
|
|
func isValidHostname(hostname string) error {
|
|
// Use net.SplitHostPort-compatible check
|
|
// Hostname can be an IP or domain name
|
|
if ip := net.ParseIP(hostname); ip != nil {
|
|
return nil // Valid IP address
|
|
}
|
|
|
|
// For domain names, check basic format
|
|
if len(hostname) == 0 || len(hostname) > 253 {
|
|
return fmt.Errorf("hostname length invalid")
|
|
}
|
|
|
|
// Check for invalid characters (very basic)
|
|
for _, char := range hostname {
|
|
if !isValidHostnameChar(char) {
|
|
return fmt.Errorf("hostname contains invalid character: %c", char)
|
|
}
|
|
}
|
|
|
|
// Labels must not start or end with hyphen
|
|
labels := strings.Split(hostname, ".")
|
|
for _, label := range labels {
|
|
if len(label) == 0 {
|
|
return fmt.Errorf("hostname has empty label")
|
|
}
|
|
if strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
|
|
return fmt.Errorf("hostname labels cannot start or end with hyphen")
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// isValidHostnameChar checks if a character is valid in a hostname.
|
|
func isValidHostnameChar(r rune) bool {
|
|
return (r >= 'a' && r <= 'z') ||
|
|
(r >= 'A' && r <= 'Z') ||
|
|
(r >= '0' && r <= '9') ||
|
|
r == '.' ||
|
|
r == '-' ||
|
|
r == '_' || // Underscores are sometimes allowed
|
|
r == '*' // Wildcard support
|
|
}
|
|
|
|
// Error method makes ValidationError satisfy the error interface.
|
|
func (e ValidationError) Error() string {
|
|
return e.Message
|
|
}
|