feat(assessment): record capture hints and keep one window per attempt
This commit is contained in:
1 parent
c975a0d506
commit
bb917bf62e
108 files changed
+6649
-139
No files matched your search
@@ -27,6 +27,10 @@ type SubmitAttemptAnswerCommand struct {
|
||||
// Origin is the sender of the request. It feeds the server signals only and
|
||||
// is not part of the idempotency fingerprint.
|
||||
Origin RequestOrigin
|
||||
// Client is the identifier of the open page, or empty when the request has
|
||||
// none. A page that does not hold the work session is refused while another
|
||||
// page does, and the refusal is not stored under the idempotency key.
|
||||
Client string
|
||||
}
|
||||
|
||||
type canonicalAttemptAnswerBody struct {
|
||||
@@ -135,6 +139,9 @@ func (service *AttemptService) submitNewAnswer(
|
||||
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
|
||||
}
|
||||
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
|
||||
if err := service.workSessions.requireHolder(ctx, unit, current, command.Client, databaseTime); err != nil {
|
||||
return fmt.Errorf("%s - check the holder of the work session: %w", location, err)
|
||||
}
|
||||
return service.persistSubmittedAnswer(ctx, unit, repository, scope, command, current, databaseTime, result)
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,7 @@ type AttemptService struct {
|
||||
clock func() time.Time
|
||||
categoryDecisions AssessmentCategoryDecisionService
|
||||
signalObserver *SignalObserver
|
||||
workSessions *WorkSessions
|
||||
}
|
||||
|
||||
// NewAttemptService fails at startup when a required dependency is missing.
|
||||
@@ -538,6 +539,10 @@ type StartAttemptSessionCommand struct {
|
||||
AttemptID domain.AssessmentAttemptID
|
||||
ExpectedVersion int64
|
||||
IdempotencyKey string
|
||||
// Client is the identifier of the open page, or empty when the request has
|
||||
// none. It is not part of the idempotency fingerprint: the refusal that it
|
||||
// can cause is not stored.
|
||||
Client string
|
||||
}
|
||||
|
||||
type canonicalAttemptSessionBody struct {
|
||||
@@ -651,6 +656,9 @@ func (service *AttemptService) startNewSession(
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read database time after attempt lock: %w", location, err)
|
||||
}
|
||||
if err := service.workSessions.requireHolder(ctx, unit, current, command.Client, databaseTime.UTC().Truncate(time.Microsecond)); err != nil {
|
||||
return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - check the holder of the work session: %w", location, err)
|
||||
}
|
||||
updated, _, err := repository.StartOrResumeSession(ctx, command.ActorID, command.AttemptID, command.ExpectedVersion, databaseTime)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict) || errors.Is(err, domain.ErrAssessmentAttemptVersionConflict) {
|
||||
return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict)
|
||||
|
||||
@@ -18,10 +18,12 @@ import (
|
||||
// every candidate acknowledges the new wording. Acknowledgements are stored per
|
||||
// version, so one given for an earlier version never counts for this one.
|
||||
//
|
||||
// Version 3 describes the watermark of the task screen and text, which version
|
||||
// 2 announced as planned; version 2 added the attempt measures to the text;
|
||||
// version 1 listed signals only.
|
||||
const CurrentSignalNoticeVersion int32 = 3
|
||||
// Version 4 added the screenshot-key and developer-tools hints, the User-Agent
|
||||
// digest, and the one-open-page rule, and says plainly that a screenshot or a
|
||||
// photo of the screen cannot be prevented; version 3 described the watermark of
|
||||
// the task screen and text, which version 2 announced as planned; version 2
|
||||
// added the attempt measures to the text; version 1 listed signals only.
|
||||
const CurrentSignalNoticeVersion int32 = 4
|
||||
|
||||
// ErrSignalNoticeVersionMismatch reports an acknowledgement for a notice
|
||||
// version other than the one the server requires.
|
||||
|
||||
@@ -18,12 +18,13 @@ import (
|
||||
)
|
||||
|
||||
// SignalDigester derives the keyed digests that stand for an answer, a login
|
||||
// session, and a client network in the stored server signals. No digest can be
|
||||
// turned back into what it stands for without the server secret.
|
||||
// session, a client network, and a User-Agent in the stored server signals. No
|
||||
// digest can be turned back into what it stands for without the server secret.
|
||||
type SignalDigester interface {
|
||||
AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, canonicalAnswer []byte) domain.AssessmentDigest
|
||||
AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest
|
||||
AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest
|
||||
AssessmentAgentDigest(attemptID uuid.UUID, userAgent string) domain.AssessmentDigest
|
||||
// AssessmentDigestKeyVersion is the key generation of the digests above.
|
||||
AssessmentDigestKeyVersion() int16
|
||||
}
|
||||
@@ -41,13 +42,15 @@ const (
|
||||
signalReviewEndedKey = "ended"
|
||||
)
|
||||
|
||||
// RequestOrigin is what the HTTP adapter knows about the sender of an answer or
|
||||
// a signal batch: the authenticated session and the limiter key of the client
|
||||
// address. It is used only to make digests and is never stored or logged. An
|
||||
// empty ClientKey means the address could not be resolved.
|
||||
// RequestOrigin is what the HTTP adapter knows about the sender of an answer, a
|
||||
// signal batch, or a work session hold: the authenticated session, the limiter
|
||||
// key of the client address, and the User-Agent. It is used only to make
|
||||
// digests and is never stored or logged. An empty ClientKey means the address
|
||||
// could not be resolved, and an empty UserAgent that the request had none.
|
||||
type RequestOrigin struct {
|
||||
SessionID uuid.UUID
|
||||
ClientKey string
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
// SignalObserver records server-side facts of real attempts and schedules the
|
||||
@@ -150,9 +153,9 @@ func answeredSince(snapshot domain.AssessmentAttemptSnapshot) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// recordOrigin stores the session and network digests of an accepted request
|
||||
// when they differ from the last stored mark, which is enough to count session
|
||||
// alternations and distinct networks. A request without a session is not
|
||||
// recordOrigin stores the session, network, and User-Agent digests of an
|
||||
// accepted request when they differ from the last stored mark, which is enough
|
||||
// to count session alternations, distinct networks, and distinct agents. A request without a session is not
|
||||
// marked. The caller holds the attempt row lock, so the last mark is stable.
|
||||
func (observer *SignalObserver) recordOrigin(
|
||||
ctx context.Context,
|
||||
@@ -178,11 +181,15 @@ func (observer *SignalObserver) recordOrigin(
|
||||
if origin.ClientKey != "" {
|
||||
mark.NetworkDigest = observer.digester.AssessmentNetworkDigest(attemptID.UUID(), origin.ClientKey)
|
||||
}
|
||||
if origin.UserAgent != "" {
|
||||
mark.AgentDigest = observer.digester.AssessmentAgentDigest(attemptID.UUID(), origin.UserAgent)
|
||||
}
|
||||
last, found, err := repository.LastOriginMark(ctx, attemptID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read last mark: %w", location, err)
|
||||
}
|
||||
if found && last.SessionDigest == mark.SessionDigest && last.NetworkDigest == mark.NetworkDigest && last.KeyVersion == mark.KeyVersion {
|
||||
if found && last.SessionDigest == mark.SessionDigest && last.NetworkDigest == mark.NetworkDigest &&
|
||||
last.AgentDigest == mark.AgentDigest && last.KeyVersion == mark.KeyVersion {
|
||||
return nil
|
||||
}
|
||||
if err := repository.SaveOriginMark(ctx, mark); err != nil {
|
||||
@@ -409,8 +416,10 @@ func evaluateReview(
|
||||
measures := domain.AssessmentReviewMeasures{
|
||||
AnsweredItems: times.Answered, FastAnswers: times.Fast, DeviatingAnswers: times.Deviating,
|
||||
ParallelAlternations: anomalies.ParallelAlternations, ExtraNetworks: anomalies.ExtraNetworks,
|
||||
ExtraAgents: anomalies.ExtraAgents,
|
||||
ClientFocusLossMS: inputs.ClientFocusLossMS, ClientClipboardEvents: inputs.ClientClipboardCount,
|
||||
ClientFullscreenExits: inputs.ClientFullscreenExit,
|
||||
ClientFullscreenExits: inputs.ClientFullscreenExit, ClientScreenshotKeys: inputs.ClientScreenshotKeys,
|
||||
ClientDevtoolsOpens: inputs.ClientDevtoolsOpens,
|
||||
}
|
||||
if len(best) > 0 {
|
||||
measures.DuplicateEvidenceBits = best[0].EvidenceBits
|
||||
|
||||
@@ -38,6 +38,14 @@ func (signalDigesterFake) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey
|
||||
return domain.AssessmentDigest(sha256.Sum256(append(attemptID[:], clientKey...)))
|
||||
}
|
||||
|
||||
func (signalDigesterFake) AssessmentAgentDigest(attemptID uuid.UUID, userAgent string) domain.AssessmentDigest {
|
||||
return domain.AssessmentDigest(sha256.Sum256(append(append([]byte("agent:"), attemptID[:]...), userAgent...)))
|
||||
}
|
||||
|
||||
func (signalDigesterFake) AssessmentWorkClientDigest(attemptID uuid.UUID, clientID string) domain.AssessmentDigest {
|
||||
return domain.AssessmentDigest(sha256.Sum256(append(append([]byte("client:"), attemptID[:]...), clientID...)))
|
||||
}
|
||||
|
||||
func (signalDigesterFake) AssessmentDigestKeyVersion() int16 { return 7 }
|
||||
|
||||
// signalRepositoryFake records the writes of the observer and the job. The
|
||||
@@ -698,3 +706,84 @@ func TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOriginMarkKeepsTheUserAgentOnlyAsAKeyedDigestAndMarksOnlyChanges(t *testing.T) {
|
||||
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
|
||||
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
|
||||
observer, err := NewSignalObserver(signalDigesterFake{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSignalObserver() error = %v", err)
|
||||
}
|
||||
unit := newSignalUnitFake()
|
||||
const chrome = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/141.0 Safari/537.36"
|
||||
const phone = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148"
|
||||
origin := RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.77", UserAgent: chrome}
|
||||
|
||||
record := func(source domain.AssessmentOriginSource, origin RequestOrigin) {
|
||||
t.Helper()
|
||||
if err := observer.recordOrigin(context.Background(), unit.repository, attempt.ID(), source, signalReviewTestTime, origin); err != nil {
|
||||
t.Fatalf("recordOrigin() error = %v", err)
|
||||
}
|
||||
}
|
||||
record(domain.AssessmentOriginWorkSession, origin)
|
||||
record(domain.AssessmentOriginAnswer, origin)
|
||||
if len(unit.repository.marks) != 1 {
|
||||
t.Fatalf("stored %d marks for two requests of one origin, want one", len(unit.repository.marks))
|
||||
}
|
||||
first := unit.repository.marks[0]
|
||||
if first.Source != domain.AssessmentOriginWorkSession || first.AgentDigest.IsZero() || first.AgentDigest != (signalDigesterFake{}).AssessmentAgentDigest(attempt.ID().UUID(), chrome) {
|
||||
t.Fatalf("first mark = %+v, want a work session mark with the keyed User-Agent digest", first)
|
||||
}
|
||||
// The same session and network with another browser is a change of its own.
|
||||
switched := origin
|
||||
switched.UserAgent = phone
|
||||
record(domain.AssessmentOriginAnswer, switched)
|
||||
if len(unit.repository.marks) != 2 || unit.repository.marks[1].AgentDigest == first.AgentDigest {
|
||||
t.Fatalf("marks after a User-Agent change = %d, want a second mark with another digest", len(unit.repository.marks))
|
||||
}
|
||||
// A request without a User-Agent stores no agent digest.
|
||||
bare := origin
|
||||
bare.UserAgent = ""
|
||||
unit.repository.marks = nil
|
||||
record(domain.AssessmentOriginSignals, bare)
|
||||
if len(unit.repository.marks) != 1 || !unit.repository.marks[0].AgentDigest.IsZero() {
|
||||
t.Fatalf("marks = %+v, want one mark without an agent digest", unit.repository.marks)
|
||||
}
|
||||
stored := fmt.Sprintf("%+v", first)
|
||||
for _, secret := range []string{"Mozilla", "Macintosh", "Chrome", chrome} {
|
||||
if strings.Contains(stored, secret) {
|
||||
t.Fatalf("the stored mark contains %q, want the User-Agent only as a digest", secret)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateReviewCountsExtraAgentsAndCaptureHintsWithoutRaisingBeyondAttention(t *testing.T) {
|
||||
signals := domain.DemoAssessmentSignalPolicyWithCaptureHints()
|
||||
productPolicy := domain.DemoProductPolicyV3()
|
||||
productPolicy.Assessment.Signals = &signals
|
||||
policy := signalReviewPolicyVersion(t, 4, productPolicy)
|
||||
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
|
||||
repository := &signalRepositoryFake{inputs: outbound.AssessmentReviewInputs{
|
||||
ClientScreenshotKeys: 500, ClientDevtoolsOpens: 500,
|
||||
Marks: []domain.AssessmentOriginMark{
|
||||
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{1}},
|
||||
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{2}},
|
||||
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{3}},
|
||||
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{4}},
|
||||
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{5}},
|
||||
},
|
||||
}}
|
||||
if err := evaluateReview(context.Background(), repository, attempt.ID(), policy, signalReviewTestTime); err != nil {
|
||||
t.Fatalf("evaluateReview() error = %v", err)
|
||||
}
|
||||
if len(repository.reviews) != 1 {
|
||||
t.Fatalf("stored %d reviews, want one", len(repository.reviews))
|
||||
}
|
||||
review := repository.reviews[0]
|
||||
if review.Measures.ExtraAgents != 4 || review.Measures.ClientScreenshotKeys != 500 || review.Measures.ClientDevtoolsOpens != 500 {
|
||||
t.Fatalf("measures = %+v, want 4 extra agents and the capture hint counts", review.Measures)
|
||||
}
|
||||
if review.Outcome.Band != domain.AssessmentReviewBandAttention {
|
||||
t.Fatalf("band = %s, want attention: capture hints and extra agents alone never reach review", review.Outcome.Band)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrAttemptWorkSessionBusy reports that another open page holds the work
|
||||
// session of the attempt. It lasts until that page releases the session or
|
||||
// stops renewing it, so it is never stored under an idempotency key.
|
||||
ErrAttemptWorkSessionBusy = errors.New("assessment work session is held by another page")
|
||||
// ErrAttemptWorkSessionState reports an attempt that has no work session to
|
||||
// hold: a training run, or an attempt that has ended or is past its deadline.
|
||||
ErrAttemptWorkSessionState = errors.New("assessment attempt has no work session to hold")
|
||||
// ErrInvalidWorkSessionClient reports a page identifier of the wrong shape.
|
||||
ErrInvalidWorkSessionClient = errors.New("invalid assessment work session client")
|
||||
)
|
||||
|
||||
const (
|
||||
minWorkClientBytes = 16
|
||||
maxWorkClientBytes = 64
|
||||
)
|
||||
|
||||
// WorkSessionDigester derives the keyed digest that stands for an open page in
|
||||
// the stored lease. The digest binds the attempt and cannot be turned back into
|
||||
// the identifier the page generated.
|
||||
type WorkSessionDigester interface {
|
||||
AssessmentWorkClientDigest(attemptID uuid.UUID, clientID string) domain.AssessmentDigest
|
||||
AssessmentDigestKeyVersion() int16
|
||||
}
|
||||
|
||||
// WorkSessions keeps one open page per real attempt: the page that holds the
|
||||
// work session of the attempt works on it, and any other page is refused until
|
||||
// the holder closes or stops renewing. It does not change an attempt, a result,
|
||||
// or a score, and it is a convenience rule, not a security boundary: a client
|
||||
// that never holds the session is refused only while another page does.
|
||||
type WorkSessions struct {
|
||||
transactor outbound.Transactor
|
||||
digester WorkSessionDigester
|
||||
observer *SignalObserver
|
||||
}
|
||||
|
||||
// NewWorkSessions fails at startup when a dependency is missing.
|
||||
func NewWorkSessions(transactor outbound.Transactor, digester WorkSessionDigester) (*WorkSessions, error) {
|
||||
if transactor == nil || digester == nil {
|
||||
return nil, errors.New("assessment.NewWorkSessions - every dependency must be set")
|
||||
}
|
||||
return &WorkSessions{transactor: transactor, digester: digester}, nil
|
||||
}
|
||||
|
||||
// WithSignalObserver makes every hold write an origin mark, which is when a
|
||||
// switch to another session, network, or User-Agent is noticed.
|
||||
func (sessions *WorkSessions) WithSignalObserver(observer *SignalObserver) *WorkSessions {
|
||||
sessions.observer = observer
|
||||
return sessions
|
||||
}
|
||||
|
||||
// WithWorkSessions makes the answer and session commands refuse a page that
|
||||
// does not hold the work session while another page does.
|
||||
func (service *AttemptService) WithWorkSessions(sessions *WorkSessions) *AttemptService {
|
||||
service.workSessions = sessions
|
||||
return service
|
||||
}
|
||||
|
||||
// HoldWorkSessionCommand is one hold or renewal from an open page.
|
||||
type HoldWorkSessionCommand struct {
|
||||
ActorID uuid.UUID
|
||||
AttemptID domain.AssessmentAttemptID
|
||||
// Client is the identifier the page generated when it loaded.
|
||||
Client string
|
||||
Origin RequestOrigin
|
||||
}
|
||||
|
||||
// WorkSessionHold is the answer to a hold: when it ends unless renewed, and how
|
||||
// often the page renews it.
|
||||
type WorkSessionHold struct {
|
||||
HeldUntil time.Time
|
||||
RenewEvery time.Duration
|
||||
}
|
||||
|
||||
// Hold makes the page the holder of the work session, or renews its hold. It
|
||||
// refuses with ErrAttemptWorkSessionBusy while another page holds it. The
|
||||
// request origin of an accepted hold is recorded for the server signals.
|
||||
func (sessions *WorkSessions) Hold(ctx context.Context, command HoldWorkSessionCommand) (WorkSessionHold, error) {
|
||||
const location = "WorkSessions.Hold"
|
||||
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || !validWorkClient(command.Client) {
|
||||
return WorkSessionHold{}, fmt.Errorf("%s - candidate, attempt, and page identifier are required: %w", location, ErrInvalidWorkSessionClient)
|
||||
}
|
||||
var hold WorkSessionHold
|
||||
err := sessions.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
attempts := unit.AssessmentAttempts()
|
||||
kind, err := attempts.GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, ErrAttemptNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
|
||||
}
|
||||
if !isRealAttemptKind(kind) {
|
||||
return fmt.Errorf("%s - a training run has no protected work session: %w", location, ErrAttemptWorkSessionState)
|
||||
}
|
||||
if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil {
|
||||
return fmt.Errorf("%s - authorize work session: %w", location, err)
|
||||
}
|
||||
attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read database time after attempt lock: %w", location, err)
|
||||
}
|
||||
now := databaseTime.UTC().Truncate(time.Microsecond)
|
||||
if !attempt.IsActive() || !now.Before(attempt.ExpiresAt()) {
|
||||
return fmt.Errorf("%s - attempt is terminal or expired: %w", location, ErrAttemptWorkSessionState)
|
||||
}
|
||||
hold, err = sessions.holdInTransaction(ctx, unit, attempt.ID(), command, now)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return WorkSessionHold{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return hold, nil
|
||||
}
|
||||
|
||||
func (sessions *WorkSessions) holdInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
command HoldWorkSessionCommand,
|
||||
now time.Time,
|
||||
) (WorkSessionHold, error) {
|
||||
const location = "WorkSessions.holdInTransaction"
|
||||
leases := unit.AssessmentWorkLeases()
|
||||
holder := sessions.digester.AssessmentWorkClientDigest(attemptID.UUID(), command.Client)
|
||||
current, found, err := leases.Get(ctx, attemptID)
|
||||
if err != nil {
|
||||
return WorkSessionHold{}, fmt.Errorf("%s - read lease: %w", location, err)
|
||||
}
|
||||
if found && !current.AdmitsHolder(holder, now) {
|
||||
return WorkSessionHold{}, fmt.Errorf("%s - another page holds the session until %s: %w", location, current.HeldUntil().Format(time.RFC3339), ErrAttemptWorkSessionBusy)
|
||||
}
|
||||
next := current.Held(attemptID, holder, sessions.digester.AssessmentDigestKeyVersion(), now)
|
||||
if err := leases.Save(ctx, next); err != nil {
|
||||
return WorkSessionHold{}, fmt.Errorf("%s - store lease: %w", location, err)
|
||||
}
|
||||
if err := sessions.observer.recordOrigin(ctx, unit.AssessmentSignals(), attemptID, domain.AssessmentOriginWorkSession, now, command.Origin); err != nil {
|
||||
return WorkSessionHold{}, fmt.Errorf("%s - record request origin: %w", location, err)
|
||||
}
|
||||
return WorkSessionHold{HeldUntil: next.HeldUntil(), RenewEvery: domain.AssessmentWorkLeaseRenewEvery}, nil
|
||||
}
|
||||
|
||||
// ReleaseWorkSessionCommand is the release of a page that is closing.
|
||||
type ReleaseWorkSessionCommand struct {
|
||||
ActorID uuid.UUID
|
||||
AttemptID domain.AssessmentAttemptID
|
||||
Client string
|
||||
}
|
||||
|
||||
// Release frees the work session when the page holds it. It reveals nothing:
|
||||
// a page that is not the holder, and an attempt that is not held, are no-ops.
|
||||
func (sessions *WorkSessions) Release(ctx context.Context, command ReleaseWorkSessionCommand) error {
|
||||
const location = "WorkSessions.Release"
|
||||
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || !validWorkClient(command.Client) {
|
||||
return fmt.Errorf("%s - candidate, attempt, and page identifier are required: %w", location, ErrInvalidWorkSessionClient)
|
||||
}
|
||||
err := sessions.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
attempts := unit.AssessmentAttempts()
|
||||
attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
leases := unit.AssessmentWorkLeases()
|
||||
current, found, err := leases.Get(ctx, attempt.ID())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read lease: %w", location, err)
|
||||
}
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read database time: %w", location, err)
|
||||
}
|
||||
released := current.ReleasedBy(sessions.digester.AssessmentWorkClientDigest(attempt.ID().UUID(), command.Client), databaseTime.UTC().Truncate(time.Microsecond))
|
||||
if released.ReleasedAt.Equal(current.ReleasedAt) {
|
||||
return nil
|
||||
}
|
||||
if err := leases.Save(ctx, released); err != nil {
|
||||
return fmt.Errorf("%s - store released lease: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// requireHolder refuses a command from a page that does not hold the work
|
||||
// session while another page does. The caller holds the row lock of the attempt
|
||||
// and passes the database time read after it. A page that sent no identifier
|
||||
// counts as one anonymous page, so omitting the header is no way around the
|
||||
// rule; an attempt that nobody holds accepts every page. A training run, and a
|
||||
// service without work sessions, are never refused.
|
||||
func (sessions *WorkSessions) requireHolder(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
attempt domain.AssessmentAttempt,
|
||||
client string,
|
||||
now time.Time,
|
||||
) error {
|
||||
const location = "WorkSessions.requireHolder"
|
||||
if sessions == nil || !isRealAttemptKind(attempt.Kind()) {
|
||||
return nil
|
||||
}
|
||||
current, found, err := unit.AssessmentWorkLeases().Get(ctx, attempt.ID())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read lease: %w", location, err)
|
||||
}
|
||||
if !found || current.AdmitsHolder(sessions.digester.AssessmentWorkClientDigest(attempt.ID().UUID(), client), now) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s - another page holds the work session: %w", location, ErrAttemptWorkSessionBusy)
|
||||
}
|
||||
|
||||
// validWorkClient accepts 16 to 64 characters of A-Z, a-z, 0-9, '_' and '-',
|
||||
// the shape of a random identifier encoded for a header.
|
||||
func validWorkClient(value string) bool {
|
||||
if len(value) < minWorkClientBytes || len(value) > maxWorkClientBytes {
|
||||
return false
|
||||
}
|
||||
for index := range len(value) {
|
||||
character := value[index]
|
||||
if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' ||
|
||||
character >= '0' && character <= '9' || character == '_' || character == '-' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// leaseRepositoryFake keeps the lease of the attempts in memory.
|
||||
type leaseRepositoryFake struct {
|
||||
leases map[domain.AssessmentAttemptID]domain.AssessmentWorkLease
|
||||
}
|
||||
|
||||
func (repository *leaseRepositoryFake) Get(_ context.Context, attemptID domain.AssessmentAttemptID) (domain.AssessmentWorkLease, bool, error) {
|
||||
lease, found := repository.leases[attemptID]
|
||||
return lease, found, nil
|
||||
}
|
||||
|
||||
func (repository *leaseRepositoryFake) Save(_ context.Context, lease domain.AssessmentWorkLease) error {
|
||||
if err := lease.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
repository.leases[lease.AttemptID] = lease
|
||||
return nil
|
||||
}
|
||||
|
||||
// workUnitFake offers the lease and the signal repositories of one unit of work.
|
||||
type workUnitFake struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
leases *leaseRepositoryFake
|
||||
signals *signalRepositoryFake
|
||||
}
|
||||
|
||||
func newWorkUnitFake() *workUnitFake {
|
||||
return &workUnitFake{
|
||||
leases: &leaseRepositoryFake{leases: map[domain.AssessmentAttemptID]domain.AssessmentWorkLease{}},
|
||||
signals: &signalRepositoryFake{},
|
||||
}
|
||||
}
|
||||
|
||||
func (unit *workUnitFake) AssessmentWorkLeases() outbound.AssessmentWorkLeaseRepository {
|
||||
return unit.leases
|
||||
}
|
||||
|
||||
func (unit *workUnitFake) AssessmentSignals() outbound.AssessmentSignalRepository {
|
||||
return unit.signals
|
||||
}
|
||||
|
||||
const (
|
||||
pageOne = "page-one-AAAAAAAAAAAAAAAA"
|
||||
pageTwo = "page-two-BBBBBBBBBBBBBBBB"
|
||||
)
|
||||
|
||||
func newTestWorkSessions(t *testing.T) *WorkSessions {
|
||||
t.Helper()
|
||||
observer, err := NewSignalObserver(signalDigesterFake{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSignalObserver() error = %v", err)
|
||||
}
|
||||
sessions, err := NewWorkSessions(&transactorStub{}, signalDigesterFake{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkSessions() error = %v", err)
|
||||
}
|
||||
return sessions.WithSignalObserver(observer)
|
||||
}
|
||||
|
||||
// transactorStub is never run: the tests call the steps that take a unit.
|
||||
type transactorStub struct{ outbound.Transactor }
|
||||
|
||||
func hold(t *testing.T, sessions *WorkSessions, unit *workUnitFake, attemptID domain.AssessmentAttemptID, client string, now time.Time) error {
|
||||
t.Helper()
|
||||
_, err := sessions.holdInTransaction(context.Background(), unit, attemptID, HoldWorkSessionCommand{
|
||||
ActorID: uuid.New(), AttemptID: attemptID, Client: client,
|
||||
Origin: RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.8", UserAgent: "TestBrowser/1.0"},
|
||||
}, now)
|
||||
return err
|
||||
}
|
||||
|
||||
func TestASecondPageIsRefusedUntilTheFirstOneIsClosed(t *testing.T) {
|
||||
sessions := newTestWorkSessions(t)
|
||||
unit := newWorkUnitFake()
|
||||
attemptID := domain.AssessmentAttemptID(uuid.New())
|
||||
now := signalReviewTestTime
|
||||
|
||||
if err := hold(t, sessions, unit, attemptID, pageOne, now); err != nil {
|
||||
t.Fatalf("the first page was refused: %v", err)
|
||||
}
|
||||
if err := hold(t, sessions, unit, attemptID, pageOne, now.Add(15*time.Second)); err != nil {
|
||||
t.Fatalf("the holder was refused its renewal: %v", err)
|
||||
}
|
||||
err := hold(t, sessions, unit, attemptID, pageTwo, now.Add(20*time.Second))
|
||||
if !errors.Is(err, ErrAttemptWorkSessionBusy) {
|
||||
t.Fatalf("second page error = %v, want ErrAttemptWorkSessionBusy", err)
|
||||
}
|
||||
// A refused page changes nothing: the first page still holds the session.
|
||||
if lease := unit.leases.leases[attemptID]; lease.Holder != (signalDigesterFake{}).AssessmentWorkClientDigest(attemptID.UUID(), pageOne) {
|
||||
t.Fatalf("the refusal changed the holder: %+v", lease)
|
||||
}
|
||||
|
||||
// The first page closes: the second takes over at once.
|
||||
lease := unit.leases.leases[attemptID]
|
||||
unit.leases.leases[attemptID] = lease.ReleasedBy(lease.Holder, now.Add(30*time.Second))
|
||||
if err := hold(t, sessions, unit, attemptID, pageTwo, now.Add(31*time.Second)); err != nil {
|
||||
t.Fatalf("the second page was refused after the first one was released: %v", err)
|
||||
}
|
||||
if err := hold(t, sessions, unit, attemptID, pageOne, now.Add(40*time.Second)); !errors.Is(err, ErrAttemptWorkSessionBusy) {
|
||||
t.Fatalf("the closed page got the session back while the second holds it: %v", err)
|
||||
}
|
||||
// A page that is killed stops renewing, and its hold ends by itself.
|
||||
if err := hold(t, sessions, unit, attemptID, pageOne, now.Add(31*time.Second+domain.AssessmentWorkLeaseDuration)); err != nil {
|
||||
t.Fatalf("the first page was refused after the second one stopped renewing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryHoldRecordsTheOriginWithTheUserAgentDigestOnly(t *testing.T) {
|
||||
sessions := newTestWorkSessions(t)
|
||||
unit := newWorkUnitFake()
|
||||
attemptID := domain.AssessmentAttemptID(uuid.New())
|
||||
if err := hold(t, sessions, unit, attemptID, pageOne, signalReviewTestTime); err != nil {
|
||||
t.Fatalf("hold error = %v", err)
|
||||
}
|
||||
if len(unit.signals.marks) != 1 {
|
||||
t.Fatalf("stored %d marks, want one", len(unit.signals.marks))
|
||||
}
|
||||
mark := unit.signals.marks[0]
|
||||
if mark.Source != domain.AssessmentOriginWorkSession || mark.AgentDigest.IsZero() ||
|
||||
mark.AgentDigest != (signalDigesterFake{}).AssessmentAgentDigest(attemptID.UUID(), "TestBrowser/1.0") {
|
||||
t.Fatalf("mark = %+v, want a work session mark with the keyed digest of the User-Agent", mark)
|
||||
}
|
||||
if strings.Contains(fmt.Sprintf("%+v", mark), "TestBrowser") {
|
||||
t.Fatal("the mark carries the raw User-Agent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestACommandFromAPageThatDoesNotHoldTheSessionIsRefusedWhileAnotherDoes(t *testing.T) {
|
||||
sessions := newTestWorkSessions(t)
|
||||
unit := newWorkUnitFake()
|
||||
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
|
||||
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
|
||||
now := signalReviewTestTime
|
||||
|
||||
check := func(client string, at time.Time) error {
|
||||
return sessions.requireHolder(context.Background(), unit, attempt, client, at)
|
||||
}
|
||||
if err := check(pageTwo, now); err != nil {
|
||||
t.Fatalf("an attempt that nobody holds refused a page: %v", err)
|
||||
}
|
||||
if err := hold(t, sessions, unit, attempt.ID(), pageOne, now); err != nil {
|
||||
t.Fatalf("hold error = %v", err)
|
||||
}
|
||||
if err := check(pageOne, now.Add(time.Second)); err != nil {
|
||||
t.Fatalf("the holder was refused: %v", err)
|
||||
}
|
||||
if err := check(pageTwo, now.Add(time.Second)); !errors.Is(err, ErrAttemptWorkSessionBusy) {
|
||||
t.Fatalf("another page error = %v, want ErrAttemptWorkSessionBusy", err)
|
||||
}
|
||||
// Leaving the identifier out is no way around the rule: it is a page of its own.
|
||||
if err := check("", now.Add(time.Second)); !errors.Is(err, ErrAttemptWorkSessionBusy) {
|
||||
t.Fatalf("a request without an identifier error = %v, want ErrAttemptWorkSessionBusy", err)
|
||||
}
|
||||
if err := check(pageTwo, now.Add(domain.AssessmentWorkLeaseDuration)); err != nil {
|
||||
t.Fatalf("a page was refused after the hold expired: %v", err)
|
||||
}
|
||||
|
||||
// A training run has no protected work session, and a service without work
|
||||
// sessions keeps every command as it was.
|
||||
training := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindDemoExpress)
|
||||
unit.leases.leases[training.ID()] = domain.AssessmentWorkLease{}.Held(training.ID(), domain.AssessmentDigest{9}, 7, now)
|
||||
if err := sessions.requireHolder(context.Background(), unit, training, pageTwo, now); err != nil {
|
||||
t.Fatalf("a training run was refused: %v", err)
|
||||
}
|
||||
var none *WorkSessions
|
||||
if err := none.requireHolder(context.Background(), unit, attempt, pageTwo, now); err != nil {
|
||||
t.Fatalf("a service without work sessions refused a page: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageIdentifiersHaveTheShapeOfARandomHeaderValue(t *testing.T) {
|
||||
for _, valid := range []string{pageOne, strings.Repeat("a", 16), strings.Repeat("Z", 64), "abc_DEF-1234567890"} {
|
||||
if !validWorkClient(valid) {
|
||||
t.Errorf("validWorkClient(%q) = false, want true", valid)
|
||||
}
|
||||
}
|
||||
for _, invalid := range []string{"", "short", strings.Repeat("a", 15), strings.Repeat("a", 65), "has space 1234567890", "plus+plus+plus+plus+", "caf\u00e9-caf\u00e9-caf\u00e9-caf\u00e9"} {
|
||||
if validWorkClient(invalid) {
|
||||
t.Errorf("validWorkClient(%q) = true, want false", invalid)
|
||||
}
|
||||
}
|
||||
if _, err := NewWorkSessions(nil, signalDigesterFake{}); err == nil {
|
||||
t.Fatal("NewWorkSessions(nil transactor) succeeded")
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,8 @@ const (
|
||||
labelSignalNetwork = "lincodex/assessment/signal-network/v1"
|
||||
labelResultCursor = "lincodex/assessment/result-history-cursor/v1"
|
||||
labelWatermark = "lincodex/assessment/watermark/v1"
|
||||
labelSignalAgent = "lincodex/assessment/signal-agent/v1"
|
||||
labelWorkClient = "lincodex/assessment/work-client/v1"
|
||||
)
|
||||
|
||||
// Keyring computes the keyed digests of the anonymous identity operations:
|
||||
@@ -55,6 +57,8 @@ type Keyring struct {
|
||||
signalNetworkKey []byte
|
||||
resultCursorKey []byte
|
||||
watermarkKey []byte
|
||||
signalAgentKey []byte
|
||||
workClientKey []byte
|
||||
}
|
||||
|
||||
// NewKeyring derives the purpose keys from secret.
|
||||
@@ -76,6 +80,8 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
signalNetworkKey: derive(secret, labelSignalNetwork),
|
||||
resultCursorKey: derive(secret, labelResultCursor),
|
||||
watermarkKey: derive(secret, labelWatermark),
|
||||
signalAgentKey: derive(secret, labelSignalAgent),
|
||||
workClientKey: derive(secret, labelWorkClient),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -242,3 +248,23 @@ func (keyring *Keyring) AssessmentWatermarkSeed(attemptID uuid.UUID) domain.Asse
|
||||
mac.Write(attemptID[:])
|
||||
return domain.AssessmentWatermarkSeed(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// AssessmentAgentDigest identifies the User-Agent of a request inside one
|
||||
// attempt. The digest changes with the attempt, so it cannot link attempts or
|
||||
// fingerprint a browser across them, and the raw value is never stored.
|
||||
func (keyring *Keyring) AssessmentAgentDigest(attemptID uuid.UUID, userAgent string) domain.AssessmentDigest {
|
||||
mac := hmac.New(sha256.New, keyring.signalAgentKey)
|
||||
mac.Write(attemptID[:])
|
||||
mac.Write([]byte(userAgent))
|
||||
return domain.AssessmentDigest(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// AssessmentWorkClientDigest identifies the open page that holds the work
|
||||
// session of an attempt from the identifier the page generated. The digest
|
||||
// binds the attempt, so the value is not reusable and not linkable.
|
||||
func (keyring *Keyring) AssessmentWorkClientDigest(attemptID uuid.UUID, clientID string) domain.AssessmentDigest {
|
||||
mac := hmac.New(sha256.New, keyring.workClientKey)
|
||||
mac.Write(attemptID[:])
|
||||
mac.Write([]byte(clientID))
|
||||
return domain.AssessmentDigest(mac.Sum(nil))
|
||||
}
|
||||
@@ -147,11 +147,47 @@ func TestAssessmentWatermarkSeedIsKeyedBoundToTheAttemptAndSeparateFromTheDigest
|
||||
}
|
||||
// The purpose key is its own: no other digest of the attempt equals the seed.
|
||||
if seed == domain.AssessmentWatermarkSeed(keyring.AssessmentSessionDigest(attempt, attempt)) ||
|
||||
seed == domain.AssessmentWatermarkSeed(keyring.AssessmentNetworkDigest(attempt, string(attempt[:]))) {
|
||||
seed == domain.AssessmentWatermarkSeed(keyring.AssessmentNetworkDigest(attempt, string(attempt[:]))) ||
|
||||
seed == domain.AssessmentWatermarkSeed(keyring.AssessmentAgentDigest(attempt, string(attempt[:]))) {
|
||||
t.Fatal("the watermark seed shares a key with another assessment digest")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentAgentAndWorkClientDigestsAreKeyedBoundToTheAttemptAndSeparate(t *testing.T) {
|
||||
keyring, err := NewKeyring(bytes.Repeat([]byte{1}, MinKeySecretBytes))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
attempt, otherAttempt := uuid.New(), uuid.New()
|
||||
const agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/141.0"
|
||||
agentDigest := keyring.AssessmentAgentDigest(attempt, agent)
|
||||
if agentDigest != keyring.AssessmentAgentDigest(attempt, agent) {
|
||||
t.Fatal("the User-Agent digest is not deterministic")
|
||||
}
|
||||
if agentDigest == keyring.AssessmentAgentDigest(otherAttempt, agent) {
|
||||
t.Fatal("one User-Agent has the same digest in two attempts, so attempts could be linked")
|
||||
}
|
||||
if agentDigest == keyring.AssessmentAgentDigest(attempt, agent+" ") {
|
||||
t.Fatal("two User-Agents have the same digest")
|
||||
}
|
||||
clientDigest := keyring.AssessmentWorkClientDigest(attempt, "page-one-AAAAAAAAAAAAAAAA")
|
||||
if clientDigest != keyring.AssessmentWorkClientDigest(attempt, "page-one-AAAAAAAAAAAAAAAA") {
|
||||
t.Fatal("the page digest is not deterministic")
|
||||
}
|
||||
if clientDigest == keyring.AssessmentWorkClientDigest(otherAttempt, "page-one-AAAAAAAAAAAAAAAA") ||
|
||||
clientDigest == keyring.AssessmentWorkClientDigest(attempt, "page-two-BBBBBBBBBBBBBBBB") {
|
||||
t.Fatal("the page digest does not separate attempts and pages")
|
||||
}
|
||||
// The empty identifier of a request without the header is a digest of its own.
|
||||
if keyring.AssessmentWorkClientDigest(attempt, "").IsZero() {
|
||||
t.Fatal("the digest of the anonymous page is empty")
|
||||
}
|
||||
// Each purpose has its own key.
|
||||
if agentDigest == keyring.AssessmentWorkClientDigest(attempt, agent) || agentDigest == keyring.AssessmentNetworkDigest(attempt, agent) {
|
||||
t.Fatal("the User-Agent digest shares a key with another purpose")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t *testing.T) {
|
||||
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
|
||||
if err != nil {
|
||||
|
||||
Reference in new issue
Block a user