package domain import ( "crypto/sha256" "errors" "fmt" "slices" "time" "github.com/google/uuid" ) // ErrInvalidAssessmentReview reports a malformed server observation or review. // Its text never includes an answer, an address, or a session identifier. var ErrInvalidAssessmentReview = errors.New("invalid assessment review") // AssessmentReviewBand is the manual-check hint of one attempt. It is stored // for an operator only. It has no effect on the result, the category, or a // quota, and no candidate or employer read carries it. type AssessmentReviewBand string const ( AssessmentReviewBandNormal AssessmentReviewBand = "normal" AssessmentReviewBandAttention AssessmentReviewBand = "attention" AssessmentReviewBandReview AssessmentReviewBand = "review" ) func (band AssessmentReviewBand) rank() int { switch band { case AssessmentReviewBandNormal: return 0 case AssessmentReviewBandAttention: return 1 case AssessmentReviewBandReview: return 2 default: return -1 } } // IsKnown reports whether the band is one of the three stored values. func (band AssessmentReviewBand) IsKnown() bool { return band.rank() >= 0 } // AssessmentReviewReason names a signal group that raised the band. type AssessmentReviewReason string const ( AssessmentReviewReasonFastAnswers AssessmentReviewReason = "fast_answers" AssessmentReviewReasonDeviatingAnswers AssessmentReviewReason = "deviating_answers" AssessmentReviewReasonParallelSessions AssessmentReviewReason = "parallel_sessions" AssessmentReviewReasonExtraNetworks AssessmentReviewReason = "extra_networks" AssessmentReviewReasonDuplicateAnswers AssessmentReviewReason = "duplicate_answers" AssessmentReviewReasonClientSignals AssessmentReviewReason = "client_signals" ) // IsKnown reports whether the reason is a stored value. func (reason AssessmentReviewReason) IsKnown() bool { switch reason { case AssessmentReviewReasonFastAnswers, AssessmentReviewReasonDeviatingAnswers, AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks, AssessmentReviewReasonDuplicateAnswers, AssessmentReviewReasonClientSignals: return true default: return false } } // AssessmentDigest is a keyed 32-byte digest. It stands for an answer, a // session, or a network address without carrying any of them. type AssessmentDigest [sha256.Size]byte // IsZero reports an unset digest. func (digest AssessmentDigest) IsZero() bool { return digest == AssessmentDigest{} } // AssessmentAnswerObservation is the server-side record of one accepted // answer: how long it took, and a keyed fingerprint of the normalized answer // that allows comparing answers of different candidates without storing them. type AssessmentAnswerObservation struct { AttemptID AssessmentAttemptID UserID uuid.UUID ItemInstanceID uuid.UUID FamilyID AssessmentFamilyID FamilyVersion int32 Seed VariantSeed AnswerFormat string Fingerprint AssessmentDigest // KeyVersion names the key generation of Fingerprint, so a rotation is // explicit and fingerprints of different generations are never compared. KeyVersion int16 ElapsedMS int32 // MeasuredFromAnswer is true when ElapsedMS starts at the previous answer, // which is when this item was shown. The first item of a work session starts // at the session start, which is only an upper bound of the time the item // was on screen, so such a time is not used for the speed signals. MeasuredFromAnswer bool ObservedAt time.Time } // Validate checks that the observation can be stored. func (observation AssessmentAnswerObservation) Validate() error { const location = "AssessmentAnswerObservation.Validate" switch { case observation.AttemptID.IsZero(), observation.UserID == uuid.Nil, observation.ItemInstanceID == uuid.Nil, uuid.UUID(observation.FamilyID) == uuid.Nil, observation.FamilyVersion < 1: return fmt.Errorf("%s - identifiers are required: %w", location, ErrInvalidAssessmentReview) case observation.AnswerFormat != AnswerFormatInteger && observation.AnswerFormat != AnswerFormatIntegerSequence: return fmt.Errorf("%s - answer format is unsupported: %w", location, ErrInvalidAssessmentReview) case observation.Fingerprint.IsZero(), observation.KeyVersion < 1: return fmt.Errorf("%s - fingerprint and its key version are required: %w", location, ErrInvalidAssessmentReview) case observation.ElapsedMS < 0, observation.ObservedAt.IsZero(): return fmt.Errorf("%s - elapsed time and observation time are required: %w", location, ErrInvalidAssessmentReview) } return nil } // AssessmentOriginSource says which request produced an origin mark. type AssessmentOriginSource string const ( AssessmentOriginAnswer AssessmentOriginSource = "answer" AssessmentOriginSignals AssessmentOriginSource = "signals" ) // AssessmentOriginMark records, for one accepted request, keyed digests of the // authenticated session and of the client network. The digests are bound to // the attempt, so they cannot be correlated between attempts, and they are // useless without the server secret. NetworkDigest is absent when the client // address could not be resolved. type AssessmentOriginMark struct { ID uuid.UUID AttemptID AssessmentAttemptID Source AssessmentOriginSource ObservedAt time.Time SessionDigest AssessmentDigest NetworkDigest AssessmentDigest KeyVersion int16 } // Validate checks that the mark can be stored. func (mark AssessmentOriginMark) Validate() error { const location = "AssessmentOriginMark.Validate" if mark.ID == uuid.Nil || mark.AttemptID.IsZero() || mark.ObservedAt.IsZero() || mark.SessionDigest.IsZero() || mark.KeyVersion < 1 { return fmt.Errorf("%s - identifiers, time, session digest, and key version are required: %w", location, ErrInvalidAssessmentReview) } if mark.Source != AssessmentOriginAnswer && mark.Source != AssessmentOriginSignals { return fmt.Errorf("%s - source is unknown: %w", location, ErrInvalidAssessmentReview) } return nil } // AssessmentResponseSample is the server time of one answer. type AssessmentResponseSample struct { AnswerFormat string ElapsedMS int32 MeasuredFromAnswer bool } // AssessmentResponseTimes counts the answers and the answers that the policy // calls fast or anomalously fast. Only server time is used: the client may // report durations of its own, but they never replace it. type AssessmentResponseTimes struct { Answered int32 Fast int32 Deviating int32 } // ClassifyResponseTimes applies the fast floors and the median deviation of // the policy. Only answers measured from the previous answer count. The // deviation is computed within one answer format, so a slow format does not // make a quick one look anomalous, and only on the fast side: a slow answer is // not suspicious by itself. One answer contributes to at most one counter: an // answer under its floor is fast and is not counted again as a deviation. func (policy AssessmentSignalPolicy) ClassifyResponseTimes(samples []AssessmentResponseSample) AssessmentResponseTimes { result := AssessmentResponseTimes{Answered: int32(min(len(samples), maxAssessmentAttemptItems))} byFormat := map[string][]int64{} for _, sample := range samples { if !sample.MeasuredFromAnswer { continue } floor := policy.fastFloor(sample.AnswerFormat) if sample.ElapsedMS < floor { result.Fast++ // Kept for the median, but marked so it is not a deviation too. byFormat[sample.AnswerFormat] = append(byFormat[sample.AnswerFormat], -int64(sample.ElapsedMS)-1) continue } byFormat[sample.AnswerFormat] = append(byFormat[sample.AnswerFormat], int64(sample.ElapsedMS)) } ratio := int64(policy.DeviationRatio) for _, marked := range byFormat { if len(marked) < int(policy.DeviationMinAnswers) { continue } elapsed := make([]int64, len(marked)) for index, value := range marked { elapsed[index] = value if value < 0 { elapsed[index] = -value - 1 } } slices.Sort(elapsed) median := elapsed[len(elapsed)/2] if len(elapsed)%2 == 0 { median = (elapsed[len(elapsed)/2-1] + elapsed[len(elapsed)/2]) / 2 } median = max(median, 1) for _, value := range marked { // value is more than ratio times below the median, in basis points. if value >= 0 && max(value, 1)*ratio < median*int64(basisPointsPerUnit) { result.Deviating++ } } } return result } func (policy AssessmentSignalPolicy) fastFloor(format string) int32 { if format == AnswerFormatIntegerSequence { return policy.FastFloorSequenceMS } return policy.FastFloorIntegerMS } // AssessmentOriginAnomalies counts the origin changes of an attempt. type AssessmentOriginAnomalies struct { // ParallelAlternations counts requests that came back to an earlier // session after another session had been used, as when two logged-in // sessions work on one attempt in turn. A single move from one session to // another is not counted. ParallelAlternations int32 // ExtraNetworks counts the distinct network digests beyond the first. A // move to another network and back is one extra network. ExtraNetworks int32 } // CountOriginAnomalies orders the marks by time and then by ID and counts // alternations between sessions and distinct client networks. func CountOriginAnomalies(marks []AssessmentOriginMark) AssessmentOriginAnomalies { ordered := slices.Clone(marks) slices.SortStableFunc(ordered, func(left, right AssessmentOriginMark) int { if byTime := left.ObservedAt.Compare(right.ObservedAt); byTime != 0 { return byTime } return slices.Compare(left.ID[:], right.ID[:]) }) var anomalies AssessmentOriginAnomalies seenSessions := map[AssessmentDigest]struct{}{} networks := map[AssessmentDigest]struct{}{} var previousSession AssessmentDigest for _, mark := range ordered { _, seen := seenSessions[mark.SessionDigest] if seen && mark.SessionDigest != previousSession { anomalies.ParallelAlternations++ } seenSessions[mark.SessionDigest] = struct{}{} previousSession = mark.SessionDigest if !mark.NetworkDigest.IsZero() { networks[mark.NetworkDigest] = struct{}{} } } anomalies.ExtraNetworks = int32(max(len(networks)-1, 0)) //nolint:gosec // The number of marks of an attempt is bounded by its stored list. return anomalies } // AssessmentReviewMeasures is everything the band is computed from. Every // field is a count or a duration; none of them holds an answer or an address. // The duplicate fields describe the pair of attempts with the most evidence. type AssessmentReviewMeasures struct { AnsweredItems int32 FastAnswers int32 DeviatingAnswers int32 ParallelAlternations int32 ExtraNetworks int32 MatchedIntegerItems int32 MatchedSequenceItems int32 DuplicateEvidenceBits int32 ClientFocusLossMS int64 ClientClipboardEvents int32 ClientFullscreenExits int32 } // AssessmentReviewOutcome is the computed band with the groups behind it. type AssessmentReviewOutcome struct { Band AssessmentReviewBand Reasons []AssessmentReviewReason } // Evaluate computes the band. Server signals decide it. Parallel sessions and // extra networks are weak and correlated (a phone and a laptop produce both), so // they are one group: alone it reaches attention at most, and review only // together with a strong signal (fast answers, deviating answers, or duplicate // answers) at attention or above. Client signals can only raise a normal band // to attention, because a browser reports them. func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures) AssessmentReviewOutcome { type signal struct { reason AssessmentReviewReason band AssessmentReviewBand weak bool } signals := []signal{ {AssessmentReviewReasonFastAnswers, signalLevel(measures.FastAnswers, policy.FastAnswersAttention, policy.FastAnswersReview), false}, {AssessmentReviewReasonDeviatingAnswers, signalLevel(measures.DeviatingAnswers, policy.DeviatingAnswersAttention, policy.DeviatingAnswersReview), false}, {AssessmentReviewReasonParallelSessions, signalLevel(measures.ParallelAlternations, policy.ParallelAlternationsAttention, policy.ParallelAlternationsReview), true}, {AssessmentReviewReasonExtraNetworks, signalLevel(measures.ExtraNetworks, policy.ExtraNetworksAttention, policy.ExtraNetworksReview), true}, {AssessmentReviewReasonDuplicateAnswers, signalLevel(measures.DuplicateEvidenceBits, policy.DuplicateAttentionBits, policy.DuplicateReviewBits), false}, } strongRaised := false for _, entry := range signals { if !entry.weak && entry.band.rank() > 0 { strongRaised = true } } outcome := AssessmentReviewOutcome{Band: AssessmentReviewBandNormal} for _, entry := range signals { band := entry.band if entry.weak && band == AssessmentReviewBandReview && !strongRaised { band = AssessmentReviewBandAttention } if band.rank() == 0 { continue } outcome.Reasons = append(outcome.Reasons, entry.reason) if band.rank() > outcome.Band.rank() { outcome.Band = band } } if measures.ClientFocusLossMS >= int64(policy.ClientFocusLossAttentionMS) || measures.ClientClipboardEvents >= policy.ClientClipboardEventsAttention || measures.ClientFullscreenExits >= policy.ClientFullscreenExitsAttention { outcome.Reasons = append(outcome.Reasons, AssessmentReviewReasonClientSignals) if outcome.Band == AssessmentReviewBandNormal { outcome.Band = AssessmentReviewBandAttention } } return outcome } func signalLevel(value, attention, review int32) AssessmentReviewBand { switch { case value >= review: return AssessmentReviewBandReview case value >= attention: return AssessmentReviewBandAttention default: return AssessmentReviewBandNormal } } // AssessmentAttemptReview is the stored review of an attempt. PolicyVersionID // pins the policy version that computed it, which is the version the attempt // itself is pinned to. type AssessmentAttemptReview struct { AttemptID AssessmentAttemptID PolicyVersionID PolicyVersionID PolicyVersion int32 Measures AssessmentReviewMeasures Outcome AssessmentReviewOutcome EvaluatedAt time.Time UpdatedAt time.Time } // Validate checks that the review can be stored. func (review AssessmentAttemptReview) Validate() error { const location = "AssessmentAttemptReview.Validate" if review.AttemptID.IsZero() || review.PolicyVersionID.IsZero() || !review.Outcome.Band.IsKnown() || review.EvaluatedAt.IsZero() || review.UpdatedAt.IsZero() { return fmt.Errorf("%s - attempt, policy, band, and times are required: %w", location, ErrInvalidAssessmentReview) } for _, reason := range review.Outcome.Reasons { if !reason.IsKnown() { return fmt.Errorf("%s - reason is unknown: %w", location, ErrInvalidAssessmentReview) } } return nil } // AssessmentReviewActor is the audit handle of an operator who reads a // review, written as operator:. It is not authentication. type AssessmentReviewActor string // ParseAssessmentReviewActor accepts operator:. func ParseAssessmentReviewActor(value string) (AssessmentReviewActor, error) { if len(value) > 128 || !assessmentOperatorPattern.MatchString(value) { return "", fmt.Errorf("domain.ParseAssessmentReviewActor - actor must be operator: of at most 128 bytes in lowercase letters, digits, '.', '_', or '-': %w", ErrInvalidAssessmentReview) } return AssessmentReviewActor(value), nil }