276 lines
14 KiB
Go
276 lines
14 KiB
Go
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 }
|