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

@@ -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,
}