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

@@ -105,16 +105,18 @@ func Execute(ctx context.Context, command Command, operator Operator, output io.
measures := review.Measures
if _, err := fmt.Fprintf(output,
"attempt: %s\nband: %s\nreasons: %s\npolicy_version: %d\nevaluated_at: %s\nupdated_at: %s\n"+
"answered_items: %d\nfast_answers: %d\ndeviating_answers: %d\nparallel_alternations: %d\nextra_networks: %d\n"+
"answered_items: %d\nfast_answers: %d\ndeviating_answers: %d\nparallel_alternations: %d\nextra_networks: %d\nextra_agents: %d\n"+
"matched_integer_items: %d\nmatched_sequence_items: %d\nduplicate_evidence_bits: %d\n"+
"client_focus_loss_ms: %d\nclient_clipboard_events: %d\nclient_fullscreen_exits: %d\n"+
"note: a hint for a manual check; it changes no result, category, or quota, and browser signals can be forged\n",
"client_screenshot_keys: %d\nclient_devtools_opens: %d\n"+
"note: a hint for a manual check; it changes no result, category, or quota, and browser signals can be forged; "+
"a screenshot or a phone photo cannot be prevented or seen by the page\n",
review.AttemptID, review.Outcome.Band, strings.Join(reasons, ","), review.PolicyVersion,
review.EvaluatedAt.UTC().Format(time.RFC3339), review.UpdatedAt.UTC().Format(time.RFC3339),
measures.AnsweredItems, measures.FastAnswers, measures.DeviatingAnswers, measures.ParallelAlternations,
measures.ExtraNetworks, measures.MatchedIntegerItems, measures.MatchedSequenceItems,
measures.ExtraNetworks, measures.ExtraAgents, measures.MatchedIntegerItems, measures.MatchedSequenceItems,
measures.DuplicateEvidenceBits, measures.ClientFocusLossMS, measures.ClientClipboardEvents,
measures.ClientFullscreenExits,
measures.ClientFullscreenExits, measures.ClientScreenshotKeys, measures.ClientDevtoolsOpens,
); err != nil {
return errors.New("could not write the review")
}
@@ -8147,6 +8147,253 @@ func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool,
}
}
// handleHoldMyAssessmentWorkSessionRequest handles HoldMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page
// at a time. The page that works on the attempt calls this operation when the candidate starts or
// resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until
// `held_until`.
//
// - If nobody holds the work session, the previous holder released it, or its hold expired, the page
// becomes the holder and the answer is 200.
// - If the same page holds it, the hold is renewed and the answer is 200.
// - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page
// is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops
// renewing and its hold expires. The client tells the candidate that the attempt is open in another
// window and does not show the task.
//
// The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no
// protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a
// candidate who closes a page, reloads, or opens the attempt on another device can continue when the
// hold is released or has expired (at most two minutes after the last renewal). It is not a security
// boundary: a client that never calls this operation is refused only while another page holds the
// session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound
// to the attempt; it never stores or returns either value. A change of the User-Agent digest during an
// attempt is a weak server signal for a manual review, never an automatic decision.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the hold (409 state_conflict).
//
// PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session
func (s *Server) handleHoldMyAssessmentWorkSessionRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("HoldMyAssessmentWorkSession"),
semconv.HTTPRequestMethodKey.String("PUT"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/work-session"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), HoldMyAssessmentWorkSessionOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: HoldMyAssessmentWorkSessionOperation,
ID: "HoldMyAssessmentWorkSession",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, HoldMyAssessmentWorkSessionOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, HoldMyAssessmentWorkSessionOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeHoldMyAssessmentWorkSessionParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response HoldMyAssessmentWorkSessionRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: HoldMyAssessmentWorkSessionOperation,
OperationSummary: "Hold the single active work session of a real assessment attempt for this page.",
OperationID: "HoldMyAssessmentWorkSession",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "attempt_id",
In: "path",
}: params.AttemptID,
{
Name: "X-Attempt-Client",
In: "header",
}: params.XAttemptClient,
},
Raw: r,
}
type (
Request = struct{}
Params = HoldMyAssessmentWorkSessionParams
Response = HoldMyAssessmentWorkSessionRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackHoldMyAssessmentWorkSessionParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.HoldMyAssessmentWorkSession(ctx, params)
return response, err
},
)
} else {
response, err = s.h.HoldMyAssessmentWorkSession(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeHoldMyAssessmentWorkSessionResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMyAssessmentResultsRequest handles ListMyAssessmentResults operation.
//
// Requires a candidate session. Returns only completed root and corrective results owned by this
@@ -12599,6 +12846,237 @@ func (s *Server) handleRegisterAccountRequest(args [0]string, argsEscaped bool,
}
}
// handleReleaseMyAssessmentWorkSessionRequest handles ReleaseMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can
// open the attempt in another window at once instead of waiting for the hold to expire. The request is
// idempotent and reveals nothing: it answers 204 whether this page held the session, another page
// holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a
// lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the release (204).
//
// DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session
func (s *Server) handleReleaseMyAssessmentWorkSessionRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ReleaseMyAssessmentWorkSession"),
semconv.HTTPRequestMethodKey.String("DELETE"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/work-session"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ReleaseMyAssessmentWorkSessionOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ReleaseMyAssessmentWorkSessionOperation,
ID: "ReleaseMyAssessmentWorkSession",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ReleaseMyAssessmentWorkSessionOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, ReleaseMyAssessmentWorkSessionOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeReleaseMyAssessmentWorkSessionParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response ReleaseMyAssessmentWorkSessionRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ReleaseMyAssessmentWorkSessionOperation,
OperationSummary: "Release the work session that this page holds.",
OperationID: "ReleaseMyAssessmentWorkSession",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "attempt_id",
In: "path",
}: params.AttemptID,
{
Name: "X-Attempt-Client",
In: "header",
}: params.XAttemptClient,
},
Raw: r,
}
type (
Request = struct{}
Params = ReleaseMyAssessmentWorkSessionParams
Response = ReleaseMyAssessmentWorkSessionRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackReleaseMyAssessmentWorkSessionParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ReleaseMyAssessmentWorkSession(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ReleaseMyAssessmentWorkSession(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeReleaseMyAssessmentWorkSessionResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleRequestMyAccountDeletionRequest handles RequestMyAccountDeletion operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
@@ -15244,6 +15722,12 @@ func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool
// start a session or commit a due transition. A background transition may persist a due outcome
// independently; after that, this command returns the stored terminal attempt without changing it.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in
// another window. That refusal is not stored under the Idempotency-Key, because it lasts only until
// the other page closes or stops renewing. A real attempt that nobody holds is not refused.
//
// The attempt must belong to the candidate of the session. An attempt of another candidate answers 404
// not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no
// operation gives an employer answers, qualification evidence, or attempt history.
@@ -15430,6 +15914,10 @@ func (s *Server) handleStartMyAssessmentAttemptSessionRequest(args [1]string, ar
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
{
Name: "X-Attempt-Client",
In: "header",
}: params.XAttemptClient,
},
Raw: r,
}
@@ -15510,6 +15998,11 @@ func (s *Server) handleStartMyAssessmentAttemptSessionRequest(args [1]string, ar
// public examples are unlimited apart from the sandbox rate limit and never show hidden group results;
// they are planned as a separate operation.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not
// stored under the Idempotency-Key and is checked before the stored answer is replayed.
//
// Repeats and conflicts, per item:
//
// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
@@ -15723,6 +16216,10 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
{
Name: "X-Attempt-Client",
In: "header",
}: params.XAttemptClient,
},
Raw: r,
}
@@ -137,6 +137,10 @@ type HideOrganizationRes interface {
hideOrganizationRes()
}
type HoldMyAssessmentWorkSessionRes interface {
holdMyAssessmentWorkSessionRes()
}
type ListMyAssessmentResultsRes interface {
listMyAssessmentResultsRes()
}
@@ -217,6 +221,10 @@ type RegisterAccountRes interface {
registerAccountRes()
}
type ReleaseMyAssessmentWorkSessionRes interface {
releaseMyAssessmentWorkSessionRes()
}
type RequestMyAccountDeletionRes interface {
requestMyAccountDeletionRes()
}
@@ -2173,6 +2173,170 @@ func (s *AssessmentAvailability) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *AssessmentCaptureSignal) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *AssessmentCaptureSignal) encodeFields(e *jx.Encoder) {
{
e.FieldStart("kind")
s.Kind.Encode(e)
}
{
e.FieldStart("item_instance_id")
s.ItemInstanceID.Encode(e)
}
{
e.FieldStart("occurred_at")
s.OccurredAt.Encode(e)
}
}
var jsonFieldsNameOfAssessmentCaptureSignal = [3]string{
0: "kind",
1: "item_instance_id",
2: "occurred_at",
}
// Decode decodes AssessmentCaptureSignal from json.
func (s *AssessmentCaptureSignal) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode AssessmentCaptureSignal to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "kind":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.Kind.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"kind\"")
}
case "item_instance_id":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.ItemInstanceID.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"item_instance_id\"")
}
case "occurred_at":
requiredBitSet[0] |= 1 << 2
if err := func() error {
if err := s.OccurredAt.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"occurred_at\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode AssessmentCaptureSignal")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfAssessmentCaptureSignal) {
name = jsonFieldsNameOfAssessmentCaptureSignal[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *AssessmentCaptureSignal) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *AssessmentCaptureSignal) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes AssessmentCaptureSignalKind as json.
func (s AssessmentCaptureSignalKind) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes AssessmentCaptureSignalKind from json.
func (s *AssessmentCaptureSignalKind) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode AssessmentCaptureSignalKind to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch AssessmentCaptureSignalKind(v) {
case AssessmentCaptureSignalKindScreenshotKey:
*s = AssessmentCaptureSignalKindScreenshotKey
case AssessmentCaptureSignalKindDevtoolsOpen:
*s = AssessmentCaptureSignalKindDevtoolsOpen
default:
*s = AssessmentCaptureSignalKind(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s AssessmentCaptureSignalKind) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *AssessmentCaptureSignalKind) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *AssessmentCategoryDecisionView) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -9878,6 +10042,26 @@ func (s AssessmentSignalEvent) encodeFields(e *jx.Encoder) {
s.OccurredAt.Encode(e)
}
}
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
switch s.Type {
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent:
e.FieldStart("kind")
e.Str("devtools_open")
case AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
e.FieldStart("kind")
e.Str("screenshot_key")
}
{
s := s.AssessmentCaptureSignal
{
e.FieldStart("item_instance_id")
s.ItemInstanceID.Encode(e)
}
{
e.FieldStart("occurred_at")
s.OccurredAt.Encode(e)
}
}
}
}
@@ -9919,6 +10103,12 @@ func (s *AssessmentSignalEvent) Decode(d *jx.Decoder) error {
case "fullscreen_exit":
s.Type = AssessmentFullscreenExitSignalAssessmentSignalEvent
found = true
case "devtools_open":
s.Type = AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent
found = true
case "screenshot_key":
s.Type = AssessmentSignalEventScreenshotKeyAssessmentSignalEvent
found = true
default:
return errors.Errorf("unknown type %s", typ)
}
@@ -9945,6 +10135,10 @@ func (s *AssessmentSignalEvent) Decode(d *jx.Decoder) error {
if err := s.AssessmentFullscreenExitSignal.Decode(d); err != nil {
return err
}
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
if err := s.AssessmentCaptureSignal.Decode(d); err != nil {
return err
}
default:
return errors.Errorf("inferred invalid type: %s", s.Type)
}
@@ -11003,6 +11197,117 @@ func (s *AssessmentWatermark) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *AssessmentWorkSession) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *AssessmentWorkSession) encodeFields(e *jx.Encoder) {
{
e.FieldStart("held_until")
s.HeldUntil.Encode(e)
}
{
e.FieldStart("renew_after_seconds")
e.Int32(s.RenewAfterSeconds)
}
}
var jsonFieldsNameOfAssessmentWorkSession = [2]string{
0: "held_until",
1: "renew_after_seconds",
}
// Decode decodes AssessmentWorkSession from json.
func (s *AssessmentWorkSession) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode AssessmentWorkSession to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "held_until":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.HeldUntil.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"held_until\"")
}
case "renew_after_seconds":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Int32()
s.RenewAfterSeconds = int32(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"renew_after_seconds\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode AssessmentWorkSession")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000011,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfAssessmentWorkSession) {
name = jsonFieldsNameOfAssessmentWorkSession[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *AssessmentWorkSession) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *AssessmentWorkSession) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *BasicScore) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -24455,6 +24760,196 @@ func (s *HideOrganizationUnauthorized) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionBadRequest as json.
func (s *HoldMyAssessmentWorkSessionBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionBadRequest from json.
func (s *HoldMyAssessmentWorkSessionBadRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionBadRequest to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = HoldMyAssessmentWorkSessionBadRequest(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionBadRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionBadRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionConflict as json.
func (s *HoldMyAssessmentWorkSessionConflict) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionConflict from json.
func (s *HoldMyAssessmentWorkSessionConflict) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionConflict to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = HoldMyAssessmentWorkSessionConflict(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionConflict) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionConflict) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionForbidden as json.
func (s *HoldMyAssessmentWorkSessionForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionForbidden from json.
func (s *HoldMyAssessmentWorkSessionForbidden) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionForbidden to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = HoldMyAssessmentWorkSessionForbidden(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionForbidden) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionForbidden) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionNotFound as json.
func (s *HoldMyAssessmentWorkSessionNotFound) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionNotFound from json.
func (s *HoldMyAssessmentWorkSessionNotFound) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionNotFound to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = HoldMyAssessmentWorkSessionNotFound(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionNotFound) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionNotFound) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionUnauthorized as json.
func (s *HoldMyAssessmentWorkSessionUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionUnauthorized from json.
func (s *HoldMyAssessmentWorkSessionUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionUnauthorized to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = HoldMyAssessmentWorkSessionUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *IdentityRequestAccepted) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -57146,6 +57641,158 @@ func (s *RegistrationRequest) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes ReleaseMyAssessmentWorkSessionBadRequest as json.
func (s *ReleaseMyAssessmentWorkSessionBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ReleaseMyAssessmentWorkSessionBadRequest from json.
func (s *ReleaseMyAssessmentWorkSessionBadRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ReleaseMyAssessmentWorkSessionBadRequest to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = ReleaseMyAssessmentWorkSessionBadRequest(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ReleaseMyAssessmentWorkSessionBadRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ReleaseMyAssessmentWorkSessionBadRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ReleaseMyAssessmentWorkSessionForbidden as json.
func (s *ReleaseMyAssessmentWorkSessionForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ReleaseMyAssessmentWorkSessionForbidden from json.
func (s *ReleaseMyAssessmentWorkSessionForbidden) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ReleaseMyAssessmentWorkSessionForbidden to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = ReleaseMyAssessmentWorkSessionForbidden(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ReleaseMyAssessmentWorkSessionForbidden) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ReleaseMyAssessmentWorkSessionForbidden) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ReleaseMyAssessmentWorkSessionNotFound as json.
func (s *ReleaseMyAssessmentWorkSessionNotFound) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ReleaseMyAssessmentWorkSessionNotFound from json.
func (s *ReleaseMyAssessmentWorkSessionNotFound) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ReleaseMyAssessmentWorkSessionNotFound to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = ReleaseMyAssessmentWorkSessionNotFound(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ReleaseMyAssessmentWorkSessionNotFound) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ReleaseMyAssessmentWorkSessionNotFound) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ReleaseMyAssessmentWorkSessionUnauthorized as json.
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ReleaseMyAssessmentWorkSessionUnauthorized from json.
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ReleaseMyAssessmentWorkSessionUnauthorized to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = ReleaseMyAssessmentWorkSessionUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes RequestMyAccountDeletionForbidden as json.
func (s *RequestMyAccountDeletionForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
@@ -42,6 +42,7 @@ const (
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
GrantMyConsentOperation OperationName = "GrantMyConsent"
HideOrganizationOperation OperationName = "HideOrganization"
HoldMyAssessmentWorkSessionOperation OperationName = "HoldMyAssessmentWorkSession"
ListMyAssessmentResultsOperation OperationName = "ListMyAssessmentResults"
ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory"
ListMyConsentsOperation OperationName = "ListMyConsents"
@@ -62,6 +63,7 @@ const (
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
RegisterAccountOperation OperationName = "RegisterAccount"
ReleaseMyAssessmentWorkSessionOperation OperationName = "ReleaseMyAssessmentWorkSession"
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
RequestMyRepositoryChecksOperation OperationName = "RequestMyRepositoryChecks"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
@@ -2666,6 +2666,138 @@ func decodeHideOrganizationParams(args [1]string, argsEscaped bool, r *http.Requ
return params, nil
}
// HoldMyAssessmentWorkSessionParams is parameters of HoldMyAssessmentWorkSession operation.
type HoldMyAssessmentWorkSessionParams struct {
// Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an
// unknown identifier both answer 404 not_found, so identifiers cannot be enumerated.
AttemptID uuid.UUID
// The page identifier described at AttemptClient. It is required here because the operation exists to
// hold or release the work session of one page.
XAttemptClient string
}
func unpackHoldMyAssessmentWorkSessionParams(packed middleware.Parameters) (params HoldMyAssessmentWorkSessionParams) {
{
key := middleware.ParameterKey{
Name: "attempt_id",
In: "path",
}
params.AttemptID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "X-Attempt-Client",
In: "header",
}
params.XAttemptClient = packed[key].(string)
}
return params
}
func decodeHoldMyAssessmentWorkSessionParams(args [1]string, argsEscaped bool, r *http.Request) (params HoldMyAssessmentWorkSessionParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode path: attempt_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "attempt_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.AttemptID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "attempt_id",
In: "path",
Err: err,
}
}
// Decode header: X-Attempt-Client.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "X-Attempt-Client",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.XAttemptClient = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 16,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.XAttemptClient)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "X-Attempt-Client",
In: "header",
Err: err,
}
}
return params, nil
}
// ListMyAssessmentResultsParams is parameters of ListMyAssessmentResults operation.
type ListMyAssessmentResultsParams struct {
// Maximum number of results per page.
@@ -5833,6 +5965,138 @@ func decodeRegisterAccountParams(args [0]string, argsEscaped bool, r *http.Reque
return params, nil
}
// ReleaseMyAssessmentWorkSessionParams is parameters of ReleaseMyAssessmentWorkSession operation.
type ReleaseMyAssessmentWorkSessionParams struct {
// Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an
// unknown identifier both answer 404 not_found, so identifiers cannot be enumerated.
AttemptID uuid.UUID
// The page identifier described at AttemptClient. It is required here because the operation exists to
// hold or release the work session of one page.
XAttemptClient string
}
func unpackReleaseMyAssessmentWorkSessionParams(packed middleware.Parameters) (params ReleaseMyAssessmentWorkSessionParams) {
{
key := middleware.ParameterKey{
Name: "attempt_id",
In: "path",
}
params.AttemptID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "X-Attempt-Client",
In: "header",
}
params.XAttemptClient = packed[key].(string)
}
return params
}
func decodeReleaseMyAssessmentWorkSessionParams(args [1]string, argsEscaped bool, r *http.Request) (params ReleaseMyAssessmentWorkSessionParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode path: attempt_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "attempt_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.AttemptID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "attempt_id",
In: "path",
Err: err,
}
}
// Decode header: X-Attempt-Client.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "X-Attempt-Client",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.XAttemptClient = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 16,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.XAttemptClient)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "X-Attempt-Client",
In: "header",
Err: err,
}
}
return params, nil
}
// RevokeMyConsentParams is parameters of RevokeMyConsent operation.
type RevokeMyConsentParams struct {
// Consent being revoked. C1 has a deletion-request operation and C4 requires an organization scope.
@@ -6274,6 +6538,15 @@ type StartMyAssessmentAttemptSessionParams struct {
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
// Random identifier that one open page of the assessment attempt generates when it loads and keeps
// until it closes, 16 to 64 characters of `A-Za-z0-9_-`. It names the page that holds the single
// active work session of the attempt (see HoldMyAssessmentWorkSession). The server keeps only a
// one-way keyed digest bound to the attempt, never the value.
//
// A request that omits the header counts as one anonymous client. It is refused with 409
// `state_conflict` while another page holds the work session, and it is accepted while nobody does, so
// a client that predates the header keeps working until a page holds the session.
XAttemptClient OptString `json:",omitempty,omitzero"`
}
func unpackStartMyAssessmentAttemptSessionParams(packed middleware.Parameters) (params StartMyAssessmentAttemptSessionParams) {
@@ -6291,6 +6564,15 @@ func unpackStartMyAssessmentAttemptSessionParams(packed middleware.Parameters) (
}
params.IdempotencyKey = packed[key].(string)
}
{
key := middleware.ParameterKey{
Name: "X-Attempt-Client",
In: "header",
}
if v, ok := packed[key]; ok {
params.XAttemptClient = v.(OptString)
}
}
return params
}
@@ -6395,6 +6677,72 @@ func decodeStartMyAssessmentAttemptSessionParams(args [1]string, argsEscaped boo
Err: err,
}
}
// Decode header: X-Attempt-Client.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "X-Attempt-Client",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotXAttemptClientVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotXAttemptClientVal = c
return nil
}(); err != nil {
return err
}
params.XAttemptClient.SetTo(paramsDotXAttemptClientVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.XAttemptClient.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 16,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "X-Attempt-Client",
In: "header",
Err: err,
}
}
return params, nil
}
@@ -6423,6 +6771,15 @@ type SubmitMyAssessmentAnswerParams struct {
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
// Random identifier that one open page of the assessment attempt generates when it loads and keeps
// until it closes, 16 to 64 characters of `A-Za-z0-9_-`. It names the page that holds the single
// active work session of the attempt (see HoldMyAssessmentWorkSession). The server keeps only a
// one-way keyed digest bound to the attempt, never the value.
//
// A request that omits the header counts as one anonymous client. It is refused with 409
// `state_conflict` while another page holds the work session, and it is accepted while nobody does, so
// a client that predates the header keeps working until a page holds the session.
XAttemptClient OptString `json:",omitempty,omitzero"`
}
func unpackSubmitMyAssessmentAnswerParams(packed middleware.Parameters) (params SubmitMyAssessmentAnswerParams) {
@@ -6440,6 +6797,15 @@ func unpackSubmitMyAssessmentAnswerParams(packed middleware.Parameters) (params
}
params.IdempotencyKey = packed[key].(string)
}
{
key := middleware.ParameterKey{
Name: "X-Attempt-Client",
In: "header",
}
if v, ok := packed[key]; ok {
params.XAttemptClient = v.(OptString)
}
}
return params
}
@@ -6544,6 +6910,72 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h
Err: err,
}
}
// Decode header: X-Attempt-Client.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "X-Attempt-Client",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotXAttemptClientVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotXAttemptClientVal = c
return nil
}(); err != nil {
return err
}
params.XAttemptClient.SetTo(paramsDotXAttemptClientVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.XAttemptClient.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 16,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "X-Attempt-Client",
In: "header",
Err: err,
}
}
return params, nil
}
@@ -3122,6 +3122,101 @@ func encodeHideOrganizationResponse(response HideOrganizationRes, w http.Respons
}
}
func encodeHoldMyAssessmentWorkSessionResponse(response HoldMyAssessmentWorkSessionRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentWorkSessionHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *HoldMyAssessmentWorkSessionBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *HoldMyAssessmentWorkSessionUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *HoldMyAssessmentWorkSessionForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *HoldMyAssessmentWorkSessionNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *HoldMyAssessmentWorkSessionConflict:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(409)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeListMyAssessmentResultsResponse(response ListMyAssessmentResultsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentResultHistoryPageHeaders:
@@ -4874,6 +4969,82 @@ func encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseW
}
}
func encodeReleaseMyAssessmentWorkSessionResponse(response ReleaseMyAssessmentWorkSessionRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ReleaseMyAssessmentWorkSessionNoContent:
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(204)
return nil
case *ReleaseMyAssessmentWorkSessionBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ReleaseMyAssessmentWorkSessionUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ReleaseMyAssessmentWorkSessionForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ReleaseMyAssessmentWorkSessionNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeRequestMyAccountDeletionResponse(response RequestMyAccountDeletionRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ConsentDeletionRequestHeaders:
@@ -11,7 +11,7 @@ import (
)
var (
rn85AllowedHeaders = map[string]string{
rn86AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn9AllowedHeaders = map[string]string{
@@ -20,37 +20,41 @@ var (
rn10AllowedHeaders = map[string]string{
"POST": "Content-Type,Origin",
}
rn80AllowedHeaders = map[string]string{
rn81AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn70AllowedHeaders = map[string]string{
rn71AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn28AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn82AllowedHeaders = map[string]string{
rn83AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn12AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn96AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
rn97AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token",
}
rn23AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn95AllowedHeaders = map[string]string{
rn96AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token",
}
rn80AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
rn58AllowedHeaders = map[string]string{
"DELETE": "X-Attempt-Client,X-Csrf-Token",
"PUT": "X-Attempt-Client,X-Csrf-Token",
}
rn5AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn87AllowedHeaders = map[string]string{
rn88AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn54AllowedHeaders = map[string]string{
@@ -66,26 +70,26 @@ var (
rn20AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn97AllowedHeaders = map[string]string{
rn98AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn73AllowedHeaders = map[string]string{
rn74AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn57AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "X-Csrf-Token",
}
rn92AllowedHeaders = map[string]string{
rn93AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn93AllowedHeaders = map[string]string{
rn94AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn39AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn83AllowedHeaders = map[string]string{
rn84AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn40AllowedHeaders = map[string]string{
@@ -106,16 +110,16 @@ var (
rn47AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn78AllowedHeaders = map[string]string{
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn90AllowedHeaders = map[string]string{
rn91AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn98AllowedHeaders = map[string]string{
rn99AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn88AllowedHeaders = map[string]string{
rn89AllowedHeaders = map[string]string{
"POST": "Content-Type,X-Csrf-Token",
}
rn19AllowedHeaders = map[string]string{
@@ -124,7 +128,7 @@ var (
rn50AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn76AllowedHeaders = map[string]string{
rn77AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
)
@@ -281,7 +285,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn85AllowedHeaders,
allowedHeaders: rn86AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -384,7 +388,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn80AllowedHeaders,
allowedHeaders: rn81AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -408,7 +412,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn70AllowedHeaders,
allowedHeaders: rn71AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -488,7 +492,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn82AllowedHeaders,
allowedHeaders: rn83AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -610,7 +614,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn96AllowedHeaders,
allowedHeaders: rn97AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -703,7 +707,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn95AllowedHeaders,
allowedHeaders: rn96AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -730,7 +734,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn79AllowedHeaders,
allowedHeaders: rn80AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -741,6 +745,37 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
case 'w': // Prefix: "work-session"
if l := len("work-session"); len(elem) >= l && elem[0:l] == "work-session" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "DELETE":
s.handleReleaseMyAssessmentWorkSessionRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
case "PUT":
s.handleHoldMyAssessmentWorkSessionRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,PUT",
allowedHeaders: rn58AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
@@ -941,7 +976,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE",
allowedHeaders: rn87AllowedHeaders,
allowedHeaders: rn88AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1183,7 +1218,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn97AllowedHeaders,
allowedHeaders: rn98AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1261,7 +1296,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn73AllowedHeaders,
allowedHeaders: rn74AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1530,7 +1565,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn92AllowedHeaders,
allowedHeaders: rn93AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1557,7 +1592,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn93AllowedHeaders,
allowedHeaders: rn94AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1612,7 +1647,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn83AllowedHeaders,
allowedHeaders: rn84AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -2001,7 +2036,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn78AllowedHeaders,
allowedHeaders: rn79AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2029,7 +2064,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn90AllowedHeaders,
allowedHeaders: rn91AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2059,7 +2094,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn98AllowedHeaders,
allowedHeaders: rn99AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2092,7 +2127,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn88AllowedHeaders,
allowedHeaders: rn89AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2253,7 +2288,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn76AllowedHeaders,
allowedHeaders: rn77AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -2953,6 +2988,40 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
case 'w': // Prefix: "work-session"
if l := len("work-session"); len(elem) >= l && elem[0:l] == "work-session" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "DELETE":
r.name = ReleaseMyAssessmentWorkSessionOperation
r.summary = "Release the work session that this page holds."
r.operationID = "ReleaseMyAssessmentWorkSession"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/work-session"
r.args = args
r.count = 1
return r, true
case "PUT":
r.name = HoldMyAssessmentWorkSessionOperation
r.summary = "Hold the single active work session of a real assessment attempt for this page."
r.operationID = "HoldMyAssessmentWorkSession"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/work-session"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
@@ -1053,6 +1053,92 @@ func (s *AssessmentAvailabilityHeaders) SetResponse(val AssessmentAvailability)
func (*AssessmentAvailabilityHeaders) getMyAssessmentAvailabilityRes() {}
// A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination
// that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on
// macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer
// tools are open (a docked panel changes the window size, or the console reads an object). Both are
// weak: a browser does not see every screenshot, an operating system can take one without a key the
// page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They
// lead to attention in a manual review at most, never to a score change, and they carry no
// measurement.
// Ref: #/components/schemas/AssessmentCaptureSignal
type AssessmentCaptureSignal struct {
Kind AssessmentCaptureSignalKind `json:"kind"`
ItemInstanceID AssessmentItemId `json:"item_instance_id"`
OccurredAt Timestamp `json:"occurred_at"`
}
// GetKind returns the value of Kind.
func (s *AssessmentCaptureSignal) GetKind() AssessmentCaptureSignalKind {
return s.Kind
}
// GetItemInstanceID returns the value of ItemInstanceID.
func (s *AssessmentCaptureSignal) GetItemInstanceID() AssessmentItemId {
return s.ItemInstanceID
}
// GetOccurredAt returns the value of OccurredAt.
func (s *AssessmentCaptureSignal) GetOccurredAt() Timestamp {
return s.OccurredAt
}
// SetKind sets the value of Kind.
func (s *AssessmentCaptureSignal) SetKind(val AssessmentCaptureSignalKind) {
s.Kind = val
}
// SetItemInstanceID sets the value of ItemInstanceID.
func (s *AssessmentCaptureSignal) SetItemInstanceID(val AssessmentItemId) {
s.ItemInstanceID = val
}
// SetOccurredAt sets the value of OccurredAt.
func (s *AssessmentCaptureSignal) SetOccurredAt(val Timestamp) {
s.OccurredAt = val
}
type AssessmentCaptureSignalKind string
const (
AssessmentCaptureSignalKindScreenshotKey AssessmentCaptureSignalKind = "screenshot_key"
AssessmentCaptureSignalKindDevtoolsOpen AssessmentCaptureSignalKind = "devtools_open"
)
// AllValues returns all AssessmentCaptureSignalKind values.
func (AssessmentCaptureSignalKind) AllValues() []AssessmentCaptureSignalKind {
return []AssessmentCaptureSignalKind{
AssessmentCaptureSignalKindScreenshotKey,
AssessmentCaptureSignalKindDevtoolsOpen,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s AssessmentCaptureSignalKind) MarshalText() ([]byte, error) {
switch s {
case AssessmentCaptureSignalKindScreenshotKey:
return []byte(s), nil
case AssessmentCaptureSignalKindDevtoolsOpen:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *AssessmentCaptureSignalKind) UnmarshalText(data []byte) error {
switch AssessmentCaptureSignalKind(data) {
case AssessmentCaptureSignalKindScreenshotKey:
*s = AssessmentCaptureSignalKindScreenshotKey
return nil
case AssessmentCaptureSignalKindDevtoolsOpen:
*s = AssessmentCaptureSignalKindDevtoolsOpen
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// Category decision captured when this result was stored. It is absent from legacy v1 results because
// their current grade cannot be inferred later. It never exposes review identifiers, private answers,
// or the candidate's current category after this decision.
@@ -5118,6 +5204,7 @@ type AssessmentSignalEvent struct {
AssessmentFocusLossSignal AssessmentFocusLossSignal
AssessmentClipboardSignal AssessmentClipboardSignal
AssessmentFullscreenExitSignal AssessmentFullscreenExitSignal
AssessmentCaptureSignal AssessmentCaptureSignal
}
// AssessmentSignalEventType is oneOf type of AssessmentSignalEvent.
@@ -5125,11 +5212,13 @@ type AssessmentSignalEventType string
// Possible values for AssessmentSignalEventType.
const (
AssessmentFocusLossSignalAssessmentSignalEvent AssessmentSignalEventType = "focus_loss"
AssessmentSignalEventCopyAssessmentSignalEvent AssessmentSignalEventType = "copy"
AssessmentSignalEventCutAssessmentSignalEvent AssessmentSignalEventType = "cut"
AssessmentSignalEventPasteAssessmentSignalEvent AssessmentSignalEventType = "paste"
AssessmentFullscreenExitSignalAssessmentSignalEvent AssessmentSignalEventType = "fullscreen_exit"
AssessmentFocusLossSignalAssessmentSignalEvent AssessmentSignalEventType = "focus_loss"
AssessmentSignalEventCopyAssessmentSignalEvent AssessmentSignalEventType = "copy"
AssessmentSignalEventCutAssessmentSignalEvent AssessmentSignalEventType = "cut"
AssessmentSignalEventPasteAssessmentSignalEvent AssessmentSignalEventType = "paste"
AssessmentFullscreenExitSignalAssessmentSignalEvent AssessmentSignalEventType = "fullscreen_exit"
AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent AssessmentSignalEventType = "devtools_open"
AssessmentSignalEventScreenshotKeyAssessmentSignalEvent AssessmentSignalEventType = "screenshot_key"
)
// IsAssessmentFocusLossSignal reports whether AssessmentSignalEvent is AssessmentFocusLossSignal.
@@ -5152,6 +5241,16 @@ func (s AssessmentSignalEvent) IsAssessmentFullscreenExitSignal() bool {
return s.Type == AssessmentFullscreenExitSignalAssessmentSignalEvent
}
// IsAssessmentCaptureSignal reports whether AssessmentSignalEvent is AssessmentCaptureSignal.
func (s AssessmentSignalEvent) IsAssessmentCaptureSignal() bool {
switch s.Type {
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
return true
default:
return false
}
}
// SetAssessmentFocusLossSignal sets AssessmentSignalEvent to AssessmentFocusLossSignal.
func (s *AssessmentSignalEvent) SetAssessmentFocusLossSignal(v AssessmentFocusLossSignal) {
s.Type = AssessmentFocusLossSignalAssessmentSignalEvent
@@ -5233,6 +5332,38 @@ func NewAssessmentFullscreenExitSignalAssessmentSignalEvent(v AssessmentFullscre
return s
}
// SetAssessmentCaptureSignal sets AssessmentSignalEvent to AssessmentCaptureSignal.
// panics if `t` is not associated with AssessmentCaptureSignal
func (s *AssessmentSignalEvent) SetAssessmentCaptureSignal(t AssessmentSignalEventType, v AssessmentCaptureSignal) {
s.Type = t
s.AssessmentCaptureSignal = v
if !s.IsAssessmentCaptureSignal() {
panic(fmt.Errorf("invariant: %v is not AssessmentCaptureSignal", t))
}
}
// GetAssessmentCaptureSignal returns AssessmentCaptureSignal and true boolean if AssessmentSignalEvent is AssessmentCaptureSignal.
func (s AssessmentSignalEvent) GetAssessmentCaptureSignal() (v AssessmentCaptureSignal, ok bool) {
if !s.IsAssessmentCaptureSignal() {
return v, false
}
return s.AssessmentCaptureSignal, true
}
// NewAssessmentSignalEventDevtoolsOpenAssessmentSignalEvent returns new AssessmentSignalEvent from AssessmentCaptureSignal.
func NewAssessmentSignalEventDevtoolsOpenAssessmentSignalEvent(v AssessmentCaptureSignal) AssessmentSignalEvent {
var s AssessmentSignalEvent
s.SetAssessmentCaptureSignal(AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, v)
return s
}
// NewAssessmentSignalEventScreenshotKeyAssessmentSignalEvent returns new AssessmentSignalEvent from AssessmentCaptureSignal.
func NewAssessmentSignalEventScreenshotKeyAssessmentSignalEvent(v AssessmentCaptureSignal) AssessmentSignalEvent {
var s AssessmentSignalEvent
s.SetAssessmentCaptureSignal(AssessmentSignalEventScreenshotKeyAssessmentSignalEvent, v)
return s
}
// State of the notice about the signals that are collected during a real assessment attempt. The
// acknowledgement is a record that the candidate was informed. It is not a consent, grants no purpose,
// and neither enables nor blocks signal storage; C3 remains the only consent that the signal operation
@@ -5668,6 +5799,64 @@ func (s *AssessmentWatermark) SetCode(val string) {
s.Code = val
}
// The work session of a real attempt that the calling page holds. It is a one-page-at-a-time rule for
// the attempt, not a score or a signal, and it changes no result.
// Ref: #/components/schemas/AssessmentWorkSession
type AssessmentWorkSession struct {
HeldUntil Timestamp `json:"held_until"`
// How often the page repeats the hold. It is well below the hold time, so a page whose timer is slowed
// down in the background still renews before its hold expires.
RenewAfterSeconds int32 `json:"renew_after_seconds"`
}
// GetHeldUntil returns the value of HeldUntil.
func (s *AssessmentWorkSession) GetHeldUntil() Timestamp {
return s.HeldUntil
}
// GetRenewAfterSeconds returns the value of RenewAfterSeconds.
func (s *AssessmentWorkSession) GetRenewAfterSeconds() int32 {
return s.RenewAfterSeconds
}
// SetHeldUntil sets the value of HeldUntil.
func (s *AssessmentWorkSession) SetHeldUntil(val Timestamp) {
s.HeldUntil = val
}
// SetRenewAfterSeconds sets the value of RenewAfterSeconds.
func (s *AssessmentWorkSession) SetRenewAfterSeconds(val int32) {
s.RenewAfterSeconds = val
}
// AssessmentWorkSessionHeaders wraps AssessmentWorkSession with response headers.
type AssessmentWorkSessionHeaders struct {
CacheControl CacheControlNoStore
Response AssessmentWorkSession
}
// GetCacheControl returns the value of CacheControl.
func (s *AssessmentWorkSessionHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *AssessmentWorkSessionHeaders) GetResponse() AssessmentWorkSession {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *AssessmentWorkSessionHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *AssessmentWorkSessionHeaders) SetResponse(val AssessmentWorkSession) {
s.Response = val
}
func (*AssessmentWorkSessionHeaders) holdMyAssessmentWorkSessionRes() {}
// Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass
// mark comes from that policy version and never from the handler.
// Ref: #/components/schemas/BasicScore
@@ -11245,6 +11434,26 @@ type HideOrganizationUnauthorized Problem
func (*HideOrganizationUnauthorized) hideOrganizationRes() {}
type HoldMyAssessmentWorkSessionBadRequest Problem
func (*HoldMyAssessmentWorkSessionBadRequest) holdMyAssessmentWorkSessionRes() {}
type HoldMyAssessmentWorkSessionConflict Problem
func (*HoldMyAssessmentWorkSessionConflict) holdMyAssessmentWorkSessionRes() {}
type HoldMyAssessmentWorkSessionForbidden Problem
func (*HoldMyAssessmentWorkSessionForbidden) holdMyAssessmentWorkSessionRes() {}
type HoldMyAssessmentWorkSessionNotFound Problem
func (*HoldMyAssessmentWorkSessionNotFound) holdMyAssessmentWorkSessionRes() {}
type HoldMyAssessmentWorkSessionUnauthorized Problem
func (*HoldMyAssessmentWorkSessionUnauthorized) holdMyAssessmentWorkSessionRes() {}
// Neutral acknowledgement. Its content is identical whether or not the address belongs to an account
// or is already verified, so the response does not enumerate accounts. The client tells the user to
// check the mailbox.
@@ -28930,6 +29139,39 @@ func (s *RegistrationRequest) SetConsentC1(val PersonalDataConsentAcceptance) {
s.ConsentC1 = val
}
type ReleaseMyAssessmentWorkSessionBadRequest Problem
func (*ReleaseMyAssessmentWorkSessionBadRequest) releaseMyAssessmentWorkSessionRes() {}
type ReleaseMyAssessmentWorkSessionForbidden Problem
func (*ReleaseMyAssessmentWorkSessionForbidden) releaseMyAssessmentWorkSessionRes() {}
// ReleaseMyAssessmentWorkSessionNoContent is response for ReleaseMyAssessmentWorkSession operation.
type ReleaseMyAssessmentWorkSessionNoContent struct {
CacheControl CacheControlNoStore
}
// GetCacheControl returns the value of CacheControl.
func (s *ReleaseMyAssessmentWorkSessionNoContent) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// SetCacheControl sets the value of CacheControl.
func (s *ReleaseMyAssessmentWorkSessionNoContent) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
func (*ReleaseMyAssessmentWorkSessionNoContent) releaseMyAssessmentWorkSessionRes() {}
type ReleaseMyAssessmentWorkSessionNotFound Problem
func (*ReleaseMyAssessmentWorkSessionNotFound) releaseMyAssessmentWorkSessionRes() {}
type ReleaseMyAssessmentWorkSessionUnauthorized Problem
func (*ReleaseMyAssessmentWorkSessionUnauthorized) releaseMyAssessmentWorkSessionRes() {}
type RequestMyAccountDeletionForbidden Problem
func (*RequestMyAccountDeletionForbidden) requestMyAccountDeletionRes() {}
@@ -87,6 +87,7 @@ var operationRolesSessionCookie = map[string][]string{
GetOrganizationNeedOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
HoldMyAssessmentWorkSessionOperation: []string{},
ListMyAssessmentResultsOperation: []string{},
ListMyCardAccessHistoryOperation: []string{},
ListMyConsentsOperation: []string{},
@@ -105,6 +106,7 @@ var operationRolesSessionCookie = map[string][]string{
MarkOrganizationNotificationReadOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
ReleaseMyAssessmentWorkSessionOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RequestMyRepositoryChecksOperation: []string{},
RevokeMyConsentOperation: []string{},
@@ -160,11 +162,13 @@ var operationRolesSessionCsrf = map[string][]string{
FinalizeMyAssessmentAttemptOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
HoldMyAssessmentWorkSessionOperation: []string{},
LogoutOperation: []string{},
MarkMyNotificationReadOperation: []string{},
MarkOrganizationNotificationReadOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
ReleaseMyAssessmentWorkSessionOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RequestMyRepositoryChecksOperation: []string{},
RevokeMyConsentOperation: []string{},
@@ -1086,6 +1086,37 @@ type Handler interface {
//
// PUT /api/v1/me/privacy/hidden-organizations/{org_id}
HideOrganization(ctx context.Context, params HideOrganizationParams) (HideOrganizationRes, error)
// HoldMyAssessmentWorkSession implements HoldMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page
// at a time. The page that works on the attempt calls this operation when the candidate starts or
// resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until
// `held_until`.
//
// - If nobody holds the work session, the previous holder released it, or its hold expired, the page
// becomes the holder and the answer is 200.
// - If the same page holds it, the hold is renewed and the answer is 200.
// - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page
// is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops
// renewing and its hold expires. The client tells the candidate that the attempt is open in another
// window and does not show the task.
//
// The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no
// protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a
// candidate who closes a page, reloads, or opens the attempt on another device can continue when the
// hold is released or has expired (at most two minutes after the last renewal). It is not a security
// boundary: a client that never calls this operation is refused only while another page holds the
// session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound
// to the attempt; it never stores or returns either value. A change of the User-Agent digest during an
// attempt is a weak server signal for a manual review, never an automatic decision.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the hold (409 state_conflict).
//
// PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session
HoldMyAssessmentWorkSession(ctx context.Context, params HoldMyAssessmentWorkSessionParams) (HoldMyAssessmentWorkSessionRes, error)
// ListMyAssessmentResults implements ListMyAssessmentResults operation.
//
// Requires a candidate session. Returns only completed root and corrective results owned by this
@@ -1546,6 +1577,21 @@ type Handler interface {
//
// POST /api/v1/identity/registrations
RegisterAccount(ctx context.Context, req *RegistrationRequest, params RegisterAccountParams) (RegisterAccountRes, error)
// ReleaseMyAssessmentWorkSession implements ReleaseMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can
// open the attempt in another window at once instead of waiting for the hold to expire. The request is
// idempotent and reveals nothing: it answers 204 whether this page held the session, another page
// holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a
// lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the release (204).
//
// DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session
ReleaseMyAssessmentWorkSession(ctx context.Context, params ReleaseMyAssessmentWorkSessionParams) (ReleaseMyAssessmentWorkSessionRes, error)
// RequestMyAccountDeletion implements RequestMyAccountDeletion operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
@@ -1915,6 +1961,12 @@ type Handler interface {
// start a session or commit a due transition. A background transition may persist a due outcome
// independently; after that, this command returns the stored terminal attempt without changing it.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in
// another window. That refusal is not stored under the Idempotency-Key, because it lasts only until
// the other page closes or stops renewing. A real attempt that nobody holds is not refused.
//
// The attempt must belong to the candidate of the session. An attempt of another candidate answers 404
// not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no
// operation gives an employer answers, qualification evidence, or attempt history.
@@ -1950,6 +2002,11 @@ type Handler interface {
// public examples are unlimited apart from the sandbox rate limit and never show hidden group results;
// they are planned as a separate operation.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not
// stored under the Idempotency-Key and is checked before the stored answer is replayed.
//
// Repeats and conflicts, per item:
//
// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
@@ -1199,6 +1199,40 @@ func (UnimplementedHandler) HideOrganization(ctx context.Context, params HideOrg
return r, ht.ErrNotImplemented
}
// HoldMyAssessmentWorkSession implements HoldMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page
// at a time. The page that works on the attempt calls this operation when the candidate starts or
// resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until
// `held_until`.
//
// - If nobody holds the work session, the previous holder released it, or its hold expired, the page
// becomes the holder and the answer is 200.
// - If the same page holds it, the hold is renewed and the answer is 200.
// - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page
// is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops
// renewing and its hold expires. The client tells the candidate that the attempt is open in another
// window and does not show the task.
//
// The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no
// protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a
// candidate who closes a page, reloads, or opens the attempt on another device can continue when the
// hold is released or has expired (at most two minutes after the last renewal). It is not a security
// boundary: a client that never calls this operation is refused only while another page holds the
// session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound
// to the attempt; it never stores or returns either value. A change of the User-Agent digest during an
// attempt is a weak server signal for a manual review, never an automatic decision.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the hold (409 state_conflict).
//
// PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session
func (UnimplementedHandler) HoldMyAssessmentWorkSession(ctx context.Context, params HoldMyAssessmentWorkSessionParams) (r HoldMyAssessmentWorkSessionRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMyAssessmentResults implements ListMyAssessmentResults operation.
//
// Requires a candidate session. Returns only completed root and corrective results owned by this
@@ -1719,6 +1753,24 @@ func (UnimplementedHandler) RegisterAccount(ctx context.Context, req *Registrati
return r, ht.ErrNotImplemented
}
// ReleaseMyAssessmentWorkSession implements ReleaseMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can
// open the attempt in another window at once instead of waiting for the hold to expire. The request is
// idempotent and reveals nothing: it answers 204 whether this page held the session, another page
// holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a
// lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the release (204).
//
// DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session
func (UnimplementedHandler) ReleaseMyAssessmentWorkSession(ctx context.Context, params ReleaseMyAssessmentWorkSessionParams) (r ReleaseMyAssessmentWorkSessionRes, _ error) {
return r, ht.ErrNotImplemented
}
// RequestMyAccountDeletion implements RequestMyAccountDeletion operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
@@ -2121,6 +2173,12 @@ func (UnimplementedHandler) SetMySearchStatus(ctx context.Context, req *SearchSt
// start a session or commit a due transition. A background transition may persist a due outcome
// independently; after that, this command returns the stored terminal attempt without changing it.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in
// another window. That refusal is not stored under the Idempotency-Key, because it lasts only until
// the other page closes or stops renewing. A real attempt that nobody holds is not refused.
//
// The attempt must belong to the candidate of the session. An attempt of another candidate answers 404
// not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no
// operation gives an employer answers, qualification evidence, or attempt history.
@@ -2159,6 +2217,11 @@ func (UnimplementedHandler) StartMyAssessmentAttemptSession(ctx context.Context,
// public examples are unlimited apart from the sandbox rate limit and never show hidden group results;
// they are planned as a separate operation.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not
// stored under the Idempotency-Key and is checked before the stored answer is replayed.
//
// Repeats and conflicts, per item:
//
// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
@@ -785,6 +785,40 @@ func (s *AssessmentAvailabilityHeaders) Validate() error {
return nil
}
func (s *AssessmentCaptureSignal) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Kind.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "kind",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s AssessmentCaptureSignalKind) Validate() error {
switch s {
case "screenshot_key":
return nil
case "devtools_open":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *AssessmentCategoryDecisionView) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -4340,6 +4374,11 @@ func (s AssessmentSignalEvent) Validate() error {
return err
}
return nil
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
if err := s.AssessmentCaptureSignal.Validate(); err != nil {
return err
}
return nil
default:
return errors.Errorf("invalid type %q", s.Type)
}
@@ -4824,6 +4863,73 @@ func (s *AssessmentWatermark) Validate() error {
return nil
}
func (s *AssessmentWorkSession) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 3600,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.RenewAfterSeconds)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "renew_after_seconds",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *AssessmentWorkSessionHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *BasicScore) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -10603,6 +10709,46 @@ func (s *HideOrganizationUnauthorized) Validate() error {
return nil
}
func (s *HoldMyAssessmentWorkSessionBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *HoldMyAssessmentWorkSessionConflict) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *HoldMyAssessmentWorkSessionForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *HoldMyAssessmentWorkSessionNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *HoldMyAssessmentWorkSessionUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *IdentityRequestAccepted) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -22964,6 +23110,61 @@ func (s *RegistrationRequest) Validate() error {
return nil
}
func (s *ReleaseMyAssessmentWorkSessionBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ReleaseMyAssessmentWorkSessionForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ReleaseMyAssessmentWorkSessionNoContent) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ReleaseMyAssessmentWorkSessionNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RequestMyAccountDeletionForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -12,10 +12,15 @@ const SessionCookieName = "__Host-lincodex_session"
type sessionRequestMetadataKey struct{}
// maxUserAgentBytes bounds the User-Agent that is kept for the request. A
// browser sends a few hundred bytes; the rest is not a browser.
const maxUserAgentBytes = 512
type sessionRequestMetadata struct {
origin string
originValid bool
incomingToken domain.SecretToken
userAgent string
}
// SessionRequestMetadata records the browser Origin and an optional incoming
@@ -24,7 +29,7 @@ type sessionRequestMetadata struct {
func SessionRequestMetadata() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
metadata := sessionRequestMetadata{}
metadata := sessionRequestMetadata{userAgent: boundedUserAgent(r.Header.Get("User-Agent"))}
origins := r.Header.Values("Origin")
if len(origins) == 1 {
metadata.origin = origins[0]
@@ -55,6 +60,21 @@ func RequestOrigin(ctx context.Context) (string, bool) {
return metadata.origin, ok && metadata.originValid
}
// RequestUserAgent returns the User-Agent of the request, cut to a safe length,
// or an empty string when it had none. It exists to be hashed with a key into a
// signal of the attempt; callers never store or log it.
func RequestUserAgent(ctx context.Context) string {
metadata, _ := ctx.Value(sessionRequestMetadataKey{}).(sessionRequestMetadata)
return metadata.userAgent
}
func boundedUserAgent(value string) string {
if len(value) > maxUserAgentBytes {
return value[:maxUserAgentBytes]
}
return value
}
// IncomingSessionToken returns a parsed token from exactly one session cookie.
// The zero value means missing, malformed, or duplicated input.
func IncomingSessionToken(ctx context.Context) domain.SecretToken {
@@ -3,6 +3,7 @@ package middleware
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"lincodex/backend/internal/domain"
@@ -94,3 +95,32 @@ func TestSessionCookieMatchesOnlyTheBoundaryToken(t *testing.T) {
t.Fatalf("SessionCookieMatches() = %v", matches)
}
}
func TestRequestUserAgentIsBoundedAndAbsentWithoutTheMiddleware(t *testing.T) {
var seen string
handler := SessionRequestMetadata()(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
seen = RequestUserAgent(request.Context())
}))
request := httptest.NewRequest(http.MethodGet, "/api/v1/me/assessment-attempts", nil)
request.Header.Set("User-Agent", "TestBrowser/1.0")
handler.ServeHTTP(httptest.NewRecorder(), request)
if seen != "TestBrowser/1.0" {
t.Fatalf("RequestUserAgent() = %q, want the header value", seen)
}
request = httptest.NewRequest(http.MethodGet, "/api/v1/me/assessment-attempts", nil)
request.Header.Set("User-Agent", strings.Repeat("A", 4*maxUserAgentBytes))
handler.ServeHTTP(httptest.NewRecorder(), request)
if len(seen) != maxUserAgentBytes {
t.Fatalf("RequestUserAgent() length = %d, want it cut to %d bytes", len(seen), maxUserAgentBytes)
}
request = httptest.NewRequest(http.MethodGet, "/api/v1/me/assessment-attempts", nil)
handler.ServeHTTP(httptest.NewRecorder(), request)
if seen != "" {
t.Fatalf("RequestUserAgent() = %q, want empty for a request without the header", seen)
}
if got := RequestUserAgent(request.Context()); got != "" {
t.Fatalf("RequestUserAgent() without the middleware = %q, want empty", got)
}
}
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"math"
"time"
"github.com/google/uuid"
@@ -29,10 +30,18 @@ type AssessmentPresenter interface {
Present(snapshot domain.AssessmentAttemptPublicSnapshot) (domain.AssessmentAttemptPublicSnapshot, error)
}
// AssessmentWorkSessions holds and releases the single active work session of a
// real attempt for the open page that calls.
type AssessmentWorkSessions interface {
Hold(ctx context.Context, command assessmentusecase.HoldWorkSessionCommand) (assessmentusecase.WorkSessionHold, error)
Release(ctx context.Context, command assessmentusecase.ReleaseWorkSessionCommand) error
}
// AssessmentHandler serves the candidate's frozen assessment attempts.
type AssessmentHandler struct {
operations AssessmentOperations
presenter AssessmentPresenter
operations AssessmentOperations
presenter AssessmentPresenter
workSessions AssessmentWorkSessions
}
func NewAssessmentHandler(operations AssessmentOperations) *AssessmentHandler {
@@ -49,6 +58,13 @@ func (handler *AssessmentHandler) WithPresenter(presenter AssessmentPresenter) *
return handler
}
// WithWorkSessions enables the hold and release operations of the work session.
// Without it they answer as not implemented.
func (handler *AssessmentHandler) WithWorkSessions(sessions AssessmentWorkSessions) *AssessmentHandler {
handler.workSessions = sessions
return handler
}
// attemptResponse presents the snapshot and maps it to the response. Every
// operation that returns an attempt goes through it.
func (handler *AssessmentHandler) attemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot) (api.AssessmentAttempt, error) {
@@ -114,6 +130,26 @@ func (handler *Handler) SubmitMyAssessmentAnswer(
return handler.assessment.SubmitMyAssessmentAnswer(ctx, request, params)
}
func (handler *Handler) HoldMyAssessmentWorkSession(
ctx context.Context,
params api.HoldMyAssessmentWorkSessionParams,
) (api.HoldMyAssessmentWorkSessionRes, error) {
if handler.assessment == nil || handler.assessment.workSessions == nil {
return handler.UnimplementedHandler.HoldMyAssessmentWorkSession(ctx, params)
}
return handler.assessment.HoldMyAssessmentWorkSession(ctx, params)
}
func (handler *Handler) ReleaseMyAssessmentWorkSession(
ctx context.Context,
params api.ReleaseMyAssessmentWorkSessionParams,
) (api.ReleaseMyAssessmentWorkSessionRes, error) {
if handler.assessment == nil || handler.assessment.workSessions == nil {
return handler.UnimplementedHandler.ReleaseMyAssessmentWorkSession(ctx, params)
}
return handler.assessment.ReleaseMyAssessmentWorkSession(ctx, params)
}
func (handler *Handler) FinalizeMyAssessmentAttempt(
ctx context.Context,
request *api.AssessmentFinalization,
@@ -199,6 +235,7 @@ func (handler *AssessmentHandler) StartMyAssessmentAttemptSession(
result, err := handler.operations.StartSession(ctx, assessmentusecase.StartAttemptSessionCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
ExpectedVersion: int64(request.ExpectedVersion), IdempotencyKey: params.IdempotencyKey,
Client: params.XAttemptClient.Or(""),
})
if err != nil {
return assessmentSessionFailure(ctx, err)
@@ -236,6 +273,7 @@ func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
ItemID: uuid.UUID(request.ItemID), ExpectedVersion: int64(request.ExpectedVersion),
IdempotencyKey: params.IdempotencyKey, Answer: answer, Origin: assessmentRequestOrigin(ctx),
Client: params.XAttemptClient.Or(""),
})
if err != nil {
return assessmentAnswerFailure(ctx, err)
@@ -250,6 +288,46 @@ func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func (handler *AssessmentHandler) HoldMyAssessmentWorkSession(
ctx context.Context,
params api.HoldMyAssessmentWorkSessionParams,
) (api.HoldMyAssessmentWorkSessionRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.HoldMyAssessmentWorkSessionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
hold, err := handler.workSessions.Hold(ctx, assessmentusecase.HoldWorkSessionCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
Client: params.XAttemptClient, Origin: assessmentRequestOrigin(ctx),
})
if err != nil {
return assessmentHoldFailure(ctx, err)
}
return &api.AssessmentWorkSessionHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.AssessmentWorkSession{
HeldUntil: api.Timestamp(hold.HeldUntil), RenewAfterSeconds: int32(math.Ceil(hold.RenewEvery.Seconds())),
},
}, nil
}
func (handler *AssessmentHandler) ReleaseMyAssessmentWorkSession(
ctx context.Context,
params api.ReleaseMyAssessmentWorkSessionParams,
) (api.ReleaseMyAssessmentWorkSessionRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ReleaseMyAssessmentWorkSessionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
err := handler.workSessions.Release(ctx, assessmentusecase.ReleaseWorkSessionCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID), Client: params.XAttemptClient,
})
if err != nil {
return assessmentReleaseFailure(ctx, err)
}
return &api.ReleaseMyAssessmentWorkSessionNoContent{CacheControl: api.CacheControlNoStoreNoStore}, nil
}
func (handler *AssessmentHandler) FinalizeMyAssessmentAttempt(
ctx context.Context,
request *api.AssessmentFinalization,
@@ -407,6 +485,8 @@ func assessmentSessionFailure(ctx context.Context, err error) (api.StartMyAssess
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
return (*api.StartMyAssessmentAttemptSessionPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptWorkSessionBusy):
return (*api.StartMyAssessmentAttemptSessionConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
return (*api.StartMyAssessmentAttemptSessionUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
@@ -418,6 +498,35 @@ func assessmentSessionFailure(ctx context.Context, err error) (api.StartMyAssess
}
}
func assessmentHoldFailure(ctx context.Context, err error) (api.HoldMyAssessmentWorkSessionRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
return (*api.HoldMyAssessmentWorkSessionForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.HoldMyAssessmentWorkSessionNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptWorkSessionBusy), errors.Is(err, assessmentusecase.ErrAttemptWorkSessionState):
return (*api.HoldMyAssessmentWorkSessionConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidWorkSessionClient):
return (*api.HoldMyAssessmentWorkSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/X-Attempt-Client").Response), nil
default:
return nil, err
}
}
func assessmentReleaseFailure(ctx context.Context, err error) (api.ReleaseMyAssessmentWorkSessionRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
return (*api.ReleaseMyAssessmentWorkSessionForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.ReleaseMyAssessmentWorkSessionNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidWorkSessionClient):
return (*api.ReleaseMyAssessmentWorkSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/X-Attempt-Client").Response), nil
default:
return nil, err
}
}
func assessmentAnswerFailure(ctx context.Context, err error) (api.SubmitMyAssessmentAnswerRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
@@ -428,7 +537,7 @@ func assessmentAnswerFailure(ctx context.Context, err error) (api.SubmitMyAssess
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
return (*api.SubmitMyAssessmentAnswerPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict), errors.Is(err, assessmentusecase.ErrAttemptWorkSessionBusy):
return (*api.SubmitMyAssessmentAnswerConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
return (*api.SubmitMyAssessmentAnswerUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
@@ -3,16 +3,19 @@ package v1
import (
"context"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
// assessmentRequestOrigin hands the authenticated session and the limiter key
// of the client address to the server signals. The usecase turns them into
// keyed digests; neither value is stored or logged.
// assessmentRequestOrigin hands the authenticated session, the limiter key of
// the client address, and the User-Agent to the server signals. The usecase
// turns them into keyed digests; no value is stored or logged.
func assessmentRequestOrigin(ctx context.Context) assessmentusecase.RequestOrigin {
session, ok := sessionFromContext(ctx)
if !ok {
return assessmentusecase.RequestOrigin{}
}
return assessmentusecase.RequestOrigin{SessionID: session.SessionID, ClientKey: clientKey(ctx)}
return assessmentusecase.RequestOrigin{
SessionID: session.SessionID, ClientKey: clientKey(ctx), UserAgent: httpmiddleware.RequestUserAgent(ctx),
}
}
@@ -105,6 +105,9 @@ func assessmentSignalEventInput(requestEvent api.AssessmentSignalEvent) (domain.
return assessmentClipboardInput(requestEvent)
case api.AssessmentFullscreenExitSignalAssessmentSignalEvent:
return assessmentFullscreenExitInput(requestEvent)
case api.AssessmentSignalEventScreenshotKeyAssessmentSignalEvent,
api.AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent:
return assessmentCaptureInput(requestEvent)
default:
return domain.AssessmentSignalEventInput{}, false
}
@@ -149,6 +152,20 @@ func assessmentFullscreenExitInput(requestEvent api.AssessmentSignalEvent) (doma
}, true
}
func assessmentCaptureInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
value, ok := requestEvent.GetAssessmentCaptureSignal()
if !ok {
return domain.AssessmentSignalEventInput{}, false
}
kind := domain.AssessmentSignalKind(value.Kind)
if kind != domain.AssessmentSignalKind(requestEvent.Type) {
return domain.AssessmentSignalEventInput{}, false
}
return domain.AssessmentSignalEventInput{
Kind: kind, ItemInstanceID: uuid.UUID(value.ItemInstanceID), OccurredAt: time.Time(value.OccurredAt),
}, true
}
func signalInvalidBody(ctx context.Context) *api.RecordMyAssessmentAttemptSignalsBadRequest {
return (*api.RecordMyAssessmentAttemptSignalsBadRequest)(
&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response,
@@ -55,8 +55,14 @@ func TestAssessmentSignalHandlerMapsAllowlistedEventVariants(t *testing.T) {
Kind: api.AssessmentFullscreenExitSignalKindFullscreenExit, ItemInstanceID: api.AssessmentItemId(itemID),
OccurredAt: at,
}),
api.NewAssessmentSignalEventScreenshotKeyAssessmentSignalEvent(api.AssessmentCaptureSignal{
Kind: api.AssessmentCaptureSignalKindScreenshotKey, ItemInstanceID: api.AssessmentItemId(itemID), OccurredAt: at,
}),
api.NewAssessmentSignalEventDevtoolsOpenAssessmentSignalEvent(api.AssessmentCaptureSignal{
Kind: api.AssessmentCaptureSignalKindDevtoolsOpen, ItemInstanceID: api.AssessmentItemId(itemID), OccurredAt: at,
}),
}}
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptAccepted, 5, time.Now())
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptAccepted, 7, time.Now())
if err != nil {
t.Fatalf("NewAssessmentSignalReceipt() error = %v", err)
}
@@ -71,18 +77,19 @@ func TestAssessmentSignalHandlerMapsAllowlistedEventVariants(t *testing.T) {
if !ok {
t.Fatalf("RecordMyAssessmentAttemptSignals() result = %T, want receipt headers", result)
}
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.AcceptedEvents != 5 ||
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.AcceptedEvents != 7 ||
response.Response.Status != api.AssessmentSignalReceiptStatusAccepted {
t.Fatalf("receipt response = %+v", response)
}
command := operations.command
if operations.calls != 1 || command.ActorID != actorID || command.AttemptID != domain.AssessmentAttemptID(attemptID) ||
command.IdempotencyKey != "event-batch" || len(command.Events) != 5 {
command.IdempotencyKey != "event-batch" || len(command.Events) != 7 {
t.Fatalf("record command = %+v, calls %d", command, operations.calls)
}
wantKinds := []domain.AssessmentSignalKind{
domain.AssessmentSignalFocusLoss, domain.AssessmentSignalCopy, domain.AssessmentSignalPaste,
domain.AssessmentSignalCut, domain.AssessmentSignalFullscreenExit,
domain.AssessmentSignalScreenshotKey, domain.AssessmentSignalDevtoolsOpen,
}
for index, event := range command.Events {
if event.Kind() != wantKinds[index] || event.ItemInstanceID() != itemID || !event.OccurredAt().Equal(time.Time(at)) {
@@ -99,6 +106,25 @@ func TestAssessmentSignalHandlerMapsAllowlistedEventVariants(t *testing.T) {
}
}
func TestAssessmentSignalHandlerRefusesACaptureEventWhoseKindDisagreesWithItsVariant(t *testing.T) {
itemID := uuid.New()
mismatched := api.NewAssessmentSignalEventDevtoolsOpenAssessmentSignalEvent(api.AssessmentCaptureSignal{
Kind: api.AssessmentCaptureSignalKindScreenshotKey, ItemInstanceID: api.AssessmentItemId(itemID),
OccurredAt: api.Timestamp(time.Now().UTC()),
})
operations := &assessmentSignalOperationsStub{}
handler := NewAssessmentSignalHandler(operations)
result, err := handler.RecordMyAssessmentAttemptSignals(principalForTest(uuid.New()),
&api.AssessmentSignalBatch{Events: []api.AssessmentSignalEvent{mismatched}},
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: uuid.New(), IdempotencyKey: "mismatch"})
if err != nil {
t.Fatalf("RecordMyAssessmentAttemptSignals() error = %v", err)
}
if _, ok := result.(*api.RecordMyAssessmentAttemptSignalsBadRequest); !ok || operations.calls != 0 {
t.Fatalf("mismatched capture event result = %T, calls %d, want a 400 before the usecase", result, operations.calls)
}
}
func TestAssessmentSignalHandlerMapsAuthorizationAndBusinessProblems(t *testing.T) {
for _, testCase := range []struct {
name string
@@ -3,6 +3,7 @@ package v1
import (
"context"
"errors"
"strings"
"testing"
"time"
@@ -305,3 +306,150 @@ func TestAPresenterFailureIsAServerErrorNotAnUnmarkedAttempt(t *testing.T) {
t.Fatal("GetMyAssessmentAttempt() succeeded, want an error so that the task text is never served unmarked")
}
}
type workSessionsStub struct {
holdCommand assessmentusecase.HoldWorkSessionCommand
hold assessmentusecase.WorkSessionHold
holdErr error
releaseCommand assessmentusecase.ReleaseWorkSessionCommand
releaseErr error
}
func (stub *workSessionsStub) Hold(_ context.Context, command assessmentusecase.HoldWorkSessionCommand) (assessmentusecase.WorkSessionHold, error) {
stub.holdCommand = command
return stub.hold, stub.holdErr
}
func (stub *workSessionsStub) Release(_ context.Context, command assessmentusecase.ReleaseWorkSessionCommand) error {
stub.releaseCommand = command
return stub.releaseErr
}
const testPageClient = "page-one-AAAAAAAAAAAAAAAA"
func TestHoldWorkSessionAnswersTheLeaseWithoutTheClientIdentifier(t *testing.T) {
userID, attemptID := uuid.New(), uuid.New()
until := time.Date(2026, time.October, 11, 9, 2, 0, 0, time.UTC)
stub := &workSessionsStub{hold: assessmentusecase.WorkSessionHold{HeldUntil: until, RenewEvery: 15 * time.Second}}
handler := NewAssessmentHandler(&assessmentOperationsStub{}).WithWorkSessions(stub)
response, err := handler.HoldMyAssessmentWorkSession(principalForTest(userID),
api.HoldMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if err != nil {
t.Fatalf("HoldMyAssessmentWorkSession() error = %v", err)
}
headers, ok := response.(*api.AssessmentWorkSessionHeaders)
if !ok || headers.CacheControl != api.CacheControlNoStoreNoStore ||
!time.Time(headers.Response.HeldUntil).Equal(until) || headers.Response.RenewAfterSeconds != 15 {
t.Fatalf("hold response = %T %+v, want a no-store lease that ends at %s", response, response, until)
}
if stub.holdCommand.ActorID != userID || stub.holdCommand.AttemptID != domain.AssessmentAttemptID(attemptID) || stub.holdCommand.Client != testPageClient {
t.Fatalf("hold command = %+v, want the verified principal, the attempt, and the page identifier", stub.holdCommand)
}
encoded, err := headers.Response.MarshalJSON()
if err != nil || strings.Contains(string(encoded), testPageClient) {
t.Fatalf("the response %s repeats the page identifier (error %v)", encoded, err)
}
}
func TestHoldAndReleaseWorkSessionMapTheirFailures(t *testing.T) {
attemptID := uuid.New()
stub := &workSessionsStub{}
handler := NewAssessmentHandler(&assessmentOperationsStub{}).WithWorkSessions(stub)
hold := func(err error) api.HoldMyAssessmentWorkSessionRes {
t.Helper()
stub.holdErr = err
response, handleErr := handler.HoldMyAssessmentWorkSession(principalForTest(uuid.New()),
api.HoldMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if handleErr != nil {
t.Fatalf("HoldMyAssessmentWorkSession(%v) error = %v", err, handleErr)
}
return response
}
if _, ok := hold(assessmentusecase.ErrAttemptWorkSessionBusy).(*api.HoldMyAssessmentWorkSessionConflict); !ok {
t.Fatal("a held session did not answer 409")
}
if _, ok := hold(assessmentusecase.ErrAttemptWorkSessionState).(*api.HoldMyAssessmentWorkSessionConflict); !ok {
t.Fatal("an attempt with no work session did not answer 409")
}
if _, ok := hold(assessmentusecase.ErrAttemptNotFound).(*api.HoldMyAssessmentWorkSessionNotFound); !ok {
t.Fatal("an unknown attempt did not answer 404")
}
if _, ok := hold(assessmentusecase.ErrAttemptConsentRequired).(*api.HoldMyAssessmentWorkSessionForbidden); !ok {
t.Fatal("a missing consent did not answer 403")
}
if _, ok := hold(assessmentusecase.ErrInvalidWorkSessionClient).(*api.HoldMyAssessmentWorkSessionBadRequest); !ok {
t.Fatal("a malformed page identifier did not answer 400")
}
stub.holdErr = errors.New("private database detail")
if _, err := handler.HoldMyAssessmentWorkSession(principalForTest(uuid.New()),
api.HoldMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient}); err == nil || err.Error() != "private database detail" {
t.Fatalf("internal error mapping = %v", err)
}
stub.holdErr = nil
release, err := handler.ReleaseMyAssessmentWorkSession(principalForTest(uuid.New()),
api.ReleaseMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if err != nil {
t.Fatalf("ReleaseMyAssessmentWorkSession() error = %v", err)
}
if noContent, ok := release.(*api.ReleaseMyAssessmentWorkSessionNoContent); !ok || noContent.CacheControl != api.CacheControlNoStoreNoStore {
t.Fatalf("release response = %T, want no-store 204", release)
}
if stub.releaseCommand.Client != testPageClient || stub.releaseCommand.AttemptID != domain.AssessmentAttemptID(attemptID) {
t.Fatalf("release command = %+v", stub.releaseCommand)
}
stub.releaseErr = assessmentusecase.ErrAttemptNotFound
missing, err := handler.ReleaseMyAssessmentWorkSession(principalForTest(uuid.New()),
api.ReleaseMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if _, ok := missing.(*api.ReleaseMyAssessmentWorkSessionNotFound); !ok || err != nil {
t.Fatalf("release of an unknown attempt = %T, %v, want 404", missing, err)
}
guest, err := handler.HoldMyAssessmentWorkSession(context.Background(), api.HoldMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if _, ok := guest.(*api.HoldMyAssessmentWorkSessionUnauthorized); !ok || err != nil {
t.Fatalf("guest hold = %T, %v, want 401", guest, err)
}
}
func TestStartSessionAndAnswerPassThePageAndRefuseAHeldAttemptWith409(t *testing.T) {
snapshot := assessmentPublicSnapshot()
operations := &assessmentOperationsStub{start: outbound.AssessmentAttemptSessionResult{Response: snapshot}}
handler := NewAssessmentHandler(operations)
ctx := principalForTest(uuid.New())
params := api.StartMyAssessmentAttemptSessionParams{
AttemptID: snapshot.ID.UUID(), IdempotencyKey: "session-key", XAttemptClient: api.NewOptString(testPageClient),
}
if _, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{ExpectedVersion: 7}, params); err != nil {
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
}
if operations.startCommand.Client != testPageClient {
t.Fatalf("StartSession() client = %q, want the page identifier", operations.startCommand.Client)
}
operations.startErr = assessmentusecase.ErrAttemptWorkSessionBusy
response, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{ExpectedVersion: 7}, params)
if err != nil {
t.Fatalf("StartMyAssessmentAttemptSession(held) error = %v", err)
}
conflict, ok := response.(*api.StartMyAssessmentAttemptSessionConflict)
if !ok || api.Problem(*conflict).Code != api.ProblemCodeStateConflict {
t.Fatalf("held attempt response = %T, want 409 state_conflict", response)
}
// Without the header the request is one anonymous page.
params.XAttemptClient = api.OptString{}
operations.startErr = nil
if _, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{ExpectedVersion: 7}, params); err != nil || operations.startCommand.Client != "" {
t.Fatalf("StartSession() without a header: client %q, error %v, want an empty client", operations.startCommand.Client, err)
}
if _, ok := assessmentAnswerFailureOf(t, assessmentusecase.ErrAttemptWorkSessionBusy).(*api.SubmitMyAssessmentAnswerConflict); !ok {
t.Fatal("a held attempt did not answer 409 to an answer")
}
}
func assessmentAnswerFailureOf(t *testing.T, err error) api.SubmitMyAssessmentAnswerRes {
t.Helper()
response, mapped := assessmentAnswerFailure(context.Background(), err)
if mapped != nil {
t.Fatalf("assessmentAnswerFailure(%v) error = %v", err, mapped)
}
return response
}
@@ -43,14 +43,17 @@ func (repository assessmentSignalRepository) SaveOriginMark(ctx context.Context,
if err := mark.Validate(); err != nil {
return fmt.Errorf("%s - mark is invalid: %w", location, err)
}
var network []byte
var network, agent []byte
if !mark.NetworkDigest.IsZero() {
network = mark.NetworkDigest[:]
}
if !mark.AgentDigest.IsZero() {
agent = mark.AgentDigest[:]
}
if err := repository.queries.InsertAssessmentOriginMark(ctx, sqlc.InsertAssessmentOriginMarkParams{
ID: pgUUID(mark.ID), AttemptID: pgUUID(mark.AttemptID.UUID()), Source: string(mark.Source),
ObservedAt: pgTime(mark.ObservedAt), SessionDigest: mark.SessionDigest[:], NetworkDigest: network,
KeyVersion: mark.KeyVersion,
AgentDigest: agent, KeyVersion: mark.KeyVersion,
}); err != nil {
return fmt.Errorf("%s - insert origin mark: %w", location, mapAssessmentError(err))
}
@@ -102,7 +105,8 @@ func (repository assessmentSignalRepository) ReviewInputs(
}
inputs := outbound.AssessmentReviewInputs{
ClientFocusLossMS: totals.FocusLossMs, ClientClipboardCount: totals.ClipboardEvents,
ClientFullscreenExit: totals.FullscreenExits,
ClientFullscreenExit: totals.FullscreenExits, ClientScreenshotKeys: totals.ScreenshotKeys,
ClientDevtoolsOpens: totals.DevtoolsOpens,
}
for _, row := range times {
inputs.Answers = append(inputs.Answers, domain.AssessmentResponseSample{
@@ -121,7 +125,8 @@ func (repository assessmentSignalRepository) ReviewInputs(
func restoreAssessmentOriginMark(row sqlc.AssessmentAttemptOriginMark) (domain.AssessmentOriginMark, error) {
if !row.ID.Valid || !row.AttemptID.Valid || !row.ObservedAt.Valid || len(row.SessionDigest) != len(domain.AssessmentDigest{}) ||
len(row.NetworkDigest) != 0 && len(row.NetworkDigest) != len(domain.AssessmentDigest{}) {
len(row.NetworkDigest) != 0 && len(row.NetworkDigest) != len(domain.AssessmentDigest{}) ||
len(row.AgentDigest) != 0 && len(row.AgentDigest) != len(domain.AssessmentDigest{}) {
return domain.AssessmentOriginMark{}, domain.ErrInvalidAssessmentReview
}
mark := domain.AssessmentOriginMark{
@@ -131,6 +136,7 @@ func restoreAssessmentOriginMark(row sqlc.AssessmentAttemptOriginMark) (domain.A
}
copy(mark.SessionDigest[:], row.SessionDigest)
copy(mark.NetworkDigest[:], row.NetworkDigest)
copy(mark.AgentDigest[:], row.AgentDigest)
if err := mark.Validate(); err != nil {
return domain.AssessmentOriginMark{}, err
}
@@ -219,6 +225,8 @@ func (repository assessmentSignalRepository) SaveReview(ctx context.Context, rev
MatchedIntegerItems: measures.MatchedIntegerItems, MatchedSequenceItems: measures.MatchedSequenceItems,
DuplicateEvidenceBits: measures.DuplicateEvidenceBits, ClientFocusLossMs: measures.ClientFocusLossMS,
ClientClipboardEvents: measures.ClientClipboardEvents, ClientFullscreenExits: measures.ClientFullscreenExits,
ExtraAgents: measures.ExtraAgents, ClientScreenshotKeys: measures.ClientScreenshotKeys,
ClientDevtoolsOpens: measures.ClientDevtoolsOpens,
}); err != nil {
return fmt.Errorf("%s - upsert review: %w", location, mapAssessmentError(err))
}
@@ -262,7 +270,8 @@ func restoreAssessmentAttemptReview(row sqlc.GetAssessmentAttemptReviewRow) (dom
Measures: domain.AssessmentReviewMeasures{
AnsweredItems: row.AnsweredItems, FastAnswers: row.FastAnswers, DeviatingAnswers: row.DeviatingAnswers,
ParallelAlternations: row.ParallelAlternations, ExtraNetworks: row.ExtraNetworks,
MatchedIntegerItems: row.MatchedIntegerItems, MatchedSequenceItems: row.MatchedSequenceItems,
ExtraAgents: row.ExtraAgents, ClientScreenshotKeys: row.ClientScreenshotKeys,
ClientDevtoolsOpens: row.ClientDevtoolsOpens, MatchedIntegerItems: row.MatchedIntegerItems, MatchedSequenceItems: row.MatchedSequenceItems,
DuplicateEvidenceBits: row.DuplicateEvidenceBits,
ClientFocusLossMS: row.ClientFocusLossMs, ClientClipboardEvents: row.ClientClipboardEvents,
ClientFullscreenExits: row.ClientFullscreenExits,
@@ -0,0 +1,74 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.AssessmentWorkLeaseRepository = assessmentWorkLeaseRepository{}
func (unit *UnitOfWork) AssessmentWorkLeases() outbound.AssessmentWorkLeaseRepository {
return assessmentWorkLeaseRepository{queries: unit.queries}
}
type assessmentWorkLeaseRepository struct {
queries *sqlc.Queries
}
func (repository assessmentWorkLeaseRepository) Get(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
) (domain.AssessmentWorkLease, bool, error) {
const location = "assessmentWorkLeaseRepository.Get"
if attemptID.IsZero() {
return domain.AssessmentWorkLease{}, false, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentWorkLease)
}
row, err := repository.queries.GetAssessmentWorkLease(ctx, pgUUID(attemptID.UUID()))
if errors.Is(err, pgx.ErrNoRows) {
return domain.AssessmentWorkLease{}, false, nil
}
if err != nil {
return domain.AssessmentWorkLease{}, false, fmt.Errorf("%s - read lease: %w", location, mapAssessmentError(err))
}
if !row.AttemptID.Valid || !row.AcquiredAt.Valid || !row.RenewedAt.Valid || len(row.HolderDigest) != len(domain.AssessmentDigest{}) {
return domain.AssessmentWorkLease{}, false, fmt.Errorf("%s - stored lease is incomplete: %w", location, domain.ErrInvalidAssessmentWorkLease)
}
lease := domain.AssessmentWorkLease{
AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes), KeyVersion: row.KeyVersion,
AcquiredAt: row.AcquiredAt.Time.UTC(), RenewedAt: row.RenewedAt.Time.UTC(),
}
copy(lease.Holder[:], row.HolderDigest)
if row.ReleasedAt.Valid {
lease.ReleasedAt = row.ReleasedAt.Time.UTC()
}
if err := lease.Validate(); err != nil {
return domain.AssessmentWorkLease{}, false, fmt.Errorf("%s - restore lease: %w", location, err)
}
return lease, true, nil
}
func (repository assessmentWorkLeaseRepository) Save(ctx context.Context, lease domain.AssessmentWorkLease) error {
const location = "assessmentWorkLeaseRepository.Save"
if err := lease.Validate(); err != nil {
return fmt.Errorf("%s - lease is invalid: %w", location, err)
}
released := pgtype.Timestamptz{}
if !lease.ReleasedAt.IsZero() {
released = pgTime(lease.ReleasedAt)
}
if err := repository.queries.UpsertAssessmentWorkLease(ctx, sqlc.UpsertAssessmentWorkLeaseParams{
AttemptID: pgUUID(lease.AttemptID.UUID()), HolderDigest: lease.Holder[:], KeyVersion: lease.KeyVersion,
AcquiredAt: pgTime(lease.AcquiredAt), RenewedAt: pgTime(lease.RenewedAt), ReleasedAt: released,
}); err != nil {
return fmt.Errorf("%s - upsert lease: %w", location, mapAssessmentError(err))
}
return nil
}
@@ -29,6 +29,9 @@ SELECT
review.client_focus_loss_ms,
review.client_clipboard_events,
review.client_fullscreen_exits,
review.extra_agents,
review.client_screenshot_keys,
review.client_devtools_opens,
review.evaluated_at,
review.updated_at
FROM assessment_attempt_reviews AS review
@@ -53,6 +56,9 @@ type GetAssessmentAttemptReviewRow struct {
ClientFocusLossMs int64
ClientClipboardEvents int32
ClientFullscreenExits int32
ExtraAgents int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
EvaluatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
@@ -77,6 +83,9 @@ func (q *Queries) GetAssessmentAttemptReview(ctx context.Context, attemptID pgty
&i.ClientFocusLossMs,
&i.ClientClipboardEvents,
&i.ClientFullscreenExits,
&i.ExtraAgents,
&i.ClientScreenshotKeys,
&i.ClientDevtoolsOpens,
&i.EvaluatedAt,
&i.UpdatedAt,
)
@@ -87,7 +96,9 @@ const getAssessmentClientSignalTotals = `-- name: GetAssessmentClientSignalTotal
SELECT
COALESCE(sum(duration_ms) FILTER (WHERE kind = 'focus_loss'), 0)::bigint AS focus_loss_ms,
(count(*) FILTER (WHERE kind IN ('copy', 'paste', 'cut')))::integer AS clipboard_events,
(count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits
(count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits,
(count(*) FILTER (WHERE kind = 'screenshot_key'))::integer AS screenshot_keys,
(count(*) FILTER (WHERE kind = 'devtools_open'))::integer AS devtools_opens
FROM assessment_signal_events
WHERE attempt_id = $1
`
@@ -96,12 +107,20 @@ type GetAssessmentClientSignalTotalsRow struct {
FocusLossMs int64
ClipboardEvents int32
FullscreenExits int32
ScreenshotKeys int32
DevtoolsOpens int32
}
func (q *Queries) GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error) {
row := q.db.QueryRow(ctx, getAssessmentClientSignalTotals, attemptID)
var i GetAssessmentClientSignalTotalsRow
err := row.Scan(&i.FocusLossMs, &i.ClipboardEvents, &i.FullscreenExits)
err := row.Scan(
&i.FocusLossMs,
&i.ClipboardEvents,
&i.FullscreenExits,
&i.ScreenshotKeys,
&i.DevtoolsOpens,
)
return i, err
}
@@ -120,7 +139,7 @@ func (q *Queries) GetAssessmentReviewSubject(ctx context.Context, attemptID pgty
}
const getLastAssessmentOriginMark = `-- name: GetLastAssessmentOriginMark :one
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest
FROM assessment_attempt_origin_marks
WHERE attempt_id = $1
ORDER BY observed_at DESC, id DESC
@@ -139,6 +158,7 @@ func (q *Queries) GetLastAssessmentOriginMark(ctx context.Context, attemptID pgt
&i.SessionDigest,
&i.NetworkDigest,
&i.KeyVersion,
&i.AgentDigest,
)
return i, err
}
@@ -210,6 +230,7 @@ INSERT INTO assessment_attempt_origin_marks (
observed_at,
session_digest,
network_digest,
agent_digest,
key_version
) VALUES (
$1,
@@ -218,7 +239,8 @@ INSERT INTO assessment_attempt_origin_marks (
$4,
$5,
$6,
$7
$7,
$8
)
`
@@ -229,6 +251,7 @@ type InsertAssessmentOriginMarkParams struct {
ObservedAt pgtype.Timestamptz
SessionDigest []byte
NetworkDigest []byte
AgentDigest []byte
KeyVersion int16
}
@@ -240,6 +263,7 @@ func (q *Queries) InsertAssessmentOriginMark(ctx context.Context, arg InsertAsse
arg.ObservedAt,
arg.SessionDigest,
arg.NetworkDigest,
arg.AgentDigest,
arg.KeyVersion,
)
return err
@@ -423,7 +447,7 @@ func (q *Queries) ListAssessmentDuplicatePairs(ctx context.Context, arg ListAsse
}
const listAssessmentOriginMarks = `-- name: ListAssessmentOriginMarks :many
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest
FROM assessment_attempt_origin_marks
WHERE attempt_id = $1
ORDER BY observed_at, id
@@ -449,6 +473,7 @@ func (q *Queries) ListAssessmentOriginMarks(ctx context.Context, attemptID pgtyp
&i.SessionDigest,
&i.NetworkDigest,
&i.KeyVersion,
&i.AgentDigest,
); err != nil {
return nil, err
}
@@ -492,6 +517,9 @@ INSERT INTO assessment_attempt_reviews (
client_focus_loss_ms,
client_clipboard_events,
client_fullscreen_exits,
extra_agents,
client_screenshot_keys,
client_devtools_opens,
evaluated_at,
updated_at
) VALUES (
@@ -510,6 +538,9 @@ INSERT INTO assessment_attempt_reviews (
$13,
$14,
$15,
$16,
$17,
$18,
clock_timestamp(),
clock_timestamp()
)
@@ -528,6 +559,9 @@ ON CONFLICT (attempt_id) DO UPDATE SET
client_focus_loss_ms = EXCLUDED.client_focus_loss_ms,
client_clipboard_events = EXCLUDED.client_clipboard_events,
client_fullscreen_exits = EXCLUDED.client_fullscreen_exits,
extra_agents = EXCLUDED.extra_agents,
client_screenshot_keys = EXCLUDED.client_screenshot_keys,
client_devtools_opens = EXCLUDED.client_devtools_opens,
updated_at = greatest(
clock_timestamp(), assessment_attempt_reviews.evaluated_at, assessment_attempt_reviews.updated_at
)
@@ -549,6 +583,9 @@ type UpsertAssessmentAttemptReviewParams struct {
ClientFocusLossMs int64
ClientClipboardEvents int32
ClientFullscreenExits int32
ExtraAgents int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
}
// The times come from the database clock, never from a caller, and the update
@@ -572,6 +609,9 @@ func (q *Queries) UpsertAssessmentAttemptReview(ctx context.Context, arg UpsertA
arg.ClientFocusLossMs,
arg.ClientClipboardEvents,
arg.ClientFullscreenExits,
arg.ExtraAgents,
arg.ClientScreenshotKeys,
arg.ClientDevtoolsOpens,
)
return err
}
@@ -0,0 +1,80 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_work_leases.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getAssessmentWorkLease = `-- name: GetAssessmentWorkLease :one
SELECT attempt_id, holder_digest, key_version, acquired_at, renewed_at, released_at
FROM assessment_attempt_work_leases
WHERE attempt_id = $1
`
// The hold of the single active work session of a real attempt. The caller
// holds the row lock of the attempt, so one attempt's lease is changed by one
// transaction at a time.
func (q *Queries) GetAssessmentWorkLease(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptWorkLease, error) {
row := q.db.QueryRow(ctx, getAssessmentWorkLease, attemptID)
var i AssessmentAttemptWorkLease
err := row.Scan(
&i.AttemptID,
&i.HolderDigest,
&i.KeyVersion,
&i.AcquiredAt,
&i.RenewedAt,
&i.ReleasedAt,
)
return i, err
}
const upsertAssessmentWorkLease = `-- name: UpsertAssessmentWorkLease :exec
INSERT INTO assessment_attempt_work_leases (
attempt_id,
holder_digest,
key_version,
acquired_at,
renewed_at,
released_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6
)
ON CONFLICT (attempt_id) DO UPDATE SET
holder_digest = EXCLUDED.holder_digest,
key_version = EXCLUDED.key_version,
acquired_at = EXCLUDED.acquired_at,
renewed_at = EXCLUDED.renewed_at,
released_at = EXCLUDED.released_at
`
type UpsertAssessmentWorkLeaseParams struct {
AttemptID pgtype.UUID
HolderDigest []byte
KeyVersion int16
AcquiredAt pgtype.Timestamptz
RenewedAt pgtype.Timestamptz
ReleasedAt pgtype.Timestamptz
}
func (q *Queries) UpsertAssessmentWorkLease(ctx context.Context, arg UpsertAssessmentWorkLeaseParams) error {
_, err := q.db.Exec(ctx, upsertAssessmentWorkLease,
arg.AttemptID,
arg.HolderDigest,
arg.KeyVersion,
arg.AcquiredAt,
arg.RenewedAt,
arg.ReleasedAt,
)
return err
}
@@ -109,6 +109,7 @@ type AssessmentAttemptOriginMark struct {
SessionDigest []byte
NetworkDigest []byte
KeyVersion int16
AgentDigest []byte
}
type AssessmentAttemptResult struct {
@@ -156,6 +157,18 @@ type AssessmentAttemptReview struct {
ClientFullscreenExits int32
EvaluatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
ExtraAgents int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
}
type AssessmentAttemptWorkLease struct {
AttemptID pgtype.UUID
HolderDigest []byte
KeyVersion int16
AcquiredAt pgtype.Timestamptz
RenewedAt pgtype.Timestamptz
ReleasedAt pgtype.Timestamptz
}
type AssessmentCategoryCatalogBinding struct {
@@ -320,6 +320,10 @@ type Querier interface {
GetAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg GetAssessmentSignalNoticeAcknowledgementParams) (pgtype.Timestamptz, error)
// Read only the receipt associated with the reserved idempotency scope.
GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error)
// The hold of the single active work session of a real attempt. The caller
// holds the row lock of the attempt, so one attempt's lease is changed by one
// transaction at a time.
GetAssessmentWorkLease(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptWorkLease, error)
GetCandidateAssessmentCategory(ctx context.Context, arg GetCandidateAssessmentCategoryParams) (CandidateAssessmentCategory, error)
// Reads one hiding of the candidate with the current name of the
// organization.
@@ -1251,6 +1255,7 @@ type Querier interface {
// either order keep the order check. The first evaluation time and the policy
// version stay; the guard trigger refuses a change of either.
UpsertAssessmentAttemptReview(ctx context.Context, arg UpsertAssessmentAttemptReviewParams) error
UpsertAssessmentWorkLease(ctx context.Context, arg UpsertAssessmentWorkLeaseParams) error
}
var _ Querier = (*Queries)(nil)
+10 -1
View File
@@ -56,6 +56,15 @@ func newAssessmentHandler(
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create signal observer: %w", err)
}
service.WithSignalObserver(observer)
// One open page per real attempt: the work session lease keeps its holder as
// a keyed digest, and the same observer records the origin of every hold.
workSessions, err := assessment.NewWorkSessions(transactor, keyring)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create work sessions: %w", err)
}
workSessions.WithSignalObserver(observer)
service.WithWorkSessions(workSessions)
// The watermark is derived from the identity keyring like the signal
// digests: the same secret, a key of its own, and no new setting.
watermarker, err := assessment.NewWatermarker(keyring)
@@ -63,5 +72,5 @@ func newAssessmentHandler(
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create watermarker: %w", err)
}
return v1.NewAssessmentHandler(service).WithPresenter(watermarker), pool.Close, nil
return v1.NewAssessmentHandler(service).WithPresenter(watermarker).WithWorkSessions(workSessions), pool.Close, nil
}
+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
}
@@ -24,6 +24,8 @@ type AssessmentReviewInputs struct {
ClientFocusLossMS int64
ClientClipboardCount int32
ClientFullscreenExit int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
}
// AssessmentDuplicateQuery selects the pairs of attempts that share answers.
@@ -53,6 +55,17 @@ type AssessmentDuplicatePair struct {
type AssessmentSignalRepositories interface {
AssessmentSignals() AssessmentSignalRepository
AssessmentWorkLeases() AssessmentWorkLeaseRepository
}
// AssessmentWorkLeaseRepository keeps the hold of the single active work
// session of a real attempt. The caller holds the row lock of the attempt, so
// the lease of an attempt is read and written by one transaction at a time.
type AssessmentWorkLeaseRepository interface {
// Get returns the lease; found is false when the attempt never had one.
Get(ctx context.Context, attemptID domain.AssessmentAttemptID) (lease domain.AssessmentWorkLease, found bool, err error)
// Save stores the lease, replacing the previous one of the attempt.
Save(ctx context.Context, lease domain.AssessmentWorkLease) error
}
// AssessmentSignalRepository persists event metadata and the immutable
@@ -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 {