package token import ( "errors" "fmt" "log/slog" "os" "strings" ) // DevOnlySigningKey is the in-memory fallback anchorage uses when no // signing keys are configured. It is long enough to satisfy the 32-byte // minimum but trivially predictable — intentionally so, so operators // notice the loud warning in logs and replace it. // // Never use this key in any environment that touches real data. const DevOnlySigningKey = "dev-only-do-not-use-in-production-0123456789abcdef" // readKeyFile reads a key file, strips a trailing newline, and enforces // the 32-byte minimum. Kept unexported — callers use LoadSigningKeys. // // Trailing newline handling means `openssl rand -base64 48 > jwt.key` // works without ceremony. func readKeyFile(path string) ([]byte, error) { raw, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("read signing key %s: %w", path, err) } key := []byte(strings.TrimRight(string(raw), "\r\n")) if len(key) < 32 { return nil, errors.New("signing key " + path + " is too short (need >= 32 bytes)") } return key, nil } // KeyFileSpec names a single signing key file on disk. Mirrors // config.SigningKeyConfig in a shape the token package can depend on // without importing config. type KeyFileSpec struct { Path string ID string Primary bool } // LoadSigningKeys validates and loads the rotation key set. // // - An empty slice returns a dev-only fallback (kid=DevKeyID, primary) // with a loud warning so operators notice they haven't configured // real keys. // - A non-empty slice is validated (unique non-empty IDs, exactly one // primary, 32-byte minimum on each file) and returned. // // Never returns an empty slice on success. func LoadSigningKeys(rotation []KeyFileSpec) ([]SigningKey, error) { if len(rotation) == 0 { slog.Warn("token: no signing keys configured — using the built-in dev key. DO NOT use in production.") return []SigningKey{{ ID: DevKeyID, Key: []byte(DevOnlySigningKey), Primary: true, }}, nil } out := make([]SigningKey, 0, len(rotation)) seen := map[string]bool{} primaries := 0 for i, spec := range rotation { if spec.ID == "" { return nil, fmt.Errorf("token: signingKeys[%d].id is required", i) } if spec.Path == "" { return nil, fmt.Errorf("token: signingKeys[%d].path is required", i) } if seen[spec.ID] { return nil, fmt.Errorf("token: duplicate signingKey id %q", spec.ID) } seen[spec.ID] = true key, err := readKeyFile(spec.Path) if err != nil { return nil, fmt.Errorf("token: signingKeys[%d] (%q): %w", i, spec.ID, err) } out = append(out, SigningKey{ID: spec.ID, Key: key, Primary: spec.Primary}) if spec.Primary { primaries++ } } if primaries != 1 { return nil, fmt.Errorf("token: exactly one signingKey must be marked primary (got %d)", primaries) } return out, nil }