517 lines
24 KiB
Go
517 lines
24 KiB
Go
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 attempt lifetime": func(policy *ProductPolicy) {
|
|
policy.Assessment.Attempt.Lifetime = 0
|
|
},
|
|
"chain exceeds attempt lifetime": func(policy *ProductPolicy) {
|
|
policy.Assessment.Attempt.Lifetime = 24
|
|
policy.Assessment.Attempt.ChainDeadline = 25
|
|
},
|
|
"idle timeout above lifetime": func(policy *ProductPolicy) {
|
|
policy.Assessment.Attempt.Lifetime = 1
|
|
policy.Assessment.Attempt.IdleTimeoutSeconds = 3601
|
|
},
|
|
"unknown real attempt mode": func(policy *ProductPolicy) {
|
|
policy.Assessment.Attempt.RealMode = "client_selected"
|
|
},
|
|
"basic mode missing pass mark": func(policy *ProductPolicy) {
|
|
policy.Assessment.Attempt.BasicPassMark = 0
|
|
},
|
|
"adaptive mode with basic mark": func(policy *ProductPolicy) {
|
|
policy.Assessment.Attempt.RealMode = AssessmentRealModeAdaptive
|
|
},
|
|
"adaptive mode without calibration": func(policy *ProductPolicy) {
|
|
policy.Assessment.Calibration = AssessmentCalibrationUncalibratedInitial
|
|
policy.Assessment.Attempt.RealMode = AssessmentRealModeAdaptive
|
|
policy.Assessment.Attempt.BasicPassMark = 0
|
|
},
|
|
"invalid express duration": func(policy *ProductPolicy) {
|
|
policy.Assessment.Training.DemoExpressDurationSeconds = 179
|
|
},
|
|
"invalid express item count": func(policy *ProductPolicy) {
|
|
policy.Assessment.Training.DemoExpressItemCount = 0
|
|
},
|
|
"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()
|
|
preset := DemoProductPolicyV2().Assessment
|
|
attempt := *preset.Attempt
|
|
training := *preset.Training
|
|
policy.Assessment.Attempt = &attempt
|
|
policy.Assessment.Training = &training
|
|
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)
|
|
}
|
|
}
|