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)