feat(policy): add immutable versioned product policy store

This commit is contained in:
shira committed 2026-10-06 01:52:39 +03:00
1 parent 0e2a3b02ab
commit 7a5105acc7
30 files changed
+3893 -37

No files matched your search

+415
View File
@@ -0,0 +1,415 @@
package domain
import (
"errors"
"fmt"
"slices"
"time"
)
// ErrInvalidPolicy reports a policy value that is missing, out of range, or
// inconsistent with another value of the same policy.
var ErrInvalidPolicy = errors.New("invalid policy")
// Units of policy values. Every value carries its unit in its type and in its
// document field name, so a number never changes meaning between code and
// storage.
type (
// CalendarDays counts whole days of 24 hours. Duration does not follow
// daylight saving shifts; deadlines are computed in UTC.
CalendarDays int32
// BusinessDays counts working days. Converting it to a deadline needs a
// business calendar, which the consuming feature defines, so it has no
// Duration method.
BusinessDays int32
// Hours counts whole hours.
Hours int32
// BasisPoints is a non-negative decimal with four fractional digits,
// stored as an integer count of 0.0001 units: 0.80 is 8000. Thresholds
// compare exactly, without the drift of binary floating point, and the
// document keeps an integer that every JSON reader decodes the same way.
BasisPoints int32
)
// basisPointsPerUnit is the BasisPoints value of 1.0.
const basisPointsPerUnit BasisPoints = 10000
func (days CalendarDays) Duration() time.Duration { return time.Duration(days) * 24 * time.Hour }
func (hours Hours) Duration() time.Duration { return time.Duration(hours) * time.Hour }
// String formats the value as a decimal, for example "0.8000".
func (points BasisPoints) String() string {
return fmt.Sprintf("%d.%04d", points/basisPointsPerUnit, points%basisPointsPerUnit)
}
// Sanity bounds of policy values. They reject typing mistakes such as a
// value in the wrong unit; they are not product decisions, which the policy
// values themselves record.
const (
maxResponseDeadlineOptions = 5
maxResponseDeadline = CalendarDays(30)
maxPendingInvitationsPerNeed = 1000
maxRepeatAfterDecline = CalendarDays(365)
maxInterviewProposalDeadline = BusinessDays(30)
maxNoDealPause = CalendarDays(365)
maxInvitationQuotaWindow = CalendarDays(31)
maxCardViewQuotaWindow = Hours(7 * 24)
maxTierQuotaLimit = 100000
maxSameGradeRetryInterval = CalendarDays(365)
maxAssessmentAttemptsPerWindow = 20
maxAssessmentAttemptWindow = CalendarDays(730)
maxPromotionInterval = CalendarDays(730)
maxScoredItems = 200
maxSeedItems = 20
maxVerificationTokenLifetime = Hours(7 * 24)
maxUnverifiedAccountLifetime = CalendarDays(90)
maxSessionIdleTimeout = Hours(30 * 24)
maxSessionAbsoluteLifetime = CalendarDays(90)
maxSearchingConfirmationInterval = CalendarDays(365)
minExclusiveProbabilityBasisPoints = BasisPoints(1)
maxExclusiveProbabilityBasisPoints = basisPointsPerUnit - 1
minPositiveStandardErrorBasisPoints = BasisPoints(1)
)
// ProductPolicy holds the deadlines, quotas, thresholds, and coefficients
// that product rules read. A stored policy is immutable: a change is a new
// PolicyVersion, and records built under a policy keep the version they used.
type ProductPolicy struct {
Invitations InvitationPolicy
OrganizationQuotas OrganizationQuotaPolicy
Assessment AssessmentPolicy
Identity IdentityPolicy
SearchStatus SearchStatusPolicy
}
// Validate checks every section. A zero value is never valid, so a section
// that was left out fails instead of silently meaning zero.
func (policy ProductPolicy) Validate() error {
for _, validate := range []func() error{
policy.Invitations.Validate,
policy.OrganizationQuotas.Validate,
policy.Assessment.Validate,
policy.Identity.Validate,
policy.SearchStatus.Validate,
} {
if err := validate(); err != nil {
return err
}
}
return nil
}
// clone copies the slices, so a caller cannot change a stored version through
// a returned policy.
func (policy ProductPolicy) clone() ProductPolicy {
copied := policy
copied.Invitations.ResponseDeadlineOptions = slices.Clone(policy.Invitations.ResponseDeadlineOptions)
return copied
}
// InvitationPolicy governs salary offers sent to candidates.
type InvitationPolicy struct {
// ResponseDeadlineOptions are the response deadlines an employer may
// choose, in strictly increasing order.
ResponseDeadlineOptions []CalendarDays
// DefaultResponseDeadline is one of ResponseDeadlineOptions.
DefaultResponseDeadline CalendarDays
// MaxPendingPerNeed limits unanswered invitations for one employer need.
MaxPendingPerNeed int32
// RepeatAfterDecline is the pause before the same company may invite a
// candidate who declined.
RepeatAfterDecline CalendarDays
// InterviewProposalDeadline is the time the employer has to propose an
// interview after acceptance.
InterviewProposalDeadline BusinessDays
// NoDealPause is the pause after a contact that ended without a deal.
NoDealPause CalendarDays
}
func (policy InvitationPolicy) Validate() error {
const location = "InvitationPolicy.Validate"
options := policy.ResponseDeadlineOptions
if len(options) == 0 || len(options) > maxResponseDeadlineOptions {
return invalidPolicy(location, fmt.Sprintf("invitations.response_deadline_options_days must have 1 to %d values", maxResponseDeadlineOptions))
}
for index, option := range options {
if err := checkRange(location, "invitations.response_deadline_options_days", option, 1, maxResponseDeadline); err != nil {
return err
}
if index > 0 && option <= options[index-1] {
return invalidPolicy(location, "invitations.response_deadline_options_days must be strictly increasing")
}
}
if !slices.Contains(options, policy.DefaultResponseDeadline) {
return invalidPolicy(location, "invitations.default_response_deadline_days must be one of the response deadline options")
}
return firstError(
checkRange(location, "invitations.max_pending_per_need", policy.MaxPendingPerNeed, 1, maxPendingInvitationsPerNeed),
checkRange(location, "invitations.repeat_after_decline_days", policy.RepeatAfterDecline, 1, maxRepeatAfterDecline),
checkRange(location, "invitations.interview_proposal_deadline_business_days", policy.InterviewProposalDeadline, 1, maxInterviewProposalDeadline),
checkRange(location, "invitations.no_deal_pause_days", policy.NoDealPause, 1, maxNoDealPause),
)
}
// OrganizationTier is an employer trust level. Levels are ordered E0 < E1 <
// E2; the rules that move an organization between them belong to the quota
// feature, not to the policy. E0 is the level every organization starts at.
type OrganizationTier string
const (
OrganizationTierE0 OrganizationTier = "e0"
OrganizationTierE1 OrganizationTier = "e1"
OrganizationTierE2 OrganizationTier = "e2"
)
// ParseOrganizationTier accepts e0, e1, or e2.
func ParseOrganizationTier(value string) (OrganizationTier, error) {
tier := OrganizationTier(value)
switch tier {
case OrganizationTierE0, OrganizationTierE1, OrganizationTierE2:
return tier, nil
default:
return "", invalidPolicy("domain.ParseOrganizationTier", "tier must be e0, e1, or e2")
}
}
// OrganizationQuotaPolicy limits employer activity per trust level. Limits
// apply per rolling window.
type OrganizationQuotaPolicy struct {
InvitationWindow CalendarDays
CardViewWindow Hours
TierE0 OrganizationTierQuota
TierE1 OrganizationTierQuota
TierE2 OrganizationTierQuota
}
// OrganizationTierQuota is the quota of one level. An inactive level keeps
// its limits for the time it is enabled, but no organization can hold it
// before that. E0 is always active, and the active levels form a prefix: a
// level is active only when every lower level is.
type OrganizationTierQuota struct {
Active bool
InvitationsPerWindow int32
DistinctCardViewsPerWindow int32
}
// Tier returns the quota of a level. An unknown level returns
// ErrInvalidPolicy; callers check Active before assigning a level.
func (policy OrganizationQuotaPolicy) Tier(tier OrganizationTier) (OrganizationTierQuota, error) {
switch tier {
case OrganizationTierE0:
return policy.TierE0, nil
case OrganizationTierE1:
return policy.TierE1, nil
case OrganizationTierE2:
return policy.TierE2, nil
default:
return OrganizationTierQuota{}, invalidPolicy("OrganizationQuotaPolicy.Tier", "tier must be e0, e1, or e2")
}
}
func (policy OrganizationQuotaPolicy) Validate() error {
const location = "OrganizationQuotaPolicy.Validate"
if err := firstError(
checkRange(location, "organization_quotas.invitation_window_days", policy.InvitationWindow, 1, maxInvitationQuotaWindow),
checkRange(location, "organization_quotas.card_view_window_hours", policy.CardViewWindow, 1, maxCardViewQuotaWindow),
); err != nil {
return err
}
if !policy.TierE0.Active {
return invalidPolicy(location, "organization_quotas.tiers.e0 must be active, because every organization starts there")
}
tiers := []struct {
name OrganizationTier
quota OrganizationTierQuota
}{
{name: OrganizationTierE0, quota: policy.TierE0},
{name: OrganizationTierE1, quota: policy.TierE1},
{name: OrganizationTierE2, quota: policy.TierE2},
}
// The zero quota is below every valid limit and counts as active, so the
// lowest level passes the ordering checks.
lower := OrganizationTierQuota{Active: true}
for _, tier := range tiers {
prefix := "organization_quotas.tiers." + string(tier.name)
if err := firstError(
checkRange(location, prefix+".invitations_per_window", tier.quota.InvitationsPerWindow, 1, maxTierQuotaLimit),
checkRange(location, prefix+".distinct_card_views_per_window", tier.quota.DistinctCardViewsPerWindow, 1, maxTierQuotaLimit),
); err != nil {
return err
}
if tier.quota.Active && !lower.Active {
return invalidPolicy(location, prefix+" cannot be active while a lower tier is inactive")
}
// A higher level is granted after more trust, so it never has a
// smaller limit than the level below it.
if tier.quota.InvitationsPerWindow < lower.InvitationsPerWindow ||
tier.quota.DistinctCardViewsPerWindow < lower.DistinctCardViewsPerWindow {
return invalidPolicy(location, prefix+" limits must not be lower than the tier below")
}
lower = tier.quota
}
return nil
}
// AssessmentCalibration records whether assessment thresholds come from a
// calibration study.
type AssessmentCalibration string
const (
// AssessmentCalibrationUncalibratedInitial marks initial values chosen for
// verification of the product flow. They make no psychometric claim.
AssessmentCalibrationUncalibratedInitial AssessmentCalibration = "uncalibrated_initial"
// AssessmentCalibrationCalibrated marks values backed by a pilot and a
// documented calibration.
AssessmentCalibrationCalibrated AssessmentCalibration = "calibrated"
)
// AssessmentPolicy governs grade assessment attempts and decisions. P_G is
// the estimated probability that the candidate meets the claimed grade.
type AssessmentPolicy struct {
Calibration AssessmentCalibration
// SameGradeRetryAfter is the pause before another attempt at the same
// grade.
SameGradeRetryAfter CalendarDays
// MaxAttemptsPerWindow limits attempts in any AttemptWindow. Whether the
// limit counts per grade, per specialty, or across all assessments of a
// candidate is an open question for the attempt tasks (TASK-157 and
// TASK-158); the policy stores only the number.
MaxAttemptsPerWindow int32
AttemptWindow CalendarDays
// PromotionMinInterval is the minimum time between grade promotions.
PromotionMinInterval CalendarDays
// ConfirmationThreshold is the lowest P_G that confirms the grade.
ConfirmationThreshold BasisPoints
// HighStrengthThreshold is the lowest P_G reported as a strong result.
HighStrengthThreshold BasisPoints
// PracticeRequired makes the unscored practice block mandatory before a
// scored attempt.
PracticeRequired bool
StopRule AssessmentStopRule
}
// AssessmentStopRule ends an adaptive attempt. After MinScoredItems the
// attempt stops when P_G reaches UpperProbability or falls to
// LowerProbability, or when the standard error is at most MaxStandardError;
// it always stops after MaxScoredItems. SeedItems are unscored items for
// collecting statistics on new tasks and come on top of the scored ones.
type AssessmentStopRule struct {
MinScoredItems int32
MaxScoredItems int32
SeedItems int32
UpperProbability BasisPoints
LowerProbability BasisPoints
MaxStandardError BasisPoints
}
func (policy AssessmentPolicy) Validate() error {
const location = "AssessmentPolicy.Validate"
switch policy.Calibration {
case AssessmentCalibrationUncalibratedInitial, AssessmentCalibrationCalibrated:
default:
return invalidPolicy(location, "assessment.calibration must be uncalibrated_initial or calibrated")
}
if err := firstError(
checkRange(location, "assessment.same_grade_retry_after_days", policy.SameGradeRetryAfter, 1, maxSameGradeRetryInterval),
checkRange(location, "assessment.max_attempts_per_window", policy.MaxAttemptsPerWindow, 1, maxAssessmentAttemptsPerWindow),
checkRange(location, "assessment.attempt_window_days", policy.AttemptWindow, 1, maxAssessmentAttemptWindow),
checkRange(location, "assessment.promotion_min_interval_days", policy.PromotionMinInterval, 1, maxPromotionInterval),
checkProbability(location, "assessment.confirmation_threshold_bp", policy.ConfirmationThreshold),
checkProbability(location, "assessment.high_strength_threshold_bp", policy.HighStrengthThreshold),
); err != nil {
return err
}
if policy.HighStrengthThreshold < policy.ConfirmationThreshold {
return invalidPolicy(location, "assessment.high_strength_threshold_bp must not be below the confirmation threshold")
}
return policy.StopRule.validate(location, policy.ConfirmationThreshold)
}
func (rule AssessmentStopRule) validate(location string, confirmation BasisPoints) error {
if err := firstError(
checkRange(location, "assessment.stop_rule.min_scored_items", rule.MinScoredItems, 1, maxScoredItems),
checkRange(location, "assessment.stop_rule.max_scored_items", rule.MaxScoredItems, rule.MinScoredItems, maxScoredItems),
checkRange(location, "assessment.stop_rule.seed_items", rule.SeedItems, 0, maxSeedItems),
checkProbability(location, "assessment.stop_rule.upper_probability_bp", rule.UpperProbability),
checkProbability(location, "assessment.stop_rule.lower_probability_bp", rule.LowerProbability),
checkRange(location, "assessment.stop_rule.max_standard_error_bp", rule.MaxStandardError, minPositiveStandardErrorBasisPoints, basisPointsPerUnit),
); err != nil {
return err
}
// An attempt must be able to stop above the confirmation threshold and
// below it; otherwise an early stop could never confirm or never reject.
if rule.LowerProbability >= confirmation || rule.UpperProbability < confirmation {
return invalidPolicy(location, "assessment.stop_rule probabilities must satisfy lower < confirmation threshold <= upper")
}
return nil
}
// IdentityPolicy holds the account and session lifetimes of the identity
// contract.
type IdentityPolicy struct {
VerificationTokenLifetime Hours
// UnverifiedAccountLifetime counts from the latest registration.
UnverifiedAccountLifetime CalendarDays
SessionIdleTimeout Hours
SessionAbsoluteLifetime CalendarDays
}
func (policy IdentityPolicy) Validate() error {
const location = "IdentityPolicy.Validate"
if err := firstError(
checkRange(location, "identity.verification_token_lifetime_hours", policy.VerificationTokenLifetime, 1, maxVerificationTokenLifetime),
checkRange(location, "identity.unverified_account_lifetime_days", policy.UnverifiedAccountLifetime, 1, maxUnverifiedAccountLifetime),
checkRange(location, "identity.session_idle_timeout_hours", policy.SessionIdleTimeout, 1, maxSessionIdleTimeout),
checkRange(location, "identity.session_absolute_lifetime_days", policy.SessionAbsoluteLifetime, 1, maxSessionAbsoluteLifetime),
); err != nil {
return err
}
if policy.SessionIdleTimeout.Duration() > policy.SessionAbsoluteLifetime.Duration() {
return invalidPolicy(location, "identity.session_idle_timeout_hours must not exceed the absolute session lifetime")
}
return nil
}
// SearchStatusPolicy governs the candidate "searching" status.
type SearchStatusPolicy struct {
// SearchingConfirmationInterval is how often a candidate confirms that
// the "searching" status is still current.
SearchingConfirmationInterval CalendarDays
}
func (policy SearchStatusPolicy) Validate() error {
return checkRange("SearchStatusPolicy.Validate", "search_status.searching_confirmation_interval_days",
policy.SearchingConfirmationInterval, 1, maxSearchingConfirmationInterval)
}
func checkRange[T ~int32](location, field string, value, minimum, maximum T) error {
if value < minimum || value > maximum {
return invalidPolicy(location, fmt.Sprintf("%s must be between %d and %d", field, minimum, maximum))
}
return nil
}
// checkProbability accepts a probability strictly between 0 and 1: a
// threshold of 0 or 1 would make a rule always or never apply.
func checkProbability(location, field string, value BasisPoints) error {
return checkRange(location, field, value, minExclusiveProbabilityBasisPoints, maxExclusiveProbabilityBasisPoints)
}
func invalidPolicy(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidPolicy)
}
func firstError(errs ...error) error {
for _, err := range errs {
if err != nil {
return err
}
}
return nil
}
+62
View File
@@ -0,0 +1,62 @@
package domain
// DemoProductPolicyV1 returns the initial product policy that is published as
// version 1 of ProductPolicyKey with PolicyKindDemo. Its values are the agreed
// starting rules for verifying the product flow, not results of a study: the
// assessment section is marked AssessmentCalibrationUncalibratedInitial, and
// its thresholds and stop rule make no psychometric or quality claim until a
// pilot calibrates them and a calibrated version is published.
//
// The policy holds rules only. Assessment content, such as the task bank,
// blueprints, and variants, is separate work and is not part of it.
//
// Tests must not use this policy as a fixture for other values; they build
// their own policies under their own keys.
func DemoProductPolicyV1() ProductPolicy {
return ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: []CalendarDays{3, 7, 14},
DefaultResponseDeadline: 7,
MaxPendingPerNeed: 20,
RepeatAfterDecline: 30,
InterviewProposalDeadline: 5,
NoDealPause: 30,
},
OrganizationQuotas: OrganizationQuotaPolicy{
InvitationWindow: 7,
CardViewWindow: 24,
TierE0: OrganizationTierQuota{Active: true, InvitationsPerWindow: 10, DistinctCardViewsPerWindow: 50},
TierE1: OrganizationTierQuota{Active: true, InvitationsPerWindow: 40, DistinctCardViewsPerWindow: 150},
// E2 stays inactive until the organization verification that
// grants it exists.
TierE2: OrganizationTierQuota{Active: false, InvitationsPerWindow: 100, DistinctCardViewsPerWindow: 400},
},
Assessment: AssessmentPolicy{
Calibration: AssessmentCalibrationUncalibratedInitial,
SameGradeRetryAfter: 30,
MaxAttemptsPerWindow: 3,
AttemptWindow: 180,
PromotionMinInterval: 90,
ConfirmationThreshold: 8000,
HighStrengthThreshold: 9000,
PracticeRequired: true,
StopRule: AssessmentStopRule{
MinScoredItems: 8,
MaxScoredItems: 23,
SeedItems: 2,
UpperProbability: 9000,
LowerProbability: 1000,
MaxStandardError: 2500,
},
},
Identity: IdentityPolicy{
VerificationTokenLifetime: 24,
UnverifiedAccountLifetime: 7,
SessionIdleTimeout: 24,
SessionAbsoluteLifetime: 7,
},
SearchStatus: SearchStatusPolicy{
SearchingConfirmationInterval: 30,
},
}
}
+275
View File
@@ -0,0 +1,275 @@
package domain
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
)
const (
// productPolicySchemaVersion is the layout of the stored document. A new
// layout adds a decoder for its version; stored versions are never
// rewritten.
productPolicySchemaVersion = 1
// maxPolicyDocumentBytes bounds a document before decoding. The current
// layout encodes to well under 2 KiB.
maxPolicyDocumentBytes = 64 << 10
)
// PolicyDocumentHash is the SHA-256 of the canonical policy document.
type PolicyDocumentHash [sha256.Size]byte
// The document types mirror ProductPolicy field by field. Every field is a
// pointer, so the decoder can tell a missing field from a zero value: a
// missing field is an error, never a default. Field names carry their unit.
type productPolicyDocument struct {
SchemaVersion *int32 `json:"schema_version"`
Invitations *invitationPolicyDocument `json:"invitations"`
OrganizationQuotas *organizationQuotaDocument `json:"organization_quotas"`
Assessment *assessmentPolicyDocument `json:"assessment"`
Identity *identityPolicyDocument `json:"identity"`
SearchStatus *searchStatusDocument `json:"search_status"`
}
type invitationPolicyDocument struct {
ResponseDeadlineOptionsDays *[]CalendarDays `json:"response_deadline_options_days"`
DefaultResponseDeadlineDays *CalendarDays `json:"default_response_deadline_days"`
MaxPendingPerNeed *int32 `json:"max_pending_per_need"`
RepeatAfterDeclineDays *CalendarDays `json:"repeat_after_decline_days"`
InterviewProposalDeadlineBusinessDays *BusinessDays `json:"interview_proposal_deadline_business_days"`
NoDealPauseDays *CalendarDays `json:"no_deal_pause_days"`
}
type organizationQuotaDocument struct {
InvitationWindowDays *CalendarDays `json:"invitation_window_days"`
CardViewWindowHours *Hours `json:"card_view_window_hours"`
Tiers *organizationTiersDocument `json:"tiers"`
}
type organizationTiersDocument struct {
E0 *organizationTierQuotaDocument `json:"e0"`
E1 *organizationTierQuotaDocument `json:"e1"`
E2 *organizationTierQuotaDocument `json:"e2"`
}
type organizationTierQuotaDocument struct {
Active *bool `json:"active"`
InvitationsPerWindow *int32 `json:"invitations_per_window"`
DistinctCardViewsPerWindow *int32 `json:"distinct_card_views_per_window"`
}
type assessmentPolicyDocument struct {
Calibration *AssessmentCalibration `json:"calibration"`
SameGradeRetryAfterDays *CalendarDays `json:"same_grade_retry_after_days"`
MaxAttemptsPerWindow *int32 `json:"max_attempts_per_window"`
AttemptWindowDays *CalendarDays `json:"attempt_window_days"`
PromotionMinIntervalDays *CalendarDays `json:"promotion_min_interval_days"`
ConfirmationThresholdBP *BasisPoints `json:"confirmation_threshold_bp"`
HighStrengthThresholdBP *BasisPoints `json:"high_strength_threshold_bp"`
PracticeRequired *bool `json:"practice_required"`
StopRule *assessmentStopDocument `json:"stop_rule"`
}
type assessmentStopDocument struct {
MinScoredItems *int32 `json:"min_scored_items"`
MaxScoredItems *int32 `json:"max_scored_items"`
SeedItems *int32 `json:"seed_items"`
UpperProbabilityBP *BasisPoints `json:"upper_probability_bp"`
LowerProbabilityBP *BasisPoints `json:"lower_probability_bp"`
MaxStandardErrorBP *BasisPoints `json:"max_standard_error_bp"`
}
type identityPolicyDocument struct {
VerificationTokenLifetimeHours *Hours `json:"verification_token_lifetime_hours"`
UnverifiedAccountLifetimeDays *CalendarDays `json:"unverified_account_lifetime_days"`
SessionIdleTimeoutHours *Hours `json:"session_idle_timeout_hours"`
SessionAbsoluteLifetimeDays *CalendarDays `json:"session_absolute_lifetime_days"`
}
type searchStatusDocument struct {
SearchingConfirmationIntervalDays *CalendarDays `json:"searching_confirmation_interval_days"`
}
// encodeProductPolicy returns the canonical document: compact JSON with the
// fields in declaration order. The same policy always encodes to the same
// bytes, which makes the document hash deterministic.
func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, error) {
invitations := policy.Invitations
quotas := policy.OrganizationQuotas
assessment := policy.Assessment
identity := policy.Identity
document := productPolicyDocument{
SchemaVersion: pointer(int32(productPolicySchemaVersion)),
Invitations: &invitationPolicyDocument{
ResponseDeadlineOptionsDays: pointer(invitations.ResponseDeadlineOptions),
DefaultResponseDeadlineDays: pointer(invitations.DefaultResponseDeadline),
MaxPendingPerNeed: pointer(invitations.MaxPendingPerNeed),
RepeatAfterDeclineDays: pointer(invitations.RepeatAfterDecline),
InterviewProposalDeadlineBusinessDays: pointer(invitations.InterviewProposalDeadline),
NoDealPauseDays: pointer(invitations.NoDealPause),
},
OrganizationQuotas: &organizationQuotaDocument{
InvitationWindowDays: pointer(quotas.InvitationWindow),
CardViewWindowHours: pointer(quotas.CardViewWindow),
Tiers: &organizationTiersDocument{
E0: encodeTierQuota(quotas.TierE0),
E1: encodeTierQuota(quotas.TierE1),
E2: encodeTierQuota(quotas.TierE2),
},
},
Assessment: &assessmentPolicyDocument{
Calibration: pointer(assessment.Calibration),
SameGradeRetryAfterDays: pointer(assessment.SameGradeRetryAfter),
MaxAttemptsPerWindow: pointer(assessment.MaxAttemptsPerWindow),
AttemptWindowDays: pointer(assessment.AttemptWindow),
PromotionMinIntervalDays: pointer(assessment.PromotionMinInterval),
ConfirmationThresholdBP: pointer(assessment.ConfirmationThreshold),
HighStrengthThresholdBP: pointer(assessment.HighStrengthThreshold),
PracticeRequired: pointer(assessment.PracticeRequired),
StopRule: &assessmentStopDocument{
MinScoredItems: pointer(assessment.StopRule.MinScoredItems),
MaxScoredItems: pointer(assessment.StopRule.MaxScoredItems),
SeedItems: pointer(assessment.StopRule.SeedItems),
UpperProbabilityBP: pointer(assessment.StopRule.UpperProbability),
LowerProbabilityBP: pointer(assessment.StopRule.LowerProbability),
MaxStandardErrorBP: pointer(assessment.StopRule.MaxStandardError),
},
},
Identity: &identityPolicyDocument{
VerificationTokenLifetimeHours: pointer(identity.VerificationTokenLifetime),
UnverifiedAccountLifetimeDays: pointer(identity.UnverifiedAccountLifetime),
SessionIdleTimeoutHours: pointer(identity.SessionIdleTimeout),
SessionAbsoluteLifetimeDays: pointer(identity.SessionAbsoluteLifetime),
},
SearchStatus: &searchStatusDocument{
SearchingConfirmationIntervalDays: pointer(policy.SearchStatus.SearchingConfirmationInterval),
},
}
encoded, err := json.Marshal(document)
if err != nil {
return nil, PolicyDocumentHash{}, fmt.Errorf("domain.encodeProductPolicy - marshal document: %w", err)
}
return encoded, sha256.Sum256(encoded), nil
}
func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument {
return &organizationTierQuotaDocument{
Active: pointer(quota.Active),
InvitationsPerWindow: pointer(quota.InvitationsPerWindow),
DistinctCardViewsPerWindow: pointer(quota.DistinctCardViewsPerWindow),
}
}
// decodeProductPolicy reads a document strictly: it rejects unknown fields,
// missing fields, null values, values of the wrong type or out of the int32
// range, an unknown schema version, and trailing data. It checks structure
// only; ProductPolicy.Validate checks the values. encoding/json matches field
// names without regard to letter case and keeps the last of duplicate keys;
// the document hash, computed over the canonical re-encoding, is what pins
// the content.
func decodeProductPolicy(document []byte) (ProductPolicy, error) {
const location = "domain.decodeProductPolicy"
if len(document) > maxPolicyDocumentBytes {
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("document must have at most %d bytes", maxPolicyDocumentBytes))
}
decoder := json.NewDecoder(bytes.NewReader(document))
decoder.DisallowUnknownFields()
var parsed productPolicyDocument
if err := decoder.Decode(&parsed); err != nil {
return ProductPolicy{}, fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return ProductPolicy{}, invalidPolicy(location, "document must contain one JSON object")
}
reader := documentReader{}
if version := require(&reader, "schema_version", parsed.SchemaVersion); reader.missing == "" && version != productPolicySchemaVersion {
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d", productPolicySchemaVersion))
}
invitations := require(&reader, "invitations", parsed.Invitations)
quotas := require(&reader, "organization_quotas", parsed.OrganizationQuotas)
tiers := require(&reader, "organization_quotas.tiers", quotas.Tiers)
assessment := require(&reader, "assessment", parsed.Assessment)
stopRule := require(&reader, "assessment.stop_rule", assessment.StopRule)
identity := require(&reader, "identity", parsed.Identity)
searchStatus := require(&reader, "search_status", parsed.SearchStatus)
policy := ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: require(&reader, "invitations.response_deadline_options_days", invitations.ResponseDeadlineOptionsDays),
DefaultResponseDeadline: require(&reader, "invitations.default_response_deadline_days", invitations.DefaultResponseDeadlineDays),
MaxPendingPerNeed: require(&reader, "invitations.max_pending_per_need", invitations.MaxPendingPerNeed),
RepeatAfterDecline: require(&reader, "invitations.repeat_after_decline_days", invitations.RepeatAfterDeclineDays),
InterviewProposalDeadline: require(&reader, "invitations.interview_proposal_deadline_business_days", invitations.InterviewProposalDeadlineBusinessDays),
NoDealPause: require(&reader, "invitations.no_deal_pause_days", invitations.NoDealPauseDays),
},
OrganizationQuotas: OrganizationQuotaPolicy{
InvitationWindow: require(&reader, "organization_quotas.invitation_window_days", quotas.InvitationWindowDays),
CardViewWindow: require(&reader, "organization_quotas.card_view_window_hours", quotas.CardViewWindowHours),
TierE0: decodeTierQuota(&reader, "organization_quotas.tiers.e0", tiers.E0),
TierE1: decodeTierQuota(&reader, "organization_quotas.tiers.e1", tiers.E1),
TierE2: decodeTierQuota(&reader, "organization_quotas.tiers.e2", tiers.E2),
},
Assessment: AssessmentPolicy{
Calibration: require(&reader, "assessment.calibration", assessment.Calibration),
SameGradeRetryAfter: require(&reader, "assessment.same_grade_retry_after_days", assessment.SameGradeRetryAfterDays),
MaxAttemptsPerWindow: require(&reader, "assessment.max_attempts_per_window", assessment.MaxAttemptsPerWindow),
AttemptWindow: require(&reader, "assessment.attempt_window_days", assessment.AttemptWindowDays),
PromotionMinInterval: require(&reader, "assessment.promotion_min_interval_days", assessment.PromotionMinIntervalDays),
ConfirmationThreshold: require(&reader, "assessment.confirmation_threshold_bp", assessment.ConfirmationThresholdBP),
HighStrengthThreshold: require(&reader, "assessment.high_strength_threshold_bp", assessment.HighStrengthThresholdBP),
PracticeRequired: require(&reader, "assessment.practice_required", assessment.PracticeRequired),
StopRule: AssessmentStopRule{
MinScoredItems: require(&reader, "assessment.stop_rule.min_scored_items", stopRule.MinScoredItems),
MaxScoredItems: require(&reader, "assessment.stop_rule.max_scored_items", stopRule.MaxScoredItems),
SeedItems: require(&reader, "assessment.stop_rule.seed_items", stopRule.SeedItems),
UpperProbability: require(&reader, "assessment.stop_rule.upper_probability_bp", stopRule.UpperProbabilityBP),
LowerProbability: require(&reader, "assessment.stop_rule.lower_probability_bp", stopRule.LowerProbabilityBP),
MaxStandardError: require(&reader, "assessment.stop_rule.max_standard_error_bp", stopRule.MaxStandardErrorBP),
},
},
Identity: IdentityPolicy{
VerificationTokenLifetime: require(&reader, "identity.verification_token_lifetime_hours", identity.VerificationTokenLifetimeHours),
UnverifiedAccountLifetime: require(&reader, "identity.unverified_account_lifetime_days", identity.UnverifiedAccountLifetimeDays),
SessionIdleTimeout: require(&reader, "identity.session_idle_timeout_hours", identity.SessionIdleTimeoutHours),
SessionAbsoluteLifetime: require(&reader, "identity.session_absolute_lifetime_days", identity.SessionAbsoluteLifetimeDays),
},
SearchStatus: SearchStatusPolicy{
SearchingConfirmationInterval: require(&reader, "search_status.searching_confirmation_interval_days", searchStatus.SearchingConfirmationIntervalDays),
},
}
if reader.missing != "" {
return ProductPolicy{}, invalidPolicy(location, reader.missing+" is required")
}
return policy, nil
}
func decodeTierQuota(reader *documentReader, field string, document *organizationTierQuotaDocument) OrganizationTierQuota {
tier := require(reader, field, document)
return OrganizationTierQuota{
Active: require(reader, field+".active", tier.Active),
InvitationsPerWindow: require(reader, field+".invitations_per_window", tier.InvitationsPerWindow),
DistinctCardViewsPerWindow: require(reader, field+".distinct_card_views_per_window", tier.DistinctCardViewsPerWindow),
}
}
// documentReader remembers the first missing field while a document is read.
type documentReader struct {
missing string
}
// require returns the value behind a document pointer, or the zero value
// after recording field as missing.
func require[T any](reader *documentReader, field string, value *T) T {
if value == nil {
if reader.missing == "" {
reader.missing = field
}
var zero T
return zero
}
return *value
}
func pointer[T any](value T) *T { return &value }
+480
View File
@@ -0,0 +1,480 @@
package domain
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"strings"
"testing"
"time"
)
// demoProductPolicyV1Document is the canonical document of the demo policy.
// Stored versions are verified by hashing the canonical re-encoding of their
// document, so any change to field order, names, or encoding would make
// every stored version fail its integrity check. A new layout needs a new
// schema version and decoder, not an edit here.
const demoProductPolicyV1Document = `{"schema_version":1,` +
`"invitations":{"response_deadline_options_days":[3,7,14],"default_response_deadline_days":7,` +
`"max_pending_per_need":20,"repeat_after_decline_days":30,"interview_proposal_deadline_business_days":5,` +
`"no_deal_pause_days":30},` +
`"organization_quotas":{"invitation_window_days":7,"card_view_window_hours":24,"tiers":{` +
`"e0":{"active":true,"invitations_per_window":10,"distinct_card_views_per_window":50},` +
`"e1":{"active":true,"invitations_per_window":40,"distinct_card_views_per_window":150},` +
`"e2":{"active":false,"invitations_per_window":100,"distinct_card_views_per_window":400}}},` +
`"assessment":{"calibration":"uncalibrated_initial","same_grade_retry_after_days":30,` +
`"max_attempts_per_window":3,"attempt_window_days":180,"promotion_min_interval_days":90,` +
`"confirmation_threshold_bp":8000,"high_strength_threshold_bp":9000,"practice_required":true,` +
`"stop_rule":{"min_scored_items":8,"max_scored_items":23,"seed_items":2,"upper_probability_bp":9000,` +
`"lower_probability_bp":1000,"max_standard_error_bp":2500}},` +
`"identity":{"verification_token_lifetime_hours":24,"unverified_account_lifetime_days":7,` +
`"session_idle_timeout_hours":24,"session_absolute_lifetime_days":7},` +
`"search_status":{"searching_confirmation_interval_days":30}}`
var (
testPolicyCreatedAt = time.Date(2026, time.October, 6, 9, 0, 0, 0, time.UTC)
testPolicyEffectiveAt = testPolicyCreatedAt.Add(time.Hour)
)
// testPolicy returns a valid policy whose values differ from the demo policy,
// so a test never relies on demo values by accident.
func testPolicy() ProductPolicy {
return ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: []CalendarDays{2, 5},
DefaultResponseDeadline: 5,
MaxPendingPerNeed: 4,
RepeatAfterDecline: 11,
InterviewProposalDeadline: 3,
NoDealPause: 12,
},
OrganizationQuotas: OrganizationQuotaPolicy{
InvitationWindow: 3,
CardViewWindow: 12,
TierE0: OrganizationTierQuota{Active: true, InvitationsPerWindow: 2, DistinctCardViewsPerWindow: 5},
TierE1: OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 6},
TierE2: OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 7},
},
Assessment: AssessmentPolicy{
Calibration: AssessmentCalibrationCalibrated,
SameGradeRetryAfter: 10,
MaxAttemptsPerWindow: 2,
AttemptWindow: 60,
PromotionMinInterval: 45,
ConfirmationThreshold: 7500,
HighStrengthThreshold: 8800,
PracticeRequired: false,
StopRule: AssessmentStopRule{
MinScoredItems: 5,
MaxScoredItems: 15,
SeedItems: 0,
UpperProbability: 9500,
LowerProbability: 500,
MaxStandardError: 3000,
},
},
Identity: IdentityPolicy{
VerificationTokenLifetime: 12,
UnverifiedAccountLifetime: 3,
SessionIdleTimeout: 6,
SessionAbsoluteLifetime: 2,
},
SearchStatus: SearchStatusPolicy{SearchingConfirmationInterval: 14},
}
}
func testDraftInput() NewPolicyVersionDraftInput {
return NewPolicyVersionDraftInput{
Key: ProductPolicyKey,
Kind: PolicyKindCalibrated,
Author: "operator:policy-tester",
EffectiveAt: testPolicyEffectiveAt,
Policy: testPolicy(),
}
}
func mustDraft(t *testing.T, input NewPolicyVersionDraftInput, number int32) PolicyVersionDraft {
t.Helper()
draft, err := NewPolicyVersionDraft(input)
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
numbered, err := draft.WithVersion(number)
if err != nil {
t.Fatalf("WithVersion(%d) error = %v", number, err)
}
return numbered
}
// storedFrom returns the row storage would hold for the draft.
func storedFrom(draft PolicyVersionDraft) StoredPolicyVersion {
hash := draft.DocumentHash()
effectiveAt, scheduled := draft.EffectiveAt()
if !scheduled {
effectiveAt = testPolicyCreatedAt
}
return StoredPolicyVersion{
ID: draft.ID(),
Key: string(draft.Key()),
Version: draft.Version(),
Kind: string(draft.Kind()),
Author: string(draft.Author()),
EffectiveAt: effectiveAt,
CreatedAt: testPolicyCreatedAt,
Document: draft.Document(),
DocumentHash: hash[:],
}
}
func mustRestore(t *testing.T, stored StoredPolicyVersion) PolicyVersion {
t.Helper()
version, err := RestorePolicyVersion(stored)
if err != nil {
t.Fatalf("RestorePolicyVersion() error = %v", err)
}
return version
}
func TestDemoProductPolicyV1IsValidDemoAndUncalibrated(t *testing.T) {
demo := DemoProductPolicyV1()
if err := demo.Validate(); err != nil {
t.Fatalf("DemoProductPolicyV1().Validate() error = %v", err)
}
if demo.Assessment.Calibration != AssessmentCalibrationUncalibratedInitial {
t.Fatalf("demo assessment calibration = %q, want uncalibrated_initial", demo.Assessment.Calibration)
}
if demo.OrganizationQuotas.TierE2.Active {
t.Fatal("demo tier E2 is active before organization verification exists")
}
draft := mustDraft(t, NewPolicyVersionDraftInput{
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: demo,
}, 1)
if got := string(draft.Document()); got != demoProductPolicyV1Document {
t.Fatalf("demo canonical document =\n%s\nwant\n%s", got, demoProductPolicyV1Document)
}
if draft.DocumentHash() != sha256.Sum256([]byte(demoProductPolicyV1Document)) {
t.Fatal("demo document hash is not the SHA-256 of the canonical document")
}
if _, scheduled := draft.EffectiveAt(); scheduled {
t.Fatal("a draft without an effective time reports a schedule")
}
calibrated := NewPolicyVersionDraftInput{Key: ProductPolicyKey, Kind: PolicyKindCalibrated, Author: DemoPolicySeedAuthor, Policy: demo}
if _, err := NewPolicyVersionDraft(calibrated); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("NewPolicyVersionDraft(demo values as calibrated) error = %v, want ErrInvalidPolicyVersion", err)
}
}
func TestProductPolicyValidateRejectsEachSection(t *testing.T) {
tests := map[string]func(*ProductPolicy){
"zero policy": func(policy *ProductPolicy) { *policy = ProductPolicy{} },
"no deadline options": func(policy *ProductPolicy) { policy.Invitations.ResponseDeadlineOptions = nil },
"too many deadline options": func(policy *ProductPolicy) {
policy.Invitations.ResponseDeadlineOptions = []CalendarDays{1, 2, 3, 4, 5, 6}
},
"deadline option out of range": func(policy *ProductPolicy) { policy.Invitations.ResponseDeadlineOptions = []CalendarDays{2, 31} },
"deadline options not increasing": func(policy *ProductPolicy) { policy.Invitations.ResponseDeadlineOptions = []CalendarDays{5, 5} },
"default deadline not an option": func(policy *ProductPolicy) { policy.Invitations.DefaultResponseDeadline = 3 },
"zero pending limit": func(policy *ProductPolicy) { policy.Invitations.MaxPendingPerNeed = 0 },
"negative repeat after decline": func(policy *ProductPolicy) { policy.Invitations.RepeatAfterDecline = -1 },
"zero interview deadline": func(policy *ProductPolicy) { policy.Invitations.InterviewProposalDeadline = 0 },
"no-deal pause over a year": func(policy *ProductPolicy) { policy.Invitations.NoDealPause = 366 },
"zero invitation window": func(policy *ProductPolicy) { policy.OrganizationQuotas.InvitationWindow = 0 },
"card view window over a week": func(policy *ProductPolicy) { policy.OrganizationQuotas.CardViewWindow = 169 },
"zero tier limit": func(policy *ProductPolicy) { policy.OrganizationQuotas.TierE0.InvitationsPerWindow = 0 },
"inactive E0": func(policy *ProductPolicy) { policy.OrganizationQuotas.TierE0.Active = false },
"active E2 above inactive E1": func(policy *ProductPolicy) { policy.OrganizationQuotas.TierE1.Active = false },
"higher tier below lower tier": func(policy *ProductPolicy) {
policy.OrganizationQuotas.TierE2.DistinctCardViewsPerWindow = policy.OrganizationQuotas.TierE1.DistinctCardViewsPerWindow - 1
},
"unknown calibration": func(policy *ProductPolicy) { policy.Assessment.Calibration = "pilot" },
"zero retry interval": func(policy *ProductPolicy) { policy.Assessment.SameGradeRetryAfter = 0 },
"zero attempts per window": func(policy *ProductPolicy) { policy.Assessment.MaxAttemptsPerWindow = 0 },
"zero attempt window": func(policy *ProductPolicy) { policy.Assessment.AttemptWindow = 0 },
"zero promotion interval": func(policy *ProductPolicy) { policy.Assessment.PromotionMinInterval = 0 },
"confirmation threshold of one": func(policy *ProductPolicy) { policy.Assessment.ConfirmationThreshold = 10000 },
"confirmation threshold of zero": func(policy *ProductPolicy) { policy.Assessment.ConfirmationThreshold = 0 },
"high strength below confirmation": func(policy *ProductPolicy) { policy.Assessment.HighStrengthThreshold = 7000 },
"zero minimum scored items": func(policy *ProductPolicy) { policy.Assessment.StopRule.MinScoredItems = 0 },
"maximum below minimum scored items": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxScoredItems = 4 },
"negative seed items": func(policy *ProductPolicy) { policy.Assessment.StopRule.SeedItems = -1 },
"lower stop at confirmation": func(policy *ProductPolicy) { policy.Assessment.StopRule.LowerProbability = 7500 },
"upper stop below confirmation": func(policy *ProductPolicy) { policy.Assessment.StopRule.UpperProbability = 7000 },
"zero standard error": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 0 },
"standard error above one": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 10001 },
"zero token lifetime": func(policy *ProductPolicy) { policy.Identity.VerificationTokenLifetime = 0 },
"zero unverified account lifetime": func(policy *ProductPolicy) { policy.Identity.UnverifiedAccountLifetime = 0 },
"zero idle timeout": func(policy *ProductPolicy) { policy.Identity.SessionIdleTimeout = 0 },
"absolute lifetime over limit": func(policy *ProductPolicy) { policy.Identity.SessionAbsoluteLifetime = 91 },
"idle timeout above absolute": func(policy *ProductPolicy) { policy.Identity.SessionIdleTimeout = 49 },
"zero searching confirmation": func(policy *ProductPolicy) { policy.SearchStatus.SearchingConfirmationInterval = 0 },
"searching confirmation over a year": func(policy *ProductPolicy) { policy.SearchStatus.SearchingConfirmationInterval = 366 },
"negative searching confirmation": func(policy *ProductPolicy) { policy.SearchStatus.SearchingConfirmationInterval = -30 },
"tier invitations above sanity bound": func(policy *ProductPolicy) {
policy.OrganizationQuotas.TierE2.InvitationsPerWindow = maxTierQuotaLimit + 1
},
}
if err := testPolicy().Validate(); err != nil {
t.Fatalf("testPolicy().Validate() error = %v", err)
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
policy := testPolicy()
mutate(&policy)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err)
}
input := testDraftInput()
input.Policy = policy
if _, err := NewPolicyVersionDraft(input); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("NewPolicyVersionDraft() error = %v, want ErrInvalidPolicy", err)
}
})
}
}
func TestNewPolicyVersionDraftRejectsInvalidMetadata(t *testing.T) {
tests := map[string]func(*NewPolicyVersionDraftInput){
"empty family": func(input *NewPolicyVersionDraftInput) { input.Key = "" },
"unknown family": func(input *NewPolicyVersionDraftInput) { input.Key = "test_policy" },
"unknown kind": func(input *NewPolicyVersionDraftInput) { input.Kind = "draft" },
"author without prefix": func(input *NewPolicyVersionDraftInput) { input.Author = "policy-tester" },
"author with an email": func(input *NewPolicyVersionDraftInput) { input.Author = "operator:tester@example.com" },
"author over 128 bytes": func(input *NewPolicyVersionDraftInput) {
input.Author = PolicyAuthor("operator:" + strings.Repeat("a", 120))
},
"calibrated without calibration": func(input *NewPolicyVersionDraftInput) {
input.Policy.Assessment.Calibration = AssessmentCalibrationUncalibratedInitial
},
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
input := testDraftInput()
mutate(&input)
if _, err := NewPolicyVersionDraft(input); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("NewPolicyVersionDraft() error = %v, want ErrInvalidPolicyVersion", err)
}
})
}
draft, err := NewPolicyVersionDraft(testDraftInput())
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
if draft.Version() != 0 {
t.Fatalf("new draft version = %d, want unnumbered", draft.Version())
}
if _, err := draft.WithVersion(0); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("WithVersion(0) error = %v, want ErrInvalidPolicyVersion", err)
}
if _, err := (PolicyVersionDraft{}).WithVersion(1); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("zero draft WithVersion(1) error = %v, want ErrInvalidPolicyVersion", err)
}
}
func TestPolicyVersionRoundTripAndHashDeterminism(t *testing.T) {
input := testDraftInput()
first := mustDraft(t, input, 3)
second := mustDraft(t, input, 3)
if first.ID() == second.ID() || first.ID().UUID().Version() != 7 {
t.Fatalf("IDs = %s and %s, want distinct UUIDv7 values", first.ID(), second.ID())
}
if string(first.Document()) != string(second.Document()) || first.DocumentHash() != second.DocumentHash() {
t.Fatal("the same policy encoded to different documents or hashes")
}
if first.DocumentHash() != sha256.Sum256(first.Document()) {
t.Fatal("document hash is not the SHA-256 of the canonical document")
}
changed := input
changed.Policy = testPolicy()
changed.Policy.Invitations.MaxPendingPerNeed++
if mustDraft(t, changed, 3).DocumentHash() == first.DocumentHash() {
t.Fatal("a different policy produced the same hash")
}
restored := mustRestore(t, storedFrom(first))
assertRestoredFromDraft(t, restored, first)
// jsonb returns the document with other key order and whitespace; the
// hash is checked against the canonical re-encoding, not the bytes.
var generic map[string]any
if err := json.Unmarshal(first.Document(), &generic); err != nil {
t.Fatalf("unmarshal document: %v", err)
}
reordered, err := json.MarshalIndent(generic, "", " ")
if err != nil {
t.Fatalf("marshal reordered document: %v", err)
}
stored := storedFrom(first)
stored.Document = reordered
assertRestoredFromDraft(t, mustRestore(t, stored), first)
}
func TestPolicyVersionAccessorsReturnCopies(t *testing.T) {
draft := mustDraft(t, testDraftInput(), 1)
version := mustRestore(t, storedFrom(draft))
for _, values := range []struct {
policy ProductPolicy
document []byte
}{
{policy: draft.Policy(), document: draft.Document()},
{policy: version.Policy(), document: version.Document()},
} {
values.policy.Invitations.ResponseDeadlineOptions[0] = 99
values.document[0] = '['
}
if draft.Policy().Invitations.ResponseDeadlineOptions[0] == 99 || draft.Document()[0] != '{' ||
version.Policy().Invitations.ResponseDeadlineOptions[0] == 99 || version.Document()[0] != '{' {
t.Fatal("changing a returned value changed the draft or the stored version")
}
}
func TestOrganizationTierLookup(t *testing.T) {
quotas := DemoProductPolicyV1().OrganizationQuotas
for value, want := range map[string]OrganizationTierQuota{"e0": quotas.TierE0, "e1": quotas.TierE1, "e2": quotas.TierE2} {
tier, err := ParseOrganizationTier(value)
if err != nil {
t.Fatalf("ParseOrganizationTier(%q) error = %v", value, err)
}
if got, err := quotas.Tier(tier); err != nil || got != want {
t.Fatalf("Tier(%s) = %+v, %v; want %+v", tier, got, err, want)
}
}
if _, err := ParseOrganizationTier("E0"); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("ParseOrganizationTier(E0) error = %v, want ErrInvalidPolicy", err)
}
if _, err := quotas.Tier("e3"); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("Tier(e3) error = %v, want ErrInvalidPolicy", err)
}
}
func TestRestorePolicyVersionRejectsInvalidDocuments(t *testing.T) {
version := mustDraft(t, testDraftInput(), 1)
editDocument := func(edit func(map[string]any)) []byte {
var generic map[string]any
if err := json.Unmarshal(version.Document(), &generic); err != nil {
t.Fatalf("unmarshal document: %v", err)
}
edit(generic)
encoded, err := json.Marshal(generic)
if err != nil {
t.Fatalf("marshal document: %v", err)
}
return encoded
}
section := func(document map[string]any, name string) map[string]any {
value, ok := document[name].(map[string]any)
if !ok {
t.Fatalf("document has no %s object", name)
}
return value
}
tests := []struct {
name string
document []byte
want error
}{
{name: "unknown top-level field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { document["notes"] = "x" })},
{name: "unknown nested field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "identity")["password_reset_hours"] = 1
})},
{name: "missing section", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { delete(document, "search_status") })},
{name: "missing nested field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
delete(section(document, "assessment"), "practice_required")
})},
{name: "null field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = nil
})},
{name: "fractional number", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = 4.5
})},
{name: "number as string", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = "4"
})},
{name: "number above int32", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = 1 << 40
})},
{name: "unknown schema version", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { document["schema_version"] = 2 })},
{name: "missing schema version", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { delete(document, "schema_version") })},
{name: "out-of-range value", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) {
section(document, "search_status")["searching_confirmation_interval_days"] = 0
})},
{name: "trailing data", want: ErrInvalidPolicy, document: append(version.Document(), []byte(` {}`)...)},
{name: "array instead of object", want: ErrInvalidPolicy, document: []byte(`[]`)},
{name: "oversized document", want: ErrInvalidPolicy, document: padDocument(version.Document(), maxPolicyDocumentBytes+1)},
{name: "valid change without a new hash", want: ErrPolicyDocumentIntegrity, document: editDocument(func(document map[string]any) {
section(document, "invitations")["max_pending_per_need"] = 5
})},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
stored := storedFrom(version)
stored.Document = test.document
if _, err := RestorePolicyVersion(stored); !errors.Is(err, test.want) {
t.Fatalf("RestorePolicyVersion() error = %v, want %v", err, test.want)
}
})
}
t.Run("whitespace up to the size limit is accepted", func(t *testing.T) {
// The oversized case above fails on size alone: the same padding
// that ends at the limit restores.
stored := storedFrom(version)
stored.Document = padDocument(version.Document(), maxPolicyDocumentBytes)
assertRestoredFromDraft(t, mustRestore(t, stored), version)
})
t.Run("hash of the wrong size", func(t *testing.T) {
stored := storedFrom(version)
stored.DocumentHash = stored.DocumentHash[:16]
if _, err := RestorePolicyVersion(stored); !errors.Is(err, ErrPolicyDocumentIntegrity) {
t.Fatalf("RestorePolicyVersion() error = %v, want ErrPolicyDocumentIntegrity", err)
}
})
t.Run("invalid metadata", func(t *testing.T) {
for name, mutate := range map[string]func(*StoredPolicyVersion){
"nil ID": func(stored *StoredPolicyVersion) { stored.ID = PolicyVersionID{} },
"unknown kind": func(stored *StoredPolicyVersion) { stored.Kind = "draft" },
"invalid author": func(stored *StoredPolicyVersion) { stored.Author = "someone" },
"unknown family": func(stored *StoredPolicyVersion) { stored.Key = "other" },
"zero version": func(stored *StoredPolicyVersion) { stored.Version = 0 },
"zero creation": func(stored *StoredPolicyVersion) { stored.CreatedAt = time.Time{} },
"backdated": func(stored *StoredPolicyVersion) { stored.EffectiveAt = stored.CreatedAt.Add(-time.Second) },
} {
stored := storedFrom(version)
mutate(&stored)
if _, err := RestorePolicyVersion(stored); !errors.Is(err, ErrInvalidPolicyVersion) {
t.Fatalf("%s: RestorePolicyVersion() error = %v, want ErrInvalidPolicyVersion", name, err)
}
}
})
}
func TestPolicyUnits(t *testing.T) {
if got := CalendarDays(7).Duration(); got != 7*24*time.Hour {
t.Fatalf("CalendarDays(7).Duration() = %s", got)
}
if got := Hours(24).Duration(); got != 24*time.Hour {
t.Fatalf("Hours(24).Duration() = %s", got)
}
for points, want := range map[BasisPoints]string{8000: "0.8000", 2500: "0.2500", 1: "0.0001", 10000: "1.0000"} {
if got := points.String(); got != want {
t.Fatalf("BasisPoints(%d).String() = %q, want %q", int32(points), got, want)
}
}
}
// padDocument appends JSON whitespace until the document has size bytes, so
// it stays a valid document of the same content.
func padDocument(document []byte, size int) []byte {
padded := append([]byte(nil), document...)
return append(padded, bytes.Repeat([]byte(" "), size-len(document))...)
}
func assertRestoredFromDraft(t *testing.T, got PolicyVersion, draft PolicyVersionDraft) {
t.Helper()
want := storedFrom(draft)
if got.ID() != draft.ID() || got.Key() != draft.Key() || got.Version() != draft.Version() || got.Kind() != draft.Kind() ||
got.Author() != draft.Author() || !got.EffectiveAt().Equal(want.EffectiveAt) || !got.CreatedAt().Equal(want.CreatedAt) ||
got.DocumentHash() != draft.DocumentHash() || string(got.Document()) != string(draft.Document()) {
t.Fatalf("restored version = %+v, want the draft %+v", got, draft)
}
}
+352
View File
@@ -0,0 +1,352 @@
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:<name>" or "operator:<handle>", 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:<name>" for an
// automated publisher or "operator:<handle>" 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:<name> or operator:<handle> 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() }