package domain import ( "crypto/subtle" "errors" "fmt" "regexp" "time" "github.com/google/uuid" ) const maxPolicyAuthorLength = 128 var ( // ErrInvalidPolicyVersion reports version metadata that is missing or // malformed: the family, number, kind, author, or times. ErrInvalidPolicyVersion = errors.New("invalid policy version") // ErrPolicyDocumentIntegrity reports a stored document whose canonical // form no longer matches the stored SHA-256. The row was changed outside // the application. ErrPolicyDocumentIntegrity = errors.New("policy document does not match its hash") // "system:" or "operator:", as in the // policy_versions_author_format CHECK. The character set excludes "@", so // an email address cannot be stored as an author. policyAuthorPattern = regexp.MustCompile(`^(system|operator):[a-z0-9][a-z0-9._-]*$`) ) // PolicyVersionID identifies one stored policy version. Records built under // a policy, such as grade decisions, selection snapshots, and invitations, // store it in a policy_version_id column that references policy_versions.id. type PolicyVersionID uuid.UUID // NewPolicyVersionID returns a time-ordered UUIDv7. func NewPolicyVersionID() (PolicyVersionID, error) { id, err := uuid.NewV7() if err != nil { return PolicyVersionID{}, fmt.Errorf("domain.NewPolicyVersionID - generate ID: %w", err) } return PolicyVersionID(id), nil } func (id PolicyVersionID) UUID() uuid.UUID { return uuid.UUID(id) } func (id PolicyVersionID) String() string { return uuid.UUID(id).String() } func (id PolicyVersionID) IsZero() bool { return uuid.UUID(id) == uuid.Nil } // PolicyKey names a policy family. Each family has exactly one document // layout and decoder; ProductPolicyKey, decoded as ProductPolicy, is the only // family. A new family adds its type and decoder here and to the // policy_versions_policy_key_known CHECK. type PolicyKey string // ProductPolicyKey is the family of the product policy that product rules // read. const ProductPolicyKey PolicyKey = "product" // ParsePolicyKey accepts a known family. func ParsePolicyKey(value string) (PolicyKey, error) { if PolicyKey(value) != ProductPolicyKey { return "", invalidPolicyVersion("domain.ParsePolicyKey", "unknown policy family") } return ProductPolicyKey, nil } // PolicyKind is the calibration state of a whole version. type PolicyKind string const ( // PolicyKindDemo marks an initial policy for verification of the product // flow. Its values make no calibrated quality claim. PolicyKindDemo PolicyKind = "demo" // PolicyKindCalibrated marks a policy whose assessment section is backed // by a calibration. A calibrated version cannot carry an uncalibrated // assessment section. PolicyKindCalibrated PolicyKind = "calibrated" ) func ParsePolicyKind(value string) (PolicyKind, error) { kind := PolicyKind(value) switch kind { case PolicyKindDemo, PolicyKindCalibrated: return kind, nil default: return "", invalidPolicyVersion("domain.ParsePolicyKind", "kind must be demo or calibrated") } } // PolicyAuthor identifies who published a version: "system:" for an // automated publisher or "operator:" for a person. It is an operator // identity, never contact data. It is not a reference to users, because a // version must outlive the account and the seed has no account. type PolicyAuthor string // DemoPolicySeedAuthor publishes the demo product policy. const DemoPolicySeedAuthor PolicyAuthor = "system:demo-seed" func ParsePolicyAuthor(value string) (PolicyAuthor, error) { if len(value) > maxPolicyAuthorLength || !policyAuthorPattern.MatchString(value) { return "", invalidPolicyVersion("domain.ParsePolicyAuthor", "author must be system: or operator: of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'") } return PolicyAuthor(value), nil } // PolicyVersionDraft is a version that is not stored yet. It has an ID, a // validated policy, and its canonical document, but no publication time: // the database sets that when it stores the draft. Its number is assigned // with WithVersion before it is stored. type PolicyVersionDraft struct { id PolicyVersionID key PolicyKey version int32 kind PolicyKind author PolicyAuthor effectiveAt time.Time policy ProductPolicy document []byte documentHash PolicyDocumentHash } // NewPolicyVersionDraftInput describes a version to publish. A zero // EffectiveAt makes the version effective at publication; a set one schedules // it and must not be earlier than the publication time, which storage // enforces. type NewPolicyVersionDraftInput struct { Key PolicyKey Kind PolicyKind Author PolicyAuthor EffectiveAt time.Time Policy ProductPolicy } // NewPolicyVersionDraft validates input, encodes the canonical document with // its hash, and assigns a UUIDv7. The draft has no number yet. func NewPolicyVersionDraft(input NewPolicyVersionDraftInput) (PolicyVersionDraft, error) { const location = "domain.NewPolicyVersionDraft" if err := validateVersionIdentity(location, input.Key, input.Kind, input.Author); err != nil { return PolicyVersionDraft{}, err } if err := input.Policy.Validate(); err != nil { return PolicyVersionDraft{}, fmt.Errorf("%s - validate policy: %w", location, err) } if err := checkKindMatchesCalibration(location, input.Kind, input.Policy); err != nil { return PolicyVersionDraft{}, err } document, hash, err := encodeProductPolicy(input.Policy) if err != nil { return PolicyVersionDraft{}, err } id, err := NewPolicyVersionID() if err != nil { return PolicyVersionDraft{}, fmt.Errorf("%s - assign ID: %w", location, err) } return PolicyVersionDraft{ id: id, key: input.Key, kind: input.Kind, author: input.Author, effectiveAt: input.EffectiveAt, policy: input.Policy.clone(), document: document, documentHash: hash, }, nil } // WithVersion returns a copy of the draft with its number in the family. func (draft PolicyVersionDraft) WithVersion(number int32) (PolicyVersionDraft, error) { if draft.IsZero() { return PolicyVersionDraft{}, invalidPolicyVersion("PolicyVersionDraft.WithVersion", "draft was not built by NewPolicyVersionDraft") } if number <= 0 { return PolicyVersionDraft{}, invalidPolicyVersion("PolicyVersionDraft.WithVersion", "version must be positive") } numbered := draft numbered.version = number return numbered, nil } func (draft PolicyVersionDraft) ID() PolicyVersionID { return draft.id } func (draft PolicyVersionDraft) Key() PolicyKey { return draft.key } // Version is zero until WithVersion assigns the number. func (draft PolicyVersionDraft) Version() int32 { return draft.version } func (draft PolicyVersionDraft) Kind() PolicyKind { return draft.kind } func (draft PolicyVersionDraft) Author() PolicyAuthor { return draft.author } // EffectiveAt returns the scheduled effective time, or false when the // version becomes effective at publication. func (draft PolicyVersionDraft) EffectiveAt() (time.Time, bool) { return draft.effectiveAt, !draft.effectiveAt.IsZero() } // Policy returns a copy of the typed policy. func (draft PolicyVersionDraft) Policy() ProductPolicy { return draft.policy.clone() } // Document returns a copy of the canonical document. func (draft PolicyVersionDraft) Document() []byte { return append([]byte(nil), draft.document...) } func (draft PolicyVersionDraft) DocumentHash() PolicyDocumentHash { return draft.documentHash } // IsZero reports a draft not built by NewPolicyVersionDraft. func (draft PolicyVersionDraft) IsZero() bool { return draft.id.IsZero() } // PolicyVersion is one stored, immutable version of a policy family. Only // RestorePolicyVersion builds it; accessors return copies. type PolicyVersion struct { id PolicyVersionID key PolicyKey version int32 kind PolicyKind author PolicyAuthor effectiveAt time.Time createdAt time.Time policy ProductPolicy document []byte documentHash PolicyDocumentHash } // StoredPolicyVersion is a policy_versions row as storage reads it. type StoredPolicyVersion struct { ID PolicyVersionID Key string Version int32 Kind string Author string EffectiveAt time.Time CreatedAt time.Time Document []byte DocumentHash []byte } // RestorePolicyVersion rebuilds a stored version. It decodes the document // strictly, validates it like NewPolicyVersionDraft, and requires the SHA-256 // of its canonical re-encoding to equal the stored hash; otherwise it returns // ErrPolicyDocumentIntegrity. jsonb normalizes the stored text, so the hash // is never compared with the stored bytes directly. func RestorePolicyVersion(stored StoredPolicyVersion) (PolicyVersion, error) { const location = "domain.RestorePolicyVersion" if stored.ID.IsZero() { return PolicyVersion{}, invalidPolicyVersion(location, "ID must not be nil") } key, err := ParsePolicyKey(stored.Key) if err != nil { return PolicyVersion{}, fmt.Errorf("%s - parse key: %w", location, err) } kind, err := ParsePolicyKind(stored.Kind) if err != nil { return PolicyVersion{}, fmt.Errorf("%s - parse kind: %w", location, err) } author, err := ParsePolicyAuthor(stored.Author) if err != nil { return PolicyVersion{}, fmt.Errorf("%s - parse author: %w", location, err) } switch { case stored.Version <= 0: return PolicyVersion{}, invalidPolicyVersion(location, "version must be positive") case stored.CreatedAt.IsZero() || stored.EffectiveAt.IsZero(): return PolicyVersion{}, invalidPolicyVersion(location, "creation and effective times must be set") case stored.EffectiveAt.Before(stored.CreatedAt): return PolicyVersion{}, invalidPolicyVersion(location, "effective time must not be earlier than the creation time") } policy, err := decodeProductPolicy(stored.Document) if err != nil { return PolicyVersion{}, fmt.Errorf("%s - decode document: %w", location, err) } if err := policy.Validate(); err != nil { return PolicyVersion{}, fmt.Errorf("%s - validate policy: %w", location, err) } if err := checkKindMatchesCalibration(location, kind, policy); err != nil { return PolicyVersion{}, err } document, hash, err := encodeProductPolicy(policy) if err != nil { return PolicyVersion{}, err } if len(stored.DocumentHash) != len(hash) || subtle.ConstantTimeCompare(stored.DocumentHash, hash[:]) != 1 { return PolicyVersion{}, fmt.Errorf("%s - verify document hash: %w", location, ErrPolicyDocumentIntegrity) } return PolicyVersion{ id: stored.ID, key: key, version: stored.Version, kind: kind, author: author, effectiveAt: stored.EffectiveAt, createdAt: stored.CreatedAt, policy: policy, document: document, documentHash: hash, }, nil } func validateVersionIdentity(location string, key PolicyKey, kind PolicyKind, author PolicyAuthor) error { if _, err := ParsePolicyKey(string(key)); err != nil { return fmt.Errorf("%s - validate key: %w", location, err) } if _, err := ParsePolicyKind(string(kind)); err != nil { return fmt.Errorf("%s - validate kind: %w", location, err) } if _, err := ParsePolicyAuthor(string(author)); err != nil { return fmt.Errorf("%s - validate author: %w", location, err) } return nil } func checkKindMatchesCalibration(location string, kind PolicyKind, policy ProductPolicy) error { if kind == PolicyKindCalibrated && policy.Assessment.Calibration != AssessmentCalibrationCalibrated { return invalidPolicyVersion(location, "a calibrated version requires a calibrated assessment section") } return nil } func invalidPolicyVersion(location, reason string) error { return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidPolicyVersion) } func (version PolicyVersion) ID() PolicyVersionID { return version.id } func (version PolicyVersion) Key() PolicyKey { return version.key } // Version is the number of the version within its family, starting at 1. func (version PolicyVersion) Version() int32 { return version.version } // Kind is the calibration state of the whole version. Consumers that make or // report a quality claim read this flag; the assessment section's own marker // always agrees with it for calibrated versions. func (version PolicyVersion) Kind() PolicyKind { return version.kind } func (version PolicyVersion) Author() PolicyAuthor { return version.author } func (version PolicyVersion) EffectiveAt() time.Time { return version.effectiveAt } // CreatedAt is the publication time from the database clock. func (version PolicyVersion) CreatedAt() time.Time { return version.createdAt } // Policy returns a copy of the typed policy. func (version PolicyVersion) Policy() ProductPolicy { return version.policy.clone() } // Document returns a copy of the canonical document. func (version PolicyVersion) Document() []byte { return append([]byte(nil), version.document...) } func (version PolicyVersion) DocumentHash() PolicyDocumentHash { return version.documentHash } // IsZero reports a PolicyVersion not built by RestorePolicyVersion. func (version PolicyVersion) IsZero() bool { return version.id.IsZero() }