feat(assessment): record capture hints and keep one window per attempt

This commit is contained in:
shira committed 2026-10-11 13:16:52 +03:00
1 parent c975a0d506
commit bb917bf62e
108 files changed
+6649 -139

No files matched your search

+16 -8
View File
@@ -27,12 +27,18 @@ const (
AssessmentSignalPaste AssessmentSignalKind = "paste"
AssessmentSignalCut AssessmentSignalKind = "cut"
AssessmentSignalFullscreenExit AssessmentSignalKind = "fullscreen_exit"
// AssessmentSignalScreenshotKey and AssessmentSignalDevtoolsOpen are weak
// hints that the screen may be captured or inspected. They carry no
// measurement and lead to attention in a manual review at most.
AssessmentSignalScreenshotKey AssessmentSignalKind = "screenshot_key"
AssessmentSignalDevtoolsOpen AssessmentSignalKind = "devtools_open"
)
func (kind AssessmentSignalKind) IsKnown() bool {
switch kind {
case AssessmentSignalFocusLoss, AssessmentSignalCopy, AssessmentSignalPaste,
AssessmentSignalCut, AssessmentSignalFullscreenExit:
AssessmentSignalCut, AssessmentSignalFullscreenExit,
AssessmentSignalScreenshotKey, AssessmentSignalDevtoolsOpen:
return true
default:
return false
@@ -75,8 +81,8 @@ func newAssessmentSignalEvent(input AssessmentSignalEventInput, occurredAt time.
return assessmentFocusLossEvent(input, occurredAt)
case AssessmentSignalCopy, AssessmentSignalPaste, AssessmentSignalCut:
return assessmentClipboardEvent(input, occurredAt)
case AssessmentSignalFullscreenExit:
return assessmentFullscreenExitEvent(input, occurredAt)
case AssessmentSignalFullscreenExit, AssessmentSignalScreenshotKey, AssessmentSignalDevtoolsOpen:
return assessmentBareEvent(input, occurredAt)
default:
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - event kind is unknown: %w", ErrInvalidAssessmentSignal)
}
@@ -102,9 +108,11 @@ func assessmentClipboardEvent(input AssessmentSignalEventInput, occurredAt time.
}, nil
}
func assessmentFullscreenExitEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
// assessmentBareEvent builds an event that is only a fact: a fullscreen exit, a
// screenshot key, or open developer tools. It has no measurement.
func assessmentBareEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
if input.DurationMS != nil || input.SizeBytes != nil {
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - fullscreen exit has no measurements: %w", ErrInvalidAssessmentSignal)
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - %s has no measurements: %w", input.Kind, ErrInvalidAssessmentSignal)
}
return AssessmentSignalEvent{kind: input.Kind, itemInstanceID: input.ItemInstanceID, occurredAt: occurredAt}, nil
}
@@ -162,8 +170,8 @@ func validateAssessmentSignalBatchEvent(event AssessmentSignalEvent) error {
return validateAssessmentSignalFocusLoss(event)
case AssessmentSignalCopy, AssessmentSignalPaste, AssessmentSignalCut:
return validateAssessmentSignalClipboard(event)
case AssessmentSignalFullscreenExit:
return validateAssessmentSignalFullscreenExit(event)
case AssessmentSignalFullscreenExit, AssessmentSignalScreenshotKey, AssessmentSignalDevtoolsOpen:
return validateAssessmentSignalBare(event)
default:
return ErrInvalidAssessmentSignal
}
@@ -183,7 +191,7 @@ func validateAssessmentSignalClipboard(event AssessmentSignalEvent) error {
return nil
}
func validateAssessmentSignalFullscreenExit(event AssessmentSignalEvent) error {
func validateAssessmentSignalBare(event AssessmentSignalEvent) error {
if event.hasDuration || event.hasSize {
return ErrInvalidAssessmentSignal
}
@@ -56,6 +56,21 @@ type AssessmentSignalPolicy struct {
ClientFocusLossAttentionMS int32
ClientClipboardEventsAttention int32
ClientFullscreenExitsAttention int32
// The signals below were added after the policy section was first
// published, so a stored version does not carry them. A zero threshold
// leaves the signal out of the band, and a version never acquires a
// default: the facts are stored and counted for the operator either way.
//
// ClientScreenshotKeysAttention and ClientDevtoolsAttention are client
// thresholds, so they raise a normal band to attention only.
ClientScreenshotKeysAttention int32
ClientDevtoolsAttention int32
// ExtraAgents counts the distinct User-Agent digests of the attempt beyond
// the first. It joins the weak group of parallel sessions and extra
// networks, so alone it reaches attention at most.
ExtraAgentsAttention int32
ExtraAgentsReview int32
}
// Sanity bounds of the signal section. They reject a value in the wrong unit;
@@ -99,6 +114,20 @@ func DemoAssessmentSignalPolicy() AssessmentSignalPolicy {
}
}
// DemoAssessmentSignalPolicyWithCaptureHints is the demonstration policy with
// the optional signals switched on: three screenshot keys, one detection of
// open developer tools, and two extra User-Agents reach attention. Like the
// other demo values they are agreed starting points that no study supports.
// DemoAssessmentSignalPolicy itself stays as it was published, because a stored
// version never changes.
func DemoAssessmentSignalPolicyWithCaptureHints() AssessmentSignalPolicy {
policy := DemoAssessmentSignalPolicy()
policy.ClientScreenshotKeysAttention = 3
policy.ClientDevtoolsAttention = 1
policy.ExtraAgentsAttention, policy.ExtraAgentsReview = 2, 4
return policy
}
// Validate rejects a zero, out-of-range, or inconsistent section.
func (policy AssessmentSignalPolicy) Validate() error {
const location = "AssessmentSignalPolicy.Validate"
@@ -115,6 +144,21 @@ func (policy AssessmentSignalPolicy) Validate() error {
); err != nil {
return err
}
if err := firstError(
checkOptionalRange(location, "assessment.signals.client_screenshot_keys_attention", policy.ClientScreenshotKeysAttention, maxSignalCount),
checkOptionalRange(location, "assessment.signals.client_devtools_attention", policy.ClientDevtoolsAttention, maxSignalCount),
checkOptionalRange(location, "assessment.signals.extra_agents_attention", policy.ExtraAgentsAttention, maxSignalCount),
); err != nil {
return err
}
if policy.ExtraAgentsAttention == 0 && policy.ExtraAgentsReview != 0 {
return invalidPolicy(location, "assessment.signals.extra_agents_review needs extra_agents_attention")
}
if policy.ExtraAgentsAttention != 0 {
if err := checkRange(location, "assessment.signals.extra_agents_review", policy.ExtraAgentsReview, policy.ExtraAgentsAttention, maxSignalCount); err != nil {
return err
}
}
for _, pair := range []struct {
field string
attention, review int32
@@ -135,3 +179,12 @@ func (policy AssessmentSignalPolicy) Validate() error {
}
return nil
}
// checkOptionalRange accepts zero, which leaves an optional signal out, or a
// value from 1 to maximum.
func checkOptionalRange(location, field string, value, maximum int32) error {
if value == 0 {
return nil
}
return checkRange(location, field, value, 1, maximum)
}
@@ -2,6 +2,7 @@ package domain
import (
"errors"
"strings"
"testing"
)
@@ -78,3 +79,66 @@ func TestSignalPolicyRejectsOutOfRangeAndInconsistentValues(t *testing.T) {
})
}
}
// A version published before the capture hints existed carries none of their
// fields. It must decode with the hints switched off and encode back to the same
// document, so its content hash and the bands of its attempts never change.
func TestPolicyWithoutCaptureThresholdsDecodesOffAndEncodesUnchanged(t *testing.T) {
policy := DemoProductPolicyV3()
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
for _, field := range []string{"client_screenshot_keys_attention", "client_devtools_attention", "extra_agents_attention", "extra_agents_review"} {
if strings.Contains(string(encoded), field) {
t.Fatalf("the document of the published policy holds %q, want it absent", field)
}
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
signals := decoded.Assessment.Signals
if signals == nil || signals.ClientScreenshotKeysAttention != 0 || signals.ClientDevtoolsAttention != 0 || signals.ExtraAgentsAttention != 0 || signals.ExtraAgentsReview != 0 {
t.Fatalf("decoded signals = %+v, want the capture hints off", signals)
}
again, _, err := encodeProductPolicy(decoded)
if err != nil || string(again) != string(encoded) {
t.Fatalf("re-encoded document differs from the stored one (error %v)", err)
}
}
func TestCaptureThresholdsRoundTripAndAreValidated(t *testing.T) {
signals := DemoAssessmentSignalPolicyWithCaptureHints()
if signals.ClientScreenshotKeysAttention == 0 || signals.ClientDevtoolsAttention == 0 || signals.ExtraAgentsAttention == 0 {
t.Fatalf("DemoAssessmentSignalPolicyWithCaptureHints() = %+v, want the hints switched on", signals)
}
policy := DemoProductPolicyV3()
policy.Assessment.Signals = &signals
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil || decoded.Assessment.Signals == nil || *decoded.Assessment.Signals != signals {
t.Fatalf("decoded signals = %+v, error %v, want the thresholds back", decoded.Assessment.Signals, err)
}
if DemoAssessmentSignalPolicy().ClientScreenshotKeysAttention != 0 {
t.Fatal("DemoAssessmentSignalPolicy gained a capture threshold; a stored version must not change")
}
for name, change := range map[string]func(*AssessmentSignalPolicy){
"negative threshold": func(policy *AssessmentSignalPolicy) { policy.ClientDevtoolsAttention = -1 },
"threshold beyond the bound": func(policy *AssessmentSignalPolicy) { policy.ClientScreenshotKeysAttention = maxSignalCount + 1 },
"review without attention": func(policy *AssessmentSignalPolicy) { policy.ExtraAgentsAttention, policy.ExtraAgentsReview = 0, 3 },
"review below attention": func(policy *AssessmentSignalPolicy) { policy.ExtraAgentsAttention, policy.ExtraAgentsReview = 4, 3 },
"attention without a review": func(policy *AssessmentSignalPolicy) { policy.ExtraAgentsAttention, policy.ExtraAgentsReview = 2, 0 },
} {
t.Run(name, func(t *testing.T) {
policy := DemoAssessmentSignalPolicyWithCaptureHints()
change(&policy)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err)
}
})
}
}
@@ -49,6 +49,7 @@ const (
AssessmentReviewReasonDeviatingAnswers AssessmentReviewReason = "deviating_answers"
AssessmentReviewReasonParallelSessions AssessmentReviewReason = "parallel_sessions"
AssessmentReviewReasonExtraNetworks AssessmentReviewReason = "extra_networks"
AssessmentReviewReasonExtraAgents AssessmentReviewReason = "extra_agents"
AssessmentReviewReasonDuplicateAnswers AssessmentReviewReason = "duplicate_answers"
AssessmentReviewReasonClientSignals AssessmentReviewReason = "client_signals"
)
@@ -57,7 +58,7 @@ const (
func (reason AssessmentReviewReason) IsKnown() bool {
switch reason {
case AssessmentReviewReasonFastAnswers, AssessmentReviewReasonDeviatingAnswers,
AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks,
AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks, AssessmentReviewReasonExtraAgents,
AssessmentReviewReasonDuplicateAnswers, AssessmentReviewReasonClientSignals:
return true
default:
@@ -129,15 +130,17 @@ func (observation AssessmentAnswerObservation) Validate() error {
type AssessmentOriginSource string
const (
AssessmentOriginAnswer AssessmentOriginSource = "answer"
AssessmentOriginSignals AssessmentOriginSource = "signals"
AssessmentOriginAnswer AssessmentOriginSource = "answer"
AssessmentOriginSignals AssessmentOriginSource = "signals"
AssessmentOriginWorkSession AssessmentOriginSource = "work_session"
)
// 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.
// authenticated session, of the client network, and of the User-Agent. 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 and AgentDigest when
// the request had no User-Agent; the raw User-Agent is never stored.
type AssessmentOriginMark struct {
ID uuid.UUID
AttemptID AssessmentAttemptID
@@ -145,6 +148,7 @@ type AssessmentOriginMark struct {
ObservedAt time.Time
SessionDigest AssessmentDigest
NetworkDigest AssessmentDigest
AgentDigest AssessmentDigest
KeyVersion int16
}
@@ -154,7 +158,7 @@ func (mark AssessmentOriginMark) Validate() error {
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 {
if mark.Source != AssessmentOriginAnswer && mark.Source != AssessmentOriginSignals && mark.Source != AssessmentOriginWorkSession {
return fmt.Errorf("%s - source is unknown: %w", location, ErrInvalidAssessmentReview)
}
return nil
@@ -243,6 +247,11 @@ type AssessmentOriginAnomalies struct {
// ExtraNetworks counts the distinct network digests beyond the first. A
// move to another network and back is one extra network.
ExtraNetworks int32
// ExtraAgents counts the distinct User-Agent digests beyond the first, so
// a switch to another browser or device and back is one extra agent. A
// browser that updates itself during an attempt can add one without any
// change of device.
ExtraAgents int32
}
// CountOriginAnomalies orders the marks by time and then by ID and counts
@@ -258,6 +267,7 @@ func CountOriginAnomalies(marks []AssessmentOriginMark) AssessmentOriginAnomalie
var anomalies AssessmentOriginAnomalies
seenSessions := map[AssessmentDigest]struct{}{}
networks := map[AssessmentDigest]struct{}{}
agents := map[AssessmentDigest]struct{}{}
var previousSession AssessmentDigest
for _, mark := range ordered {
_, seen := seenSessions[mark.SessionDigest]
@@ -269,8 +279,12 @@ func CountOriginAnomalies(marks []AssessmentOriginMark) AssessmentOriginAnomalie
if !mark.NetworkDigest.IsZero() {
networks[mark.NetworkDigest] = struct{}{}
}
if !mark.AgentDigest.IsZero() {
agents[mark.AgentDigest] = struct{}{}
}
}
anomalies.ExtraNetworks = int32(max(len(networks)-1, 0)) //nolint:gosec // The number of marks of an attempt is bounded by its stored list.
anomalies.ExtraAgents = int32(max(len(agents)-1, 0)) //nolint:gosec // The number of marks of an attempt is bounded by its stored list.
return anomalies
}
@@ -283,12 +297,16 @@ type AssessmentReviewMeasures struct {
DeviatingAnswers int32
ParallelAlternations int32
ExtraNetworks int32
ExtraAgents int32
MatchedIntegerItems int32
MatchedSequenceItems int32
DuplicateEvidenceBits int32
ClientFocusLossMS int64
ClientClipboardEvents int32
ClientFullscreenExits int32
// ClientScreenshotKeys and ClientDevtoolsOpens count the weak capture hints.
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
}
// AssessmentReviewOutcome is the computed band with the groups behind it.
@@ -297,12 +315,15 @@ type AssessmentReviewOutcome struct {
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.
// Evaluate computes the band. Server signals decide it. Parallel sessions,
// extra networks, and extra User-Agents are weak and correlated (a phone and a
// laptop produce all three), 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, the weak capture hints (screenshot keys and open developer tools)
// among them, can only raise a normal band to attention, because a browser
// reports them and anyone can forge or suppress them. A threshold of the
// optional signals that is zero in the policy leaves that signal out.
func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures) AssessmentReviewOutcome {
type signal struct {
reason AssessmentReviewReason
@@ -314,6 +335,7 @@ func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures)
{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},
{AssessmentReviewReasonExtraAgents, optionalSignalLevel(measures.ExtraAgents, policy.ExtraAgentsAttention, policy.ExtraAgentsReview), true},
{AssessmentReviewReasonDuplicateAnswers, signalLevel(measures.DuplicateEvidenceBits, policy.DuplicateAttentionBits, policy.DuplicateReviewBits), false},
}
strongRaised := false
@@ -336,9 +358,7 @@ func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures)
outcome.Band = band
}
}
if measures.ClientFocusLossMS >= int64(policy.ClientFocusLossAttentionMS) ||
measures.ClientClipboardEvents >= policy.ClientClipboardEventsAttention ||
measures.ClientFullscreenExits >= policy.ClientFullscreenExitsAttention {
if policy.clientSignalsRaised(measures) {
outcome.Reasons = append(outcome.Reasons, AssessmentReviewReasonClientSignals)
if outcome.Band == AssessmentReviewBandNormal {
outcome.Band = AssessmentReviewBandAttention
@@ -347,6 +367,37 @@ func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures)
return outcome
}
// clientSignalsRaised reports whether any browser-reported measure reaches its
// threshold. The capture hints have thresholds only in a policy version that
// opted in to them.
func (policy AssessmentSignalPolicy) clientSignalsRaised(measures AssessmentReviewMeasures) bool {
return measures.ClientFocusLossMS >= int64(policy.ClientFocusLossAttentionMS) ||
measures.ClientClipboardEvents >= policy.ClientClipboardEventsAttention ||
measures.ClientFullscreenExits >= policy.ClientFullscreenExitsAttention ||
optionalSignalReached(measures.ClientScreenshotKeys, policy.ClientScreenshotKeysAttention) ||
optionalSignalReached(measures.ClientDevtoolsOpens, policy.ClientDevtoolsAttention)
}
// optionalSignalReached is false for a threshold of zero, which switches the
// signal off.
func optionalSignalReached(value, threshold int32) bool {
return threshold > 0 && value >= threshold
}
// optionalSignalLevel is signalLevel for a signal that an older policy version
// does not carry: a zero attention threshold switches it off, and a zero review
// threshold leaves it at attention.
func optionalSignalLevel(value, attention, review int32) AssessmentReviewBand {
switch {
case attention == 0 || value < attention:
return AssessmentReviewBandNormal
case review > 0 && value >= review:
return AssessmentReviewBandReview
default:
return AssessmentReviewBandAttention
}
}
func signalLevel(value, attention, review int32) AssessmentReviewBand {
switch {
case value >= review:
@@ -141,6 +141,88 @@ func TestEvaluateBandFollowsThePolicyAndClientSignalsOnlyRaiseToAttention(t *tes
}
}
func TestWeakCaptureSignalsNeverRaiseTheBandAboveAttention(t *testing.T) {
policy := DemoAssessmentSignalPolicyWithCaptureHints()
if err := policy.Validate(); err != nil {
t.Fatalf("DemoAssessmentSignalPolicyWithCaptureHints().Validate() error = %v", err)
}
huge := int32(1_000_000)
tests := []struct {
name string
measures AssessmentReviewMeasures
wantBand AssessmentReviewBand
wantReasons []AssessmentReviewReason
}{
{"one screenshot key is below the threshold", AssessmentReviewMeasures{ClientScreenshotKeys: policy.ClientScreenshotKeysAttention - 1}, AssessmentReviewBandNormal, nil},
{"screenshot keys at the threshold reach attention", AssessmentReviewMeasures{ClientScreenshotKeys: policy.ClientScreenshotKeysAttention}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonClientSignals}},
{"open developer tools reach attention", AssessmentReviewMeasures{ClientDevtoolsOpens: policy.ClientDevtoolsAttention}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonClientSignals}},
{"however many screenshot keys and detections, attention is the ceiling", AssessmentReviewMeasures{ClientScreenshotKeys: huge, ClientDevtoolsOpens: huge}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonClientSignals}},
{"capture hints do not lift a server signal to review", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ClientScreenshotKeys: huge, ClientDevtoolsOpens: huge}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonClientSignals}},
{"extra agents reach attention", AssessmentReviewMeasures{ExtraAgents: policy.ExtraAgentsAttention}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonExtraAgents}},
{"extra agents alone stop at attention however many", AssessmentReviewMeasures{ExtraAgents: huge}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonExtraAgents}},
{"all weak signals together still stop at attention", AssessmentReviewMeasures{ExtraAgents: huge, ExtraNetworks: huge, ParallelAlternations: huge, ClientScreenshotKeys: huge, ClientDevtoolsOpens: huge}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks, AssessmentReviewReasonExtraAgents, AssessmentReviewReasonClientSignals}},
{"extra agents reach review only beside a strong signal", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ExtraAgents: huge}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonExtraAgents}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := policy.Evaluate(test.measures)
if got.Band != test.wantBand || !slices.Equal(got.Reasons, test.wantReasons) {
t.Fatalf("Evaluate() = %+v, want band %s reasons %v", got, test.wantBand, test.wantReasons)
}
})
}
}
// A policy version published before the capture hints existed has no thresholds
// for them, so the facts are stored and counted but never change its band.
func TestAPolicyWithoutCaptureThresholdsIgnoresTheCaptureHints(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
got := policy.Evaluate(AssessmentReviewMeasures{ClientScreenshotKeys: 1000, ClientDevtoolsOpens: 1000, ExtraAgents: 1000})
if got.Band != AssessmentReviewBandNormal || len(got.Reasons) != 0 {
t.Fatalf("Evaluate() = %+v, want a normal band: the hints have no threshold in this policy", got)
}
}
func TestCountOriginAnomaliesCountsDistinctAgentsBeyondTheFirst(t *testing.T) {
withAgent := func(second int, session, network, agent byte) AssessmentOriginMark {
mark := originMark(second, session, network)
if agent != 0 {
mark.AgentDigest = AssessmentDigest{agent}
}
return mark
}
tests := []struct {
name string
marks []AssessmentOriginMark
want int32
}{
{"one agent", []AssessmentOriginMark{withAgent(1, 1, 1, 1), withAgent(2, 1, 1, 1)}, 0},
{"a request without an agent is skipped", []AssessmentOriginMark{withAgent(1, 1, 1, 1), withAgent(2, 1, 1, 0), withAgent(3, 1, 1, 1)}, 0},
{"a switch to another browser and back is one extra agent", []AssessmentOriginMark{withAgent(1, 1, 1, 1), withAgent(2, 1, 1, 2), withAgent(3, 1, 1, 1)}, 1},
{"three agents", []AssessmentOriginMark{withAgent(1, 1, 1, 1), withAgent(2, 1, 1, 2), withAgent(3, 1, 1, 3)}, 2},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := CountOriginAnomalies(test.marks).ExtraAgents; got != test.want {
t.Fatalf("CountOriginAnomalies().ExtraAgents = %d, want %d", got, test.want)
}
})
}
}
func TestOriginMarkOfAWorkSessionHoldIsValid(t *testing.T) {
mark := originMark(1, 1, 1)
mark.Source = AssessmentOriginWorkSession
mark.AgentDigest = AssessmentDigest{9}
if err := mark.Validate(); err != nil {
t.Fatalf("Validate() error = %v", err)
}
mark.Source = "elsewhere"
if err := mark.Validate(); err == nil {
t.Fatal("Validate() accepted an unknown source")
}
}
func TestEvaluateUsesTheThresholdsOfTheGivenPolicy(t *testing.T) {
measures := AssessmentReviewMeasures{FastAnswers: 4}
strict := DemoAssessmentSignalPolicy()
@@ -25,6 +25,8 @@ func TestAssessmentSignalEventValidatesAllowlistedMeasurements(t *testing.T) {
{name: "paste", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalPaste, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalPaste},
{name: "cut", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCut, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalCut},
{name: "fullscreen exit", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: clientTime}, kind: domain.AssessmentSignalFullscreenExit},
{name: "screenshot key", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalScreenshotKey, ItemInstanceID: itemID, OccurredAt: clientTime}, kind: domain.AssessmentSignalScreenshotKey},
{name: "developer tools open", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalDevtoolsOpen, ItemInstanceID: itemID, OccurredAt: clientTime}, kind: domain.AssessmentSignalDevtoolsOpen},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@@ -62,6 +64,9 @@ func TestAssessmentSignalEventRejectsMismatchedOrUnboundedMeasurements(t *testin
{name: "negative clipboard size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCopy, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: func() *int32 { value := int32(-1); return &value }()}},
{name: "focus with clipboard size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &size, SizeBytes: &size}},
{name: "fullscreen with measurement", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: &size}},
{name: "screenshot key with a size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalScreenshotKey, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: &size}},
{name: "developer tools with a duration", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalDevtoolsOpen, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &size}},
{name: "screenshot key without an item", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalScreenshotKey, OccurredAt: validTime}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@@ -0,0 +1,95 @@
package domain
import (
"errors"
"fmt"
"time"
)
// ErrInvalidAssessmentWorkLease reports a malformed work session lease.
var ErrInvalidAssessmentWorkLease = errors.New("invalid assessment work lease")
const (
// AssessmentWorkLeaseDuration is how long a hold of the work session lasts
// after its last renewal. It is long enough for a background tab, whose
// timers a browser slows to about one a minute, to renew in time, and short
// enough that a crashed page frees the attempt for the candidate quickly.
AssessmentWorkLeaseDuration = 2 * time.Minute
// AssessmentWorkLeaseRenewEvery is how often a page repeats the hold.
AssessmentWorkLeaseRenewEvery = 15 * time.Second
)
// AssessmentWorkLease is the hold of the single active work session of a real
// attempt. One open page holds it at a time: it is a rule that keeps one
// attempt from being worked on in two windows, not a lock on the candidate. The
// holder is only a keyed digest of the identifier the page generated, so the
// value never reaches the store.
type AssessmentWorkLease struct {
AttemptID AssessmentAttemptID
Holder AssessmentDigest
KeyVersion int16
// AcquiredAt is when the current holder took the session; a renewal keeps it.
AcquiredAt time.Time
RenewedAt time.Time
// ReleasedAt is set when the holder closed its page, and zero otherwise.
ReleasedAt time.Time
}
// Validate checks that the lease can be stored.
func (lease AssessmentWorkLease) Validate() error {
const location = "AssessmentWorkLease.Validate"
switch {
case lease.AttemptID.IsZero(), lease.Holder.IsZero(), lease.KeyVersion < 1:
return fmt.Errorf("%s - attempt, holder, and key version are required: %w", location, ErrInvalidAssessmentWorkLease)
case lease.AcquiredAt.IsZero(), lease.RenewedAt.Before(lease.AcquiredAt):
return fmt.Errorf("%s - acquisition and renewal times are inconsistent: %w", location, ErrInvalidAssessmentWorkLease)
case !lease.ReleasedAt.IsZero() && lease.ReleasedAt.Before(lease.AcquiredAt):
return fmt.Errorf("%s - release predates acquisition: %w", location, ErrInvalidAssessmentWorkLease)
}
return nil
}
// ActiveAt reports whether the hold is in force at the time: not released and
// renewed within AssessmentWorkLeaseDuration.
func (lease AssessmentWorkLease) ActiveAt(now time.Time) bool {
return lease.ReleasedAt.IsZero() && now.Before(lease.RenewedAt.Add(AssessmentWorkLeaseDuration))
}
// HeldUntil is the end of the hold if it is not renewed.
func (lease AssessmentWorkLease) HeldUntil() time.Time {
return lease.RenewedAt.Add(AssessmentWorkLeaseDuration)
}
// AdmitsHolder reports whether a page with the given holder digest may work on
// the attempt now: nobody holds it, the hold was released or has expired, or
// the page is the holder. An absent lease is passed as the zero value.
func (lease AssessmentWorkLease) AdmitsHolder(holder AssessmentDigest, now time.Time) bool {
return lease.Holder.IsZero() || !lease.ActiveAt(now) || lease.Holder == holder
}
// Held returns the lease after the page took or renewed it at the time. A
// change of holder, a released hold, or an expired hold starts a new
// acquisition; a renewal by the holder keeps the acquisition time.
func (lease AssessmentWorkLease) Held(
attemptID AssessmentAttemptID,
holder AssessmentDigest,
keyVersion int16,
now time.Time,
) AssessmentWorkLease {
renewal := !lease.Holder.IsZero() && lease.Holder == holder && lease.ActiveAt(now)
next := AssessmentWorkLease{AttemptID: attemptID, Holder: holder, KeyVersion: keyVersion, AcquiredAt: now, RenewedAt: now}
if renewal && lease.KeyVersion == keyVersion {
next.AcquiredAt = lease.AcquiredAt
}
return next
}
// ReleasedBy returns the lease released by the holder at the time. Any other
// page, and a lease that is no longer held, leave it as it is.
func (lease AssessmentWorkLease) ReleasedBy(holder AssessmentDigest, now time.Time) AssessmentWorkLease {
if lease.Holder.IsZero() || lease.Holder != holder || !lease.ReleasedAt.IsZero() {
return lease
}
lease.ReleasedAt = now
return lease
}
@@ -0,0 +1,121 @@
package domain
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
)
var leaseStart = time.Date(2026, time.October, 11, 9, 0, 0, 0, time.UTC)
func leaseAttempt() AssessmentAttemptID { return AssessmentAttemptID(uuid.New()) }
func TestOnePageHoldsTheWorkSessionAndAnotherIsRefusedUntilItIsClosed(t *testing.T) {
attempt := leaseAttempt()
first, second := AssessmentDigest{1}, AssessmentDigest{2}
var none AssessmentWorkLease
if !none.AdmitsHolder(first, leaseStart) {
t.Fatal("an attempt that nobody holds refused a page")
}
held := none.Held(attempt, first, 1, leaseStart)
if err := held.Validate(); err != nil {
t.Fatalf("Held().Validate() error = %v", err)
}
if held.AdmitsHolder(second, leaseStart.Add(time.Second)) {
t.Fatal("a second page was admitted while the first one holds the work session")
}
if !held.AdmitsHolder(first, leaseStart.Add(time.Second)) {
t.Fatal("the holder was refused")
}
// Closing the page frees the session at once.
released := held.ReleasedBy(first, leaseStart.Add(5*time.Second))
if released.ActiveAt(leaseStart.Add(6*time.Second)) || !released.AdmitsHolder(second, leaseStart.Add(6*time.Second)) {
t.Fatal("the session is still held after the holder released it")
}
if err := released.Validate(); err != nil {
t.Fatalf("released lease Validate() error = %v", err)
}
// The second page takes it over as a new acquisition.
taken := released.Held(attempt, second, 1, leaseStart.Add(7*time.Second))
if taken.Holder != second || !taken.AcquiredAt.Equal(leaseStart.Add(7*time.Second)) || !taken.ReleasedAt.IsZero() {
t.Fatalf("takeover = %+v, want a fresh hold of the second page", taken)
}
}
func TestAHoldExpiresWhenThePageStopsRenewing(t *testing.T) {
attempt := leaseAttempt()
first, second := AssessmentDigest{1}, AssessmentDigest{2}
held := AssessmentWorkLease{}.Held(attempt, first, 1, leaseStart)
before := leaseStart.Add(AssessmentWorkLeaseDuration - time.Second)
if held.AdmitsHolder(second, before) {
t.Fatal("the hold ended before its duration")
}
if got, want := held.HeldUntil(), leaseStart.Add(AssessmentWorkLeaseDuration); !got.Equal(want) {
t.Fatalf("HeldUntil() = %s, want %s", got, want)
}
// A renewal by the holder moves the end and keeps the acquisition time.
renewed := held.Held(attempt, first, 1, leaseStart.Add(time.Minute))
if !renewed.AcquiredAt.Equal(leaseStart) || !renewed.RenewedAt.Equal(leaseStart.Add(time.Minute)) {
t.Fatalf("renewal = %+v, want the first acquisition time and a new renewal time", renewed)
}
if renewed.AdmitsHolder(second, leaseStart.Add(time.Minute+AssessmentWorkLeaseDuration-time.Second)) {
t.Fatal("a renewed hold ended early")
}
// Without a renewal the session is free once the duration has passed.
if !held.AdmitsHolder(second, leaseStart.Add(AssessmentWorkLeaseDuration)) {
t.Fatal("an expired hold refused another page")
}
// The holder coming back after an expiry is a new acquisition, not a renewal.
again := held.Held(attempt, first, 1, leaseStart.Add(time.Hour))
if !again.AcquiredAt.Equal(leaseStart.Add(time.Hour)) {
t.Fatalf("a hold after expiry kept the old acquisition time: %+v", again)
}
}
func TestOnlyTheHolderReleasesAndAReleaseNeverRevealsAnything(t *testing.T) {
attempt := leaseAttempt()
first, second := AssessmentDigest{1}, AssessmentDigest{2}
held := AssessmentWorkLease{}.Held(attempt, first, 1, leaseStart)
if other := held.ReleasedBy(second, leaseStart.Add(time.Second)); other != held {
t.Fatalf("another page changed the lease: %+v", other)
}
once := held.ReleasedBy(first, leaseStart.Add(time.Second))
if twice := once.ReleasedBy(first, leaseStart.Add(2*time.Second)); twice != once {
t.Fatalf("a second release changed the lease: %+v", twice)
}
var none AssessmentWorkLease
if got := none.ReleasedBy(first, leaseStart); got != none {
t.Fatalf("releasing a lease that does not exist changed it: %+v", got)
}
}
func TestWorkLeaseValidationRejectsIncompleteLeases(t *testing.T) {
attempt := leaseAttempt()
valid := AssessmentWorkLease{}.Held(attempt, AssessmentDigest{1}, 1, leaseStart)
for name, change := range map[string]func(*AssessmentWorkLease){
"no attempt": func(lease *AssessmentWorkLease) { lease.AttemptID = AssessmentAttemptID{} },
"no holder": func(lease *AssessmentWorkLease) { lease.Holder = AssessmentDigest{} },
"no key version": func(lease *AssessmentWorkLease) { lease.KeyVersion = 0 },
"renewed before held": func(lease *AssessmentWorkLease) { lease.RenewedAt = lease.AcquiredAt.Add(-time.Second) },
"released before held": func(lease *AssessmentWorkLease) {
lease.ReleasedAt = lease.AcquiredAt.Add(-time.Second)
},
} {
t.Run(name, func(t *testing.T) {
lease := valid
change(&lease)
if err := lease.Validate(); !errors.Is(err, ErrInvalidAssessmentWorkLease) {
t.Fatalf("Validate() error = %v, want ErrInvalidAssessmentWorkLease", err)
}
})
}
if AssessmentWorkLeaseRenewEvery*4 >= AssessmentWorkLeaseDuration {
t.Fatal("a page renews less than four times within a hold, so one slow timer would lose the session")
}
}
@@ -134,6 +134,13 @@ type assessmentSignalsDocument struct {
ClientFocusLossAttentionMS *int32 `json:"client_focus_loss_attention_ms"`
ClientClipboardEventsAttention *int32 `json:"client_clipboard_events_attention"`
ClientFullscreenExitsAttention *int32 `json:"client_fullscreen_exits_attention"`
// The optional signals are absent from a version published before they
// existed and are written only when set, so the stored document and the
// content hash of such a version never change.
ClientScreenshotKeysAttention *int32 `json:"client_screenshot_keys_attention,omitempty"`
ClientDevtoolsAttention *int32 `json:"client_devtools_attention,omitempty"`
ExtraAgentsAttention *int32 `json:"extra_agents_attention,omitempty"`
ExtraAgentsReview *int32 `json:"extra_agents_review,omitempty"`
}
type assessmentTrainingDocument struct {
@@ -354,6 +361,10 @@ func encodeAssessmentSignalPolicy(policy *AssessmentSignalPolicy) *assessmentSig
ClientFocusLossAttentionMS: pointer(policy.ClientFocusLossAttentionMS),
ClientClipboardEventsAttention: pointer(policy.ClientClipboardEventsAttention),
ClientFullscreenExitsAttention: pointer(policy.ClientFullscreenExitsAttention),
ClientScreenshotKeysAttention: optionalPointer(policy.ClientScreenshotKeysAttention),
ClientDevtoolsAttention: optionalPointer(policy.ClientDevtoolsAttention),
ExtraAgentsAttention: optionalPointer(policy.ExtraAgentsAttention),
ExtraAgentsReview: optionalPointer(policy.ExtraAgentsReview),
}
}
@@ -578,6 +589,10 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
ClientFocusLossAttentionMS: require(&reader, "assessment.signals.client_focus_loss_attention_ms", signals.ClientFocusLossAttentionMS),
ClientClipboardEventsAttention: require(&reader, "assessment.signals.client_clipboard_events_attention", signals.ClientClipboardEventsAttention),
ClientFullscreenExitsAttention: require(&reader, "assessment.signals.client_fullscreen_exits_attention", signals.ClientFullscreenExitsAttention),
ClientScreenshotKeysAttention: optionalValue(signals.ClientScreenshotKeysAttention),
ClientDevtoolsAttention: optionalValue(signals.ClientDevtoolsAttention),
ExtraAgentsAttention: optionalValue(signals.ExtraAgentsAttention),
ExtraAgentsReview: optionalValue(signals.ExtraAgentsReview),
}
}
policy := ProductPolicy{
@@ -742,3 +757,23 @@ func require[T any](reader *documentReader, field string, value *T) T {
}
func pointer[T any](value T) *T { return &value }
// optionalPointer is pointer for an optional field: a zero value is left out of
// the document, as if the field had never existed.
func optionalPointer[T comparable](value T) *T {
var zero T
if value == zero {
return nil
}
return &value
}
// optionalValue returns the value behind a pointer of an optional field, or
// the zero value when the document does not carry it.
func optionalValue[T any](value *T) T {
if value == nil {
var zero T
return zero
}
return *value
}