feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

@@ -33,6 +33,7 @@ var regexMap = map[string]ogenregex.Regexp{
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
}
var (
@@ -2503,9 +2503,10 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
//
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
// a stale version.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
@@ -4057,21 +4058,22 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped
// handleGetMyCardPreviewRequest handles GetMyCardPreview operation.
//
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
// the candidate does not hide the profile from would read it now, built from the current profile, the
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
// `Cache-Control: no-store`.
//
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
// never shown to an organization. While the profile is closed `card` is null. `card` is
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
// or account or profile identifier, and each property is null when it is not published or has no
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
// The self-assessed grade is not a category and never appears; categories come only from assessment
// results.
// The preview creates no view or access record and is never shown to an organization. While the
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
// generalize or suppress the card when an organization reads it.
//
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
// formats appear only through their separate explicit publication choices, and self-assessment never
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
@@ -5713,6 +5715,234 @@ func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool,
}
}
// handleGetOrganizationCandidateCardRequest handles GetOrganizationCandidateCard operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization and membership come from the current server-side session and path, never from cached
// search data.
//
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
// projection. The server resolves it against the current visible cohort, rechecks active membership,
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
// a handle from another organization, a closed or revoked publication, a profile hidden from this
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
//
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
// available, are a separate operation and require the current explicit C4 grant and contact-access
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
// this read immediately. Republishing does not reopen an earlier contact grant.
//
// Every allowed employer card read is recorded in the access history and consumes the organization's
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
// Retry-After. The response is `Cache-Control: no-store`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
// validation_failed.
//
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
func (s *Server) handleGetOrganizationCandidateCardRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetOrganizationCandidateCard"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationCandidateCardOperation,
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: GetOrganizationCandidateCardOperation,
ID: "GetOrganizationCandidateCard",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationCandidateCardOperation, 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
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
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 := decodeGetOrganizationCandidateCardParams(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 GetOrganizationCandidateCardRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetOrganizationCandidateCardOperation,
OperationSummary: "Read one currently visible anonymous candidate card.",
OperationID: "GetOrganizationCandidateCard",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
{
Name: "candidate_handle",
In: "path",
}: params.CandidateHandle,
},
Raw: r,
}
type (
Request = struct{}
Params = GetOrganizationCandidateCardParams
Response = GetOrganizationCandidateCardRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackGetOrganizationCandidateCardParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetOrganizationCandidateCard(ctx, params)
return response, err
},
)
} else {
response, err = s.h.GetOrganizationCandidateCard(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 := encodeGetOrganizationCandidateCardResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -6800,11 +7030,12 @@ func (s *Server) handleGrantMyConsentRequest(args [1]string, argsEscaped bool, w
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
// see answer the same 404 not_found, with the same body and without a timing or an error code that
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
// organization. The candidate can see an organization that has sent them an invitation, and the
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
// The response names the organization only after that check, with its current name. The identifiers
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
// the record never reveals to an organization that a candidate hides it.
// organization. The candidate may name an organization in their own card-access history or an existing
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
// candidate lookup remains planned. The response names the organization only after that check, with
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
// it.
//
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
@@ -7042,16 +7273,15 @@ func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool,
//
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
// writes nothing. A view of the card by an organization that has no invitation relation with the
// candidate carries `organization` null, so the candidate sees that the card was viewed without
// learning a company that they cannot otherwise see; a contact read always names the organization,
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
// hidden organization cannot read the card.
// writes nothing. A retained access record permits the candidate to see the organization's identifier
// and current name and to hide their profile from it. The nullable organization field is preserved for
// records whose organization cannot be presented. The entries carry no employee identity, search
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
// not erase earlier permitted accesses from the history.
//
// The storage of accesses is planned with the card and contact operations of the organization side
// (anonymous card reads and contact reads under the invitation contract); until then the operation
// answers 501 not_implemented after the session and request checks.
// Successful organization card reads are recorded transactionally with the visibility and quota
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
// accepted workflow status alone never authorizes contact access.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
@@ -9674,6 +9904,263 @@ func (s *Server) handleRaiseOrganizationInvitationSalaryRequest(args [2]string,
}
}
// handleRecordMyAssessmentAttemptSignalsRequest handles RecordMyAssessmentAttemptSignals operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
// every item_instance_id against that attempt, and commits the receipt and any events in one
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
// remains a separate training mode and receives no signal storage or grade effect.
//
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
// Client timestamps must be within five minutes before attempt creation and five minutes after the
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
// with the assessment attempt or account; this release does not promise an independent expiry
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
//
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
// without storing another batch; using that key with another body answers 422.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
func (s *Server) handleRecordMyAssessmentAttemptSignalsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("RecordMyAssessmentAttemptSignals"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/signals"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), RecordMyAssessmentAttemptSignalsOperation,
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: RecordMyAssessmentAttemptSignalsOperation,
ID: "RecordMyAssessmentAttemptSignals",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, RecordMyAssessmentAttemptSignalsOperation, 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, RecordMyAssessmentAttemptSignalsOperation, 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 := decodeRecordMyAssessmentAttemptSignalsParams(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
request, rawBody, close, err := s.decodeRecordMyAssessmentAttemptSignalsRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response RecordMyAssessmentAttemptSignalsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: RecordMyAssessmentAttemptSignalsOperation,
OperationSummary: "Store a bounded batch of client-reported assessment signals.",
OperationID: "RecordMyAssessmentAttemptSignals",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "attempt_id",
In: "path",
}: params.AttemptID,
{
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
},
Raw: r,
}
type (
Request = *AssessmentSignalBatch
Params = RecordMyAssessmentAttemptSignalsParams
Response = RecordMyAssessmentAttemptSignalsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackRecordMyAssessmentAttemptSignalsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.RecordMyAssessmentAttemptSignals(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.RecordMyAssessmentAttemptSignals(ctx, request, 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 := encodeRecordMyAssessmentAttemptSignalsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleRegisterAccountRequest handles RegisterAccount operation.
//
// Public operation without a session. The client reads the current C1 text with GetConsentText and
@@ -93,6 +93,10 @@ type GetMySupportCaseRes interface {
getMySupportCaseRes()
}
type GetOrganizationCandidateCardRes interface {
getOrganizationCandidateCardRes()
}
type GetOrganizationInvitationContactsRes interface {
getOrganizationInvitationContactsRes()
}
@@ -165,6 +169,10 @@ type RaiseOrganizationInvitationSalaryRes interface {
raiseOrganizationInvitationSalaryRes()
}
type RecordMyAssessmentAttemptSignalsRes interface {
recordMyAssessmentAttemptSignalsRes()
}
type RegisterAccountRes interface {
registerAccountRes()
}
File diff suppressed because it is too large. Load diff
@@ -31,6 +31,7 @@ const (
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
GetOrganizationCandidateCardOperation OperationName = "GetOrganizationCandidateCard"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
@@ -49,6 +50,7 @@ const (
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
RegisterAccountOperation OperationName = "RegisterAccount"
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
@@ -1776,6 +1776,147 @@ func decodeGetOrganizationParams(args [1]string, argsEscaped bool, r *http.Reque
return params, nil
}
// GetOrganizationCandidateCardParams is parameters of GetOrganizationCandidateCard operation.
type GetOrganizationCandidateCardParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
// Organization-scoped opaque candidate alias issued by the current visible card projection. The server
// resolves it only for the organization in the path and rechecks current membership, publication
// consent, and hiding on every read. Unknown, hidden, unpublished, and suppressed candidates all
// answer the same 404.
CandidateHandle CandidateHandle
}
func unpackGetOrganizationCandidateCardParams(packed middleware.Parameters) (params GetOrganizationCandidateCardParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "candidate_handle",
In: "path",
}
params.CandidateHandle = packed[key].(CandidateHandle)
}
return params
}
func decodeGetOrganizationCandidateCardParams(args [2]string, argsEscaped bool, r *http.Request) (params GetOrganizationCandidateCardParams, _ error) {
// Decode path: org_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: "org_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.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
// Decode path: candidate_handle.
if err := func() error {
param := args[1]
if argsEscaped {
unescaped, err := url.PathUnescape(args[1])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "candidate_handle",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
var paramsDotCandidateHandleVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotCandidateHandleVal = c
return nil
}(); err != nil {
return err
}
params.CandidateHandle = CandidateHandle(paramsDotCandidateHandleVal)
return nil
}(); err != nil {
return err
}
if err := func() error {
if err := params.CandidateHandle.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "candidate_handle",
In: "path",
Err: err,
}
}
return params, nil
}
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
type GetOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -4263,6 +4404,155 @@ func decodeRaiseOrganizationInvitationSalaryParams(args [2]string, argsEscaped b
return params, nil
}
// RecordMyAssessmentAttemptSignalsParams is parameters of RecordMyAssessmentAttemptSignals operation.
type RecordMyAssessmentAttemptSignalsParams 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
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
// request by method, path, and body.
//
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
// not_found or 409 state_conflict. A replay does not repeat the side effect.
//
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
// precondition_required (nothing changed; read the resource again and retry), 422
// idempotency_key_reused, 429, and every 5xx.
//
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
// before any other key check; a running request with the same fingerprint returns 409
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
// 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
}
func unpackRecordMyAssessmentAttemptSignalsParams(packed middleware.Parameters) (params RecordMyAssessmentAttemptSignalsParams) {
{
key := middleware.ParameterKey{
Name: "attempt_id",
In: "path",
}
params.AttemptID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "Idempotency-Key",
In: "header",
}
params.IdempotencyKey = packed[key].(string)
}
return params
}
func decodeRecordMyAssessmentAttemptSignalsParams(args [1]string, argsEscaped bool, r *http.Request) (params RecordMyAssessmentAttemptSignalsParams, _ 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: Idempotency-Key.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "Idempotency-Key",
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.IdempotencyKey = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 255,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.IdempotencyKey)); 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: "Idempotency-Key",
In: "header",
Err: err,
}
}
return params, nil
}
// RegisterAccountParams is parameters of RegisterAccount operation.
type RegisterAccountParams struct {
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
@@ -1041,6 +1041,85 @@ func (s *Server) decodeRaiseOrganizationInvitationSalaryRequest(r *http.Request)
}
}
func (s *Server) decodeRecordMyAssessmentAttemptSignalsRequest(r *http.Request) (
req *AssessmentSignalBatch,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request AssessmentSignalBatch
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeRegisterAccountRequest(r *http.Request) (
req *RegistrationRequest,
rawBody []byte,
@@ -1291,7 +1291,7 @@ func encodeFinalizeMyAssessmentAttemptResponse(response FinalizeMyAssessmentAtte
return nil
case *FinalizeMyAssessmentAttemptConflict:
case *AssessmentFinalizeConflictProblem:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(409)
@@ -2215,6 +2215,121 @@ func encodeGetOrganizationResponse(response GetOrganizationRes, w http.ResponseW
}
}
func encodeGetOrganizationCandidateCardResponse(response GetOrganizationCandidateCardRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AnonymousCardContentHeaders:
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 *GetOrganizationCandidateCardBadRequest:
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 *GetOrganizationCandidateCardUnauthorized:
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 *GetOrganizationCandidateCardForbidden:
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 *GetOrganizationCandidateCardNotFound:
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 *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.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 encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -3651,6 +3766,157 @@ func encodeRaiseOrganizationInvitationSalaryResponse(response RaiseOrganizationI
}
}
func encodeRecordMyAssessmentAttemptSignalsResponse(response RecordMyAssessmentAttemptSignalsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentSignalReceiptHeaders:
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 *RecordMyAssessmentAttemptSignalsBadRequest:
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 *RecordMyAssessmentAttemptSignalsUnauthorized:
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 *RecordMyAssessmentAttemptSignalsForbidden:
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 *RecordMyAssessmentAttemptSignalsNotFound:
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 *RecordMyAssessmentAttemptSignalsConflict:
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
case *RecordMyAssessmentAttemptSignalsRequestEntityTooLarge:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(413)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *RecordMyAssessmentAttemptSignalsUnprocessableEntity:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(422)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.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 encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *IdentityRequestAccepted:
@@ -11,40 +11,43 @@ import (
)
var (
rn66AllowedHeaders = map[string]string{
rn69AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn7AllowedHeaders = map[string]string{
"POST": "Content-Type,Origin",
}
rn62AllowedHeaders = map[string]string{
rn65AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn59AllowedHeaders = map[string]string{
rn61AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn25AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn64AllowedHeaders = map[string]string{
rn67AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn9AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn75AllowedHeaders = map[string]string{
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn20AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn74AllowedHeaders = map[string]string{
rn78AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn68AllowedHeaders = map[string]string{
rn64AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn71AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn48AllowedHeaders = map[string]string{
rn50AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "Content-Type,X-Csrf-Token",
}
@@ -57,17 +60,17 @@ var (
rn17AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn76AllowedHeaders = map[string]string{
rn80AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn51AllowedHeaders = map[string]string{
rn53AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "X-Csrf-Token",
}
rn72AllowedHeaders = map[string]string{
rn75AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn73AllowedHeaders = map[string]string{
rn76AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn36AllowedHeaders = map[string]string{
@@ -88,22 +91,22 @@ var (
rn14AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn41AllowedHeaders = map[string]string{
rn43AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn61AllowedHeaders = map[string]string{
rn63AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn70AllowedHeaders = map[string]string{
rn73AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn77AllowedHeaders = map[string]string{
rn81AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn16AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn44AllowedHeaders = map[string]string{
rn46AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
)
@@ -260,7 +263,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn66AllowedHeaders,
allowedHeaders: rn69AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -337,7 +340,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn62AllowedHeaders,
allowedHeaders: rn65AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -361,7 +364,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn59AllowedHeaders,
allowedHeaders: rn61AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -441,7 +444,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn64AllowedHeaders,
allowedHeaders: rn67AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -551,7 +554,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn75AllowedHeaders,
allowedHeaders: rn79AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -614,31 +617,72 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
case 's': // Prefix: "sessions"
case 's': // Prefix: "s"
if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" {
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleStartMyAssessmentAttemptSessionRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn74AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
break
}
switch elem[0] {
case 'e': // Prefix: "essions"
if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleStartMyAssessmentAttemptSessionRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn78AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
case 'i': // Prefix: "ignals"
if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleRecordMyAssessmentAttemptSignalsRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn64AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
return
}
}
@@ -787,7 +831,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE",
allowedHeaders: rn68AllowedHeaders,
allowedHeaders: rn71AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -821,7 +865,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,PUT",
allowedHeaders: rn48AllowedHeaders,
allowedHeaders: rn50AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1004,7 +1048,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn76AllowedHeaders,
allowedHeaders: rn80AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1184,7 +1228,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,PUT",
allowedHeaders: rn51AllowedHeaders,
allowedHeaders: rn53AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1275,7 +1319,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn72AllowedHeaders,
allowedHeaders: rn75AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1302,7 +1346,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn73AllowedHeaders,
allowedHeaders: rn76AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1512,6 +1556,43 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
break
}
switch elem[0] {
case 'c': // Prefix: "candidate-cards/"
if l := len("candidate-cards/"); len(elem) >= l && elem[0:l] == "candidate-cards/" {
elem = elem[l:]
} else {
break
}
// Param: "candidate_handle"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetOrganizationCandidateCardRequest([2]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 'i': // Prefix: "invitations"
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
@@ -1574,7 +1655,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn41AllowedHeaders,
allowedHeaders: rn43AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -1654,7 +1735,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn61AllowedHeaders,
allowedHeaders: rn63AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1682,7 +1763,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn70AllowedHeaders,
allowedHeaders: rn73AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1712,7 +1793,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn77AllowedHeaders,
allowedHeaders: rn81AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1790,7 +1871,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn44AllowedHeaders,
allowedHeaders: rn46AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -2384,29 +2465,68 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
}
case 's': // Prefix: "sessions"
case 's': // Prefix: "s"
if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" {
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = StartMyAssessmentAttemptSessionOperation
r.summary = "Start or resume a work session for the current candidate's attempt."
r.operationID = "StartMyAssessmentAttemptSession"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions"
r.args = args
r.count = 1
return r, true
default:
return
break
}
switch elem[0] {
case 'e': // Prefix: "essions"
if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = StartMyAssessmentAttemptSessionOperation
r.summary = "Start or resume a work session for the current candidate's attempt."
r.operationID = "StartMyAssessmentAttemptSession"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions"
r.args = args
r.count = 1
return r, true
default:
return
}
}
case 'i': // Prefix: "ignals"
if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = RecordMyAssessmentAttemptSignalsOperation
r.summary = "Store a bounded batch of client-reported assessment signals."
r.operationID = "RecordMyAssessmentAttemptSignals"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/signals"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
@@ -3294,6 +3414,40 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
break
}
switch elem[0] {
case 'c': // Prefix: "candidate-cards/"
if l := len("candidate-cards/"); len(elem) >= l && elem[0:l] == "candidate-cards/" {
elem = elem[l:]
} else {
break
}
// Param: "candidate_handle"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetOrganizationCandidateCardOperation
r.summary = "Read one currently visible anonymous candidate card."
r.operationID = "GetOrganizationCandidateCard"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}"
r.args = args
r.count = 2
return r, true
default:
return
}
}
case 'i': // Prefix: "invitations"
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
File diff suppressed because it is too large. Load diff
@@ -78,6 +78,7 @@ var operationRolesSessionCookie = map[string][]string{
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
GetOrganizationCandidateCardOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
@@ -94,6 +95,7 @@ var operationRolesSessionCookie = map[string][]string{
ListOrganizationNeedsOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
@@ -148,6 +150,7 @@ var operationRolesSessionCsrf = map[string][]string{
HideOrganizationOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
@@ -479,9 +479,10 @@ type Handler interface {
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
//
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
// a stale version.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
@@ -600,21 +601,22 @@ type Handler interface {
GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error)
// GetMyCardPreview implements GetMyCardPreview operation.
//
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
// the candidate does not hide the profile from would read it now, built from the current profile, the
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
// `Cache-Control: no-store`.
//
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
// never shown to an organization. While the profile is closed `card` is null. `card` is
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
// or account or profile identifier, and each property is null when it is not published or has no
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
// The self-assessed grade is not a category and never appears; categories come only from assessment
// results.
// The preview creates no view or access record and is never shown to an organization. While the
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
// generalize or suppress the card when an organization reads it.
//
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
// formats appear only through their separate explicit publication choices, and self-assessment never
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
@@ -764,6 +766,36 @@ type Handler interface {
//
// GET /api/v1/organizations/{org_id}
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
// GetOrganizationCandidateCard implements GetOrganizationCandidateCard operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization and membership come from the current server-side session and path, never from cached
// search data.
//
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
// projection. The server resolves it against the current visible cohort, rechecks active membership,
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
// a handle from another organization, a closed or revoked publication, a profile hidden from this
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
//
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
// available, are a separate operation and require the current explicit C4 grant and contact-access
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
// this read immediately. Republishing does not reopen an earlier contact grant.
//
// Every allowed employer card read is recorded in the access history and consumes the organization's
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
// Retry-After. The response is `Cache-Control: no-store`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
// validation_failed.
//
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
GetOrganizationCandidateCard(ctx context.Context, params GetOrganizationCandidateCardParams) (GetOrganizationCandidateCardRes, error)
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -901,11 +933,12 @@ type Handler interface {
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
// see answer the same 404 not_found, with the same body and without a timing or an error code that
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
// organization. The candidate can see an organization that has sent them an invitation, and the
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
// The response names the organization only after that check, with its current name. The identifiers
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
// the record never reveals to an organization that a candidate hides it.
// organization. The candidate may name an organization in their own card-access history or an existing
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
// candidate lookup remains planned. The response names the organization only after that check, with
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
// it.
//
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
@@ -931,16 +964,15 @@ type Handler interface {
//
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
// writes nothing. A view of the card by an organization that has no invitation relation with the
// candidate carries `organization` null, so the candidate sees that the card was viewed without
// learning a company that they cannot otherwise see; a contact read always names the organization,
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
// hidden organization cannot read the card.
// writes nothing. A retained access record permits the candidate to see the organization's identifier
// and current name and to hide their profile from it. The nullable organization field is preserved for
// records whose organization cannot be presented. The entries carry no employee identity, search
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
// not erase earlier permitted accesses from the history.
//
// The storage of accesses is planned with the card and contact operations of the organization side
// (anonymous card reads and contact reads under the invitation contract); until then the operation
// answers 501 not_implemented after the session and request checks.
// Successful organization card reads are recorded transactionally with the visibility and quota
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
// accepted workflow status alone never authorizes contact access.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
@@ -1189,6 +1221,32 @@ type Handler interface {
//
// POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise
RaiseOrganizationInvitationSalary(ctx context.Context, req *InvitationSalaryRaise, params RaiseOrganizationInvitationSalaryParams) (RaiseOrganizationInvitationSalaryRes, error)
// RecordMyAssessmentAttemptSignals implements RecordMyAssessmentAttemptSignals operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
// every item_instance_id against that attempt, and commits the receipt and any events in one
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
// remains a separate training mode and receives no signal storage or grade effect.
//
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
// Client timestamps must be within five minutes before attempt creation and five minutes after the
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
// with the assessment attempt or account; this release does not promise an independent expiry
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
//
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
// without storing another batch; using that key with another body answers 422.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
RecordMyAssessmentAttemptSignals(ctx context.Context, req *AssessmentSignalBatch, params RecordMyAssessmentAttemptSignalsParams) (RecordMyAssessmentAttemptSignalsRes, error)
// RegisterAccount implements RegisterAccount operation.
//
// Public operation without a session. The client reads the current C1 text with GetConsentText and
@@ -511,9 +511,10 @@ func (UnimplementedHandler) DeclineMyInvitation(ctx context.Context, req *Invita
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
//
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
// a stale version.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
@@ -656,21 +657,22 @@ func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params Ge
// GetMyCardPreview implements GetMyCardPreview operation.
//
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
// the candidate does not hide the profile from would read it now, built from the current profile, the
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
// `Cache-Control: no-store`.
//
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
// never shown to an organization. While the profile is closed `card` is null. `card` is
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
// or account or profile identifier, and each property is null when it is not published or has no
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
// The self-assessed grade is not a category and never appears; categories come only from assessment
// results.
// The preview creates no view or access record and is never shown to an organization. While the
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
// generalize or suppress the card when an organization reads it.
//
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
// formats appear only through their separate explicit publication choices, and self-assessment never
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
@@ -844,6 +846,39 @@ func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrgan
return r, ht.ErrNotImplemented
}
// GetOrganizationCandidateCard implements GetOrganizationCandidateCard operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization and membership come from the current server-side session and path, never from cached
// search data.
//
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
// projection. The server resolves it against the current visible cohort, rechecks active membership,
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
// a handle from another organization, a closed or revoked publication, a profile hidden from this
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
//
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
// available, are a separate operation and require the current explicit C4 grant and contact-access
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
// this read immediately. Republishing does not reopen an earlier contact grant.
//
// Every allowed employer card read is recorded in the access history and consumes the organization's
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
// Retry-After. The response is `Cache-Control: no-store`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
// validation_failed.
//
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
func (UnimplementedHandler) GetOrganizationCandidateCard(ctx context.Context, params GetOrganizationCandidateCardParams) (r GetOrganizationCandidateCardRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -996,11 +1031,12 @@ func (UnimplementedHandler) GrantMyConsent(ctx context.Context, req *ConsentSett
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
// see answer the same 404 not_found, with the same body and without a timing or an error code that
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
// organization. The candidate can see an organization that has sent them an invitation, and the
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
// The response names the organization only after that check, with its current name. The identifiers
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
// the record never reveals to an organization that a candidate hides it.
// organization. The candidate may name an organization in their own card-access history or an existing
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
// candidate lookup remains planned. The response names the organization only after that check, with
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
// it.
//
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
@@ -1029,16 +1065,15 @@ func (UnimplementedHandler) HideOrganization(ctx context.Context, params HideOrg
//
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
// writes nothing. A view of the card by an organization that has no invitation relation with the
// candidate carries `organization` null, so the candidate sees that the card was viewed without
// learning a company that they cannot otherwise see; a contact read always names the organization,
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
// hidden organization cannot read the card.
// writes nothing. A retained access record permits the candidate to see the organization's identifier
// and current name and to hide their profile from it. The nullable organization field is preserved for
// records whose organization cannot be presented. The entries carry no employee identity, search
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
// not erase earlier permitted accesses from the history.
//
// The storage of accesses is planned with the card and contact operations of the organization side
// (anonymous card reads and contact reads under the invitation contract); until then the operation
// answers 501 not_implemented after the session and request checks.
// Successful organization card reads are recorded transactionally with the visibility and quota
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
// accepted workflow status alone never authorizes contact access.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
@@ -1323,6 +1358,35 @@ func (UnimplementedHandler) RaiseOrganizationInvitationSalary(ctx context.Contex
return r, ht.ErrNotImplemented
}
// RecordMyAssessmentAttemptSignals implements RecordMyAssessmentAttemptSignals operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
// every item_instance_id against that attempt, and commits the receipt and any events in one
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
// remains a separate training mode and receives no signal storage or grade effect.
//
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
// Client timestamps must be within five minutes before attempt creation and five minutes after the
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
// with the assessment attempt or account; this release does not promise an independent expiry
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
//
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
// without storing another batch; using that key with another body answers 422.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
func (UnimplementedHandler) RecordMyAssessmentAttemptSignals(ctx context.Context, req *AssessmentSignalBatch, params RecordMyAssessmentAttemptSignalsParams) (r RecordMyAssessmentAttemptSignalsRes, _ error) {
return r, ht.ErrNotImplemented
}
// RegisterAccount implements RegisterAccount operation.
//
// Public operation without a session. The client reads the current C1 text with GetConsentText and
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,55 @@
package apitypes
import (
"bytes"
"encoding/json"
"errors"
"io"
)
// AssessmentNumber preserves the JSON number token for exact answer comparison.
type AssessmentNumber string
func (number *AssessmentNumber) UnmarshalJSON(encoded []byte) error {
if number == nil {
return errors.New("assessment number target is nil")
}
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return errors.New("assessment answer number is invalid")
}
parsed, ok := value.(json.Number)
if !ok {
return errors.New("assessment answer must be a JSON number")
}
var extra any
if !errors.Is(decoder.Decode(&extra), io.EOF) {
return errors.New("assessment answer number has trailing data")
}
*number = AssessmentNumber(parsed.String())
return nil
}
func (number AssessmentNumber) MarshalJSON() ([]byte, error) {
encoded := []byte(number)
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return nil, errors.New("assessment answer number is invalid")
}
if _, ok := value.(json.Number); !ok {
return nil, errors.New("assessment answer must be a JSON number")
}
var extra any
if !errors.Is(decoder.Decode(&extra), io.EOF) {
return nil, errors.New("assessment answer number has trailing data")
}
return encoded, nil
}
func (number AssessmentNumber) String() string {
return string(number)
}
@@ -0,0 +1,22 @@
package apitypes
import (
"encoding/json"
"testing"
)
func TestAssessmentNumberPreservesOnlyJSONNumberTokens(t *testing.T) {
var number AssessmentNumber
if err := json.Unmarshal([]byte(`1.0000000000000001`), &number); err != nil {
t.Fatalf("UnmarshalJSON() error = %v", err)
}
encoded, err := json.Marshal(number)
if err != nil || string(encoded) != `1.0000000000000001` {
t.Fatalf("MarshalJSON() = %s, error %v; want original exact token", encoded, err)
}
for _, input := range []string{`"1"`, `null`, `true`, `1 2`} {
if err := json.Unmarshal([]byte(input), &number); err == nil {
t.Errorf("UnmarshalJSON(%s) unexpectedly succeeded", input)
}
}
}
@@ -0,0 +1,16 @@
package httpadapter
import (
"net/http"
)
const maxAssessmentSignalBodyBytes int64 = 32 << 10
// limitAssessmentSignalBody is called only after the generated router has
// matched the signal operation. It leaves decoding and authentication order
// to the generated server while bounding both fixed-length and chunked bodies.
func limitAssessmentSignalBody(w http.ResponseWriter, request *http.Request) {
if request.Body != nil {
request.Body = http.MaxBytesReader(w, request.Body, maxAssessmentSignalBodyBytes)
}
}
@@ -0,0 +1,52 @@
package httpadapter
import (
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestLimitAssessmentSignalBodyBoundsFixedAndChunkedBodies(t *testing.T) {
testCases := []struct {
name string
contentLength int64
}{
{name: "content length", contentLength: maxAssessmentSignalBodyBytes + 1},
{name: "chunked body", contentLength: -1},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
request := httptest.NewRequest("POST", "/", strings.NewReader(strings.Repeat("x", int(maxAssessmentSignalBodyBytes+1))))
request.ContentLength = testCase.contentLength
response := httptest.NewRecorder()
limitAssessmentSignalBody(response, request)
body, err := io.ReadAll(request.Body)
var limitError *http.MaxBytesError
if !errors.As(err, &limitError) {
t.Fatalf("ReadAll() error = %v, want MaxBytesError", err)
}
if int64(len(body)) != maxAssessmentSignalBodyBytes {
t.Fatalf("ReadAll() returned %d bytes, want %d", len(body), maxAssessmentSignalBodyBytes)
}
})
}
}
func TestLimitAssessmentSignalBodyAllowsExactLimit(t *testing.T) {
request := httptest.NewRequest("POST", "/", strings.NewReader(strings.Repeat("x", int(maxAssessmentSignalBodyBytes))))
response := httptest.NewRecorder()
limitAssessmentSignalBody(response, request)
body, err := io.ReadAll(request.Body)
if err != nil {
t.Fatalf("ReadAll() error = %v", err)
}
if int64(len(body)) != maxAssessmentSignalBodyBytes {
t.Fatalf("ReadAll() returned %d bytes, want %d", len(body), maxAssessmentSignalBodyBytes)
}
}
@@ -31,7 +31,12 @@ var (
publicationSchemas = []string{"Publication", "PublicationUpdate", "PublicationVersion", "PublicationState", "PublicationClosedReason", "CardField", "CardFieldSet"}
searchStatusSchemas = []string{"SearchStatus", "SearchStatusUpdate", "SearchStatusVersion", "SearchStatusValue"}
hiddenSchemas = []string{"HiddenOrganization", "HiddenOrganizationList", "PrivacyOrganization"}
privacyOnlySchemas = []string{"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList"}
privacyOnlySchemas = []string{
"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
"CardSelfAssessmentConfirmationStatus",
"CandidateExperienceBand", "CandidateWorkFormat", "CandidateSalaryCompatibility",
"PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList",
}
// sharedLeafSchemas are the reusable leaves that the privacy family may
// refer to; none of them identifies a person or carries a contact.
sharedLeafSchemas = []string{"Timestamp", "PageInfo", "SpecializationCode", "GradeCode", "StackTag"}
@@ -207,13 +212,16 @@ func TestPublicationAndSearchStatusAreNotConsents(t *testing.T) {
// The published field set cannot name a name, a contact, or the salary.
fields := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CardField"}))
want := []string{"categories", "stack", "experience", "soft_skills", "location", "relocation"}
want := []string{
"categories", "stack", "experience", "soft_skills", "location", "relocation",
"self_assessment", "work_formats", "salary_compatibility",
}
slices.Sort(fields)
slices.Sort(want)
if !slices.Equal(fields, want) {
t.Errorf("CardField = %v, want %v", fields, want)
}
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != uint64(len(want)) {
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != 9 {
t.Error("CardFieldSet must hold distinct items and at most one per field")
}
status := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/SearchStatusValue"}))
@@ -233,7 +241,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
if card == nil {
t.Fatal("the contract has no AnonymousCardContent")
}
if got, want := propertyNames(card), []string{"categories", "experience_months", "location", "relocation", "soft_skills", "stack"}; !slices.Equal(got, want) {
if got, want := propertyNames(card), []string{
"categories", "experience_band", "pseudonym", "salary_compatibility", "self_assessment", "stack", "work_formats",
}; !slices.Equal(got, want) {
t.Errorf("AnonymousCardContent properties = %v, want %v", got, want)
}
if card.AdditionalProperties.Bool == nil || *card.AdditionalProperties.Bool {
@@ -241,7 +251,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
}
// Each property is a card field and nothing else; a null is a hidden or
// missing value, never a flag that tells which.
for _, forbidden := range []string{"email", "phone", "telegram", "contact", "name", "salary", "user", "account", "profile", "employer", "id", "url", "link", "github", "resume"} {
for _, forbidden := range []string{
"email", "phone", "telegram", "contact", "name", "salary_minimum", "salary_amount", "user", "account", "profile", "employer", "id", "url", "link", "github", "resume",
} {
for _, name := range propertyNames(card) {
if strings.Contains(name, forbidden) {
t.Errorf("AnonymousCardContent has the property %q, which looks like %q", name, forbidden)
@@ -250,7 +262,11 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
}
// What the card and the preview reach is a small closed list of leaves.
allowed := []string{"AnonymousCardContent", "CardCategory", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode", "GradeCode", "StackTag", "Timestamp", "CardPreview"}
allowed := []string{
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment", "CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
"CandidateSalaryCompatibility", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode",
"GradeCode", "StackTag", "Timestamp", "CardPreview",
}
for _, name := range []string{"AnonymousCardContent", "CardPreview"} {
for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) {
if !slices.Contains(allowed, reached) {
@@ -296,6 +312,14 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
continue
}
for reached := range reachableSchemas(index, mustJSONValue(t, item)) {
if path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}" &&
slices.Contains([]string{
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
"CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
"CandidateSalaryCompatibility",
}, reached) {
continue
}
if isPrivacySchema(reached) {
t.Errorf("%s reaches the candidate-private schema %s", path, reached)
}
@@ -38,7 +38,7 @@ func (authorizer companyAuthorizerFunc) AuthorizeCompany(ctx context.Context, ac
return authorizer(ctx, actorID, organizationID)
}
func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testing.T) {
func TestCompanyContextMiddlewareFailsClosedAndExcludesOtherScopes(t *testing.T) {
organizationID := uuid.New()
request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, organizationID)
if _, err := NewCompanyContextMiddleware(nil)(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
@@ -49,6 +49,9 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testin
}
for _, operation := range []apiadapter.OperationName{
// Card reads lock any active membership inside their read transaction;
// the owner-only capability does not apply to that operation.
apiadapter.GetOrganizationCandidateCardOperation,
apiadapter.HideOrganizationOperation,
apiadapter.UnhideOrganizationOperation,
apiadapter.RevokeMyOrganizationContactConsentOperation,
@@ -62,7 +65,7 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testin
return ogenmiddleware.Response{}, nil
})
if err != nil || !called {
t.Fatalf("candidate/self-scoped operation: called=%v err=%v; want pass-through", called, err)
t.Fatalf("operation outside owner scope: called=%v err=%v; want pass-through", called, err)
}
})
}
@@ -131,6 +134,7 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
}
seen := make(map[string]string, len(ownerCompanyOperations))
seenExceptions := make(map[string]bool, len(candidateExceptions))
seenCardRead := false
for path, methods := range document.Paths {
for _, operation := range methods {
if operation.OperationID == "" {
@@ -150,6 +154,13 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
if !strings.Contains(path, "{org_id}") {
continue
}
// The card usecase checks and locks active membership together with
// current visibility and quota. It does not require the owner role.
if operation.OperationID == "GetOrganizationCandidateCard" &&
path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}" {
seenCardRead = true
continue
}
expectedPath, candidateOperation := candidateExceptions[operation.OperationID]
if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") {
seenExceptions[operation.OperationID] = true
@@ -168,6 +179,9 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
t.Errorf("candidate exception %s is absent or moved without updating the explicit exception", operation)
}
}
if !seenCardRead {
t.Error("transaction-authorized candidate card read is absent or moved")
}
}
type companyContextAuthenticator struct {
@@ -79,7 +79,7 @@ func NewRouter(
// server aborts the response; the kit Recoverer would swallow that panic.
router.Group(func(public chi.Router) {
public.Use(problems.Recover)
public.Handle(apiWildcard, clearUnauthorizedLogoutCookie(apiServer))
public.Handle(apiWildcard, clearUnauthorizedLogoutCookie(limitOperationBody(apiServer)))
// Unknown /api paths outside the versioned prefix are also problems,
// so every error under /api has the contract's format.
public.Handle(apiRoot, http.HandlerFunc(problems.NotFound))
@@ -88,6 +88,16 @@ func NewRouter(
return router, nil
}
func limitOperationBody(server *apiadapter.Server) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
operation, found := server.FindPath(r.Method, r.URL)
if found && operation.PathPattern() == publicPrefix+"/me/assessment-attempts/{attempt_id}/signals" {
limitAssessmentSignalBody(w, r)
}
server.ServeHTTP(w, r)
})
}
func clearUnauthorizedLogoutCookie(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clearCookie := r.Method == http.MethodDelete && r.URL.Path == publicPrefix+"/identity/sessions/current"
@@ -1413,7 +1413,7 @@ const (
`"offer_type":"full_time","tasks":["Развивать сервис выплат"],"team":"Команда платежей из шести человек",` +
`"tech_stack":["Go","PostgreSQL"],"work_formats":["remote"],"location":null,` +
`"communication_method":` + invitationCommunication + `,"salary":` + invitationSalary + `,"package":` + invitationPackage + `}`
validInvitationCreate = `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt",` +
validInvitationCreate = `{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",` +
`"need":{"need_id":"01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12","requirements_version":3},` +
`"response_period_days":7,"terms":` + validInvitationTerms + `}`
validInvitationAccept = `{"expected_version":5,"terms_version":3,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true,"fields":["email"]}}`
@@ -1422,7 +1422,7 @@ const (
// invitationCreateWithTerms returns a CreateOrganizationInvitation body whose
// terms are the valid terms with one replacement applied.
func invitationCreateWithTerms(old, replacement string) string {
return `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","terms":` + strings.Replace(validInvitationTerms, old, replacement, 1) + `}`
return `{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","terms":` + strings.Replace(validInvitationTerms, old, replacement, 1) + `}`
}
// The schema alone must accept a complete invitation and reject what the
@@ -1476,7 +1476,7 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
},
{
name: "create a direct draft with the default response period",
request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","need":null,"terms":` + validInvitationTerms + `}`),
request: create(`{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","need":null,"terms":` + validInvitationTerms + `}`),
},
{
// The cross-field salary rules and the place of work for an
@@ -1505,12 +1505,12 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
},
{
name: "create for a candidate named by an email address",
request: create(strings.Replace(validInvitationCreate, `"cand_7Qm2xVb9Lr4Kp0Zt"`, `"candidate@example.com"`, 1)),
request: create(strings.Replace(validInvitationCreate, `"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"`, `"candidate@example.com"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/candidate_handle", code: "invalid",
},
{
name: "create without terms",
request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt"}`),
request: create(`{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}`),
location: api.ProblemFieldLocationBody, pointer: "/terms", code: "required",
},
{
@@ -1659,7 +1659,7 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
},
{
name: "update that changes the candidate",
request: update(`{"expected_version":1,"candidate_handle":"cand_Hx3Tn8Wq1Ys6Fd2Vb"}`),
request: update(`{"expected_version":1,"candidate_handle":"cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
@@ -17,14 +17,19 @@ import (
type Handler struct {
api.UnimplementedHandler
health *HealthHandler
identity *IdentityHandler
consent *ConsentHandler
profile *ProfileHandler
questionnaire *QuestionnaireHandler
catalog *CatalogHandler
organization *OrganizationHandler
problems *problem.Responder
health *HealthHandler
identity *IdentityHandler
consent *ConsentHandler
profile *ProfileHandler
questionnaire *QuestionnaireHandler
catalog *CatalogHandler
organization *OrganizationHandler
need *NeedHandler
support *SupportHandler
assessment *AssessmentHandler
assessmentSignals *AssessmentSignalHandler
privacy *PrivacyHandler
problems *problem.Responder
}
var _ api.Handler = (*Handler)(nil)
@@ -62,6 +67,31 @@ func WithOrganization(organization *OrganizationHandler) HandlerOption {
return func(handler *Handler) { handler.organization = organization }
}
// WithNeed serves organization-scoped hiring needs.
func WithNeed(need *NeedHandler) HandlerOption {
return func(handler *Handler) { handler.need = need }
}
// WithSupport serves account-owned support cases.
func WithSupport(support *SupportHandler) HandlerOption {
return func(handler *Handler) { handler.support = support }
}
// WithAssessment serves candidate-owned assessment attempts and sessions.
func WithAssessment(assessment *AssessmentHandler) HandlerOption {
return func(handler *Handler) { handler.assessment = assessment }
}
// WithAssessmentSignals serves bounded candidate assessment event receipts.
func WithAssessmentSignals(signals *AssessmentSignalHandler) HandlerOption {
return func(handler *Handler) { handler.assessmentSignals = signals }
}
// WithPrivacy serves current publication and candidate-card visibility operations.
func WithPrivacy(privacy *PrivacyHandler) HandlerOption {
return func(handler *Handler) { handler.privacy = privacy }
}
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
handler := &Handler{health: health, problems: problems}
for _, option := range options {
@@ -0,0 +1,799 @@
package v1
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
// AssessmentOperations serves candidate-owned attempt reads and commands.
type AssessmentOperations interface {
CreateAttempt(ctx context.Context, command assessmentusecase.CreateAttemptCommand) (outbound.AssessmentAttemptCreateResult, error)
GetMyAssessmentAvailability(ctx context.Context, userID uuid.UUID) (assessmentusecase.AssessmentAvailability, error)
GetMyAttempt(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptPublicSnapshot, error)
StartSession(ctx context.Context, command assessmentusecase.StartAttemptSessionCommand) (outbound.AssessmentAttemptSessionResult, error)
}
// AssessmentHandler serves the candidate's frozen assessment attempts.
type AssessmentHandler struct {
operations AssessmentOperations
}
func NewAssessmentHandler(operations AssessmentOperations) *AssessmentHandler {
if operations == nil {
panic("v1.NewAssessmentHandler - assessment operations must not be nil")
}
return &AssessmentHandler{operations: operations}
}
func (handler *Handler) CreateMyAssessmentAttempt(
ctx context.Context,
request api.AssessmentAttemptCreate,
params api.CreateMyAssessmentAttemptParams,
) (api.CreateMyAssessmentAttemptRes, error) {
if handler.assessment == nil {
return handler.UnimplementedHandler.CreateMyAssessmentAttempt(ctx, request, params)
}
return handler.assessment.CreateMyAssessmentAttempt(ctx, request, params)
}
func (handler *Handler) GetMyAssessmentAvailability(
ctx context.Context,
) (api.GetMyAssessmentAvailabilityRes, error) {
if handler.assessment == nil {
return handler.UnimplementedHandler.GetMyAssessmentAvailability(ctx)
}
return handler.assessment.GetMyAssessmentAvailability(ctx)
}
func (handler *Handler) GetMyAssessmentAttempt(
ctx context.Context,
params api.GetMyAssessmentAttemptParams,
) (api.GetMyAssessmentAttemptRes, error) {
if handler.assessment == nil {
return handler.UnimplementedHandler.GetMyAssessmentAttempt(ctx, params)
}
return handler.assessment.GetMyAssessmentAttempt(ctx, params)
}
func (handler *Handler) StartMyAssessmentAttemptSession(
ctx context.Context,
request *api.AssessmentAttemptSessionStart,
params api.StartMyAssessmentAttemptSessionParams,
) (api.StartMyAssessmentAttemptSessionRes, error) {
if handler.assessment == nil {
return handler.UnimplementedHandler.StartMyAssessmentAttemptSession(ctx, request, params)
}
return handler.assessment.StartMyAssessmentAttemptSession(ctx, request, params)
}
func (handler *Handler) SubmitMyAssessmentAnswer(
ctx context.Context,
request *api.AssessmentAnswerSubmission,
params api.SubmitMyAssessmentAnswerParams,
) (api.SubmitMyAssessmentAnswerRes, error) {
if handler.assessment == nil {
return handler.UnimplementedHandler.SubmitMyAssessmentAnswer(ctx, request, params)
}
return handler.assessment.SubmitMyAssessmentAnswer(ctx, request, params)
}
func (handler *Handler) FinalizeMyAssessmentAttempt(
ctx context.Context,
request *api.AssessmentFinalization,
params api.FinalizeMyAssessmentAttemptParams,
) (api.FinalizeMyAssessmentAttemptRes, error) {
if handler.assessment == nil {
return handler.UnimplementedHandler.FinalizeMyAssessmentAttempt(ctx, request, params)
}
return handler.assessment.FinalizeMyAssessmentAttempt(ctx, request, params)
}
func (handler *Handler) GetMyAssessmentResult(
ctx context.Context,
params api.GetMyAssessmentResultParams,
) (api.GetMyAssessmentResultRes, error) {
if handler.assessment == nil {
return handler.UnimplementedHandler.GetMyAssessmentResult(ctx, params)
}
return handler.assessment.GetMyAssessmentResult(ctx, params)
}
func (handler *AssessmentHandler) CreateMyAssessmentAttempt(
ctx context.Context,
request api.AssessmentAttemptCreate,
params api.CreateMyAssessmentAttemptParams,
) (api.CreateMyAssessmentAttemptRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.CreateMyAssessmentAttemptUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, valid := assessmentCreateCommand(principal.UserID, params.IdempotencyKey, request)
if !valid {
return assessmentCreateInvalid(ctx, ""), nil
}
result, err := handler.operations.CreateAttempt(ctx, command)
if err != nil {
return assessmentCreateFailure(ctx, err)
}
if result.Outcome.StatusCode == 409 {
return (*api.CreateMyAssessmentAttemptConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
}
if result.Outcome.StatusCode != 201 {
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - unexpected stored status %d", result.Outcome.StatusCode)
}
response, err := assessmentAttemptResponse(result.Outcome.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - map response: %w", err)
}
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func (handler *AssessmentHandler) GetMyAssessmentAttempt(
ctx context.Context,
params api.GetMyAssessmentAttemptParams,
) (api.GetMyAssessmentAttemptRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyAssessmentAttemptUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
snapshot, err := handler.operations.GetMyAttempt(ctx, principal.UserID, domain.AssessmentAttemptID(params.AttemptID))
if err != nil {
return assessmentAttemptReadFailure(ctx, err)
}
response, err := assessmentAttemptResponse(snapshot)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentAttempt - map response: %w", err)
}
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func (handler *AssessmentHandler) StartMyAssessmentAttemptSession(
ctx context.Context,
request *api.AssessmentAttemptSessionStart,
params api.StartMyAssessmentAttemptSessionParams,
) (api.StartMyAssessmentAttemptSessionRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.StartMyAssessmentAttemptSessionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.StartMyAssessmentAttemptSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
result, err := handler.operations.StartSession(ctx, assessmentusecase.StartAttemptSessionCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
ExpectedVersion: int64(request.ExpectedVersion), IdempotencyKey: params.IdempotencyKey,
})
if err != nil {
return assessmentSessionFailure(ctx, err)
}
response, err := assessmentAttemptResponse(result.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.StartMyAssessmentAttemptSession - map response: %w", err)
}
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
ctx context.Context,
request *api.AssessmentAnswerSubmission,
params api.SubmitMyAssessmentAnswerParams,
) (api.SubmitMyAssessmentAnswerRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SubmitMyAssessmentAnswerUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
answer, valid := assessmentAnswerJSON(request.Answer)
if !valid {
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "/answer").Response), nil
}
operations, ok := handler.operations.(interface {
SubmitAnswer(ctx context.Context, command assessmentusecase.SubmitAttemptAnswerCommand) (outbound.AssessmentAttemptCommandResult, error)
})
if !ok {
return nil, errors.New("AssessmentHandler.SubmitMyAssessmentAnswer - answer operation is unavailable")
}
result, err := operations.SubmitAnswer(ctx, assessmentusecase.SubmitAttemptAnswerCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
ItemID: uuid.UUID(request.ItemID), ExpectedVersion: int64(request.ExpectedVersion),
IdempotencyKey: params.IdempotencyKey, Answer: answer,
})
if err != nil {
return assessmentAnswerFailure(ctx, err)
}
if result.Outcome.StatusCode != 200 {
return assessmentAnswerCommandProblem(ctx, result.Outcome)
}
response, err := assessmentAttemptResponse(result.Outcome.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.SubmitMyAssessmentAnswer - map response: %w", err)
}
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func (handler *AssessmentHandler) FinalizeMyAssessmentAttempt(
ctx context.Context,
request *api.AssessmentFinalization,
params api.FinalizeMyAssessmentAttemptParams,
) (api.FinalizeMyAssessmentAttemptRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.FinalizeMyAssessmentAttemptUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.FinalizeMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
operations, ok := handler.operations.(interface {
FinalizeAttempt(ctx context.Context, command assessmentusecase.FinalizeAssessmentAttemptCommand) (outbound.AssessmentAttemptCommandResult, error)
})
if !ok {
return nil, errors.New("AssessmentHandler.FinalizeMyAssessmentAttempt - finalize operation is unavailable")
}
result, err := operations.FinalizeAttempt(ctx, assessmentusecase.FinalizeAssessmentAttemptCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
ExpectedVersion: int64(request.ExpectedVersion), IdempotencyKey: params.IdempotencyKey,
})
if err != nil {
return assessmentFinalizeFailure(ctx, err)
}
if result.Outcome.StatusCode != 200 {
return assessmentFinalizeCommandProblem(ctx, result.Outcome)
}
response, err := assessmentAttemptResponse(result.Outcome.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.FinalizeMyAssessmentAttempt - map response: %w", err)
}
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func (handler *AssessmentHandler) GetMyAssessmentResult(
ctx context.Context,
params api.GetMyAssessmentResultParams,
) (api.GetMyAssessmentResultRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyAssessmentResultUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
operations, ok := handler.operations.(interface {
GetMyResult(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (assessmentusecase.AssessmentAttemptResult, error)
})
if !ok {
return nil, errors.New("AssessmentHandler.GetMyAssessmentResult - result operation is unavailable")
}
result, err := operations.GetMyResult(ctx, principal.UserID, domain.AssessmentAttemptID(params.AttemptID))
if err != nil {
return assessmentResultFailure(ctx, err)
}
response, err := assessmentResultResponse(result)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentResult - map response: %w", err)
}
return &api.AssessmentResultHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func assessmentAnswerJSON(answer api.AssessmentAnswer) ([]byte, bool) {
encoded, err := answer.MarshalJSON()
if err != nil {
return nil, false
}
return encoded, true
}
func assessmentCreateCommand(actorID uuid.UUID, key string, request api.AssessmentAttemptCreate) (assessmentusecase.CreateAttemptCommand, bool) {
command := assessmentusecase.CreateAttemptCommand{ActorID: actorID, IdempotencyKey: key}
switch request.Type {
case api.AssessmentQualifiedAttemptCreateAssessmentAttemptCreate:
value, ok := request.GetAssessmentQualifiedAttemptCreate()
if !ok {
return assessmentusecase.CreateAttemptCommand{}, false
}
command.Kind = domain.AssessmentAttemptKindRoot
command.Specialization = specializationPointer(value.Specialization)
command.TargetGrade = gradePointer(value.TargetGrade)
command.TaskLanguage = taskLanguagePointer(value.TaskLanguage)
case api.AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate:
value, ok := request.GetAssessmentCorrectiveAttemptCreate()
if !ok {
return assessmentusecase.CreateAttemptCommand{}, false
}
command.Kind = domain.AssessmentAttemptKindCorrective
command.Specialization = specializationPointer(value.Specialization)
command.TargetGrade = gradePointer(value.TargetGrade)
command.TaskLanguage = taskLanguagePointer(value.TaskLanguage)
command.RootAttemptID = domain.AssessmentAttemptID(value.RootAttemptID)
case api.AssessmentExpressAttemptCreateAssessmentAttemptCreate:
if _, ok := request.GetAssessmentExpressAttemptCreate(); !ok {
return assessmentusecase.CreateAttemptCommand{}, false
}
command.Kind = domain.AssessmentAttemptKindDemoExpress
default:
return assessmentusecase.CreateAttemptCommand{}, false
}
return command, true
}
func specializationPointer(value api.SpecializationCode) *domain.SpecializationCode {
code := domain.SpecializationCode(value)
return &code
}
func gradePointer(value api.GradeCode) *domain.GradeCode {
code := domain.GradeCode(value)
return &code
}
func taskLanguagePointer(value api.NilTaskLanguage) *domain.TaskLanguageCode {
language, ok := value.Get()
if !ok {
return nil
}
code := domain.TaskLanguageCode(language)
return &code
}
func assessmentCreateFailure(ctx context.Context, err error) (api.CreateMyAssessmentAttemptRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
return (*api.CreateMyAssessmentAttemptForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
return (*api.CreateMyAssessmentAttemptUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
return assessmentCreateInvalidHeader(ctx), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
return assessmentCreateInvalid(ctx, attemptFieldPointer(err)), nil
default:
return nil, err
}
}
func assessmentAttemptReadFailure(ctx context.Context, err error) (api.GetMyAssessmentAttemptRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
return (*api.GetMyAssessmentAttemptForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.GetMyAssessmentAttemptNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
func assessmentSessionFailure(ctx context.Context, err error) (api.StartMyAssessmentAttemptSessionRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
return (*api.StartMyAssessmentAttemptSessionForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.StartMyAssessmentAttemptSessionNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
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.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
return (*api.StartMyAssessmentAttemptSessionUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
return (*api.StartMyAssessmentAttemptSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
return (*api.StartMyAssessmentAttemptSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, attemptFieldPointer(err)).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),
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
return (*api.SubmitMyAssessmentAnswerForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.SubmitMyAssessmentAnswerNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
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):
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
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, attemptFieldPointer(err)).Response), nil
default:
return nil, err
}
}
func assessmentFinalizeFailure(ctx context.Context, err error) (api.FinalizeMyAssessmentAttemptRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
return (*api.FinalizeMyAssessmentAttemptForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.FinalizeMyAssessmentAttemptNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
return (*api.FinalizeMyAssessmentAttemptPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
return assessmentFinalizeConflictProblem(ctx, nil), nil
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
return (*api.FinalizeMyAssessmentAttemptUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
return (*api.FinalizeMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
return (*api.FinalizeMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, attemptFieldPointer(err)).Response), nil
default:
return nil, err
}
}
func assessmentResultFailure(ctx context.Context, err error) (api.GetMyAssessmentResultRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
return (*api.GetMyAssessmentResultForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.GetMyAssessmentResultNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
return (*api.GetMyAssessmentResultConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
default:
return nil, err
}
}
func assessmentAnswerCommandProblem(ctx context.Context, outcome outbound.AssessmentAttemptCommandOutcome) (api.SubmitMyAssessmentAnswerRes, error) {
switch outcome.StatusCode {
case 404:
if outcome.ProblemCode == "not_found" {
return (*api.SubmitMyAssessmentAnswerNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
}
case 409:
if outcome.ProblemCode == "state_conflict" {
return (*api.SubmitMyAssessmentAnswerConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
}
}
return nil, errors.New("AssessmentHandler.SubmitMyAssessmentAnswer - stored problem outcome is invalid")
}
func assessmentFinalizeCommandProblem(ctx context.Context, outcome outbound.AssessmentAttemptCommandOutcome) (api.FinalizeMyAssessmentAttemptRes, error) {
switch outcome.StatusCode {
case 404:
if outcome.ProblemCode == "not_found" {
return (*api.FinalizeMyAssessmentAttemptNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
}
case 409:
if outcome.ProblemCode == "state_conflict" {
return assessmentFinalizeConflictProblem(ctx, outcome.PendingItemIDs), nil
}
}
return nil, errors.New("AssessmentHandler.FinalizeMyAssessmentAttempt - stored problem outcome is invalid")
}
func assessmentFinalizeConflictProblem(
ctx context.Context,
pendingItemIDs []uuid.UUID,
) *api.AssessmentFinalizeConflictProblem {
base := problem.New(ctx, api.ProblemCodeStateConflict).Response
return &api.AssessmentFinalizeConflictProblem{
Type: base.Type, Title: base.Title, Status: base.Status,
Code: api.AssessmentFinalizeConflictProblemCodeStateConflict,
Detail: base.Detail, Instance: base.Instance, TraceID: base.TraceID, Errors: base.Errors,
PendingItemIds: append([]uuid.UUID(nil), pendingItemIDs...),
}
}
func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult) (api.AssessmentResult, error) {
if result.Attempt.Kind == domain.AssessmentAttemptKindDemoExpress {
if result.Outcome != domain.AssessmentAttemptOutcomeDemonstration || result.DecidedAt.IsZero() || result.Summary == "" {
return api.AssessmentResult{}, errors.New("express result is incomplete")
}
return api.NewAssessmentExpressResultAssessmentResult(api.AssessmentExpressResult{
AttemptID: result.Attempt.ID.UUID(), Kind: api.AssessmentExpressResultKindDemoExpress,
Mode: api.AssessmentExpressResultModeDemoExpress, Versions: assessmentResultVersions(result.Attempt),
Outcome: api.AssessmentExpressResultOutcomeDemonstration,
CalibrationStatus: api.AssessmentExpressResultCalibrationStatusUncalibrated,
Limitations: []api.AssessmentExpressResultLimitationsItem{api.AssessmentExpressResultLimitationsItemDemonstrationOnly},
Practices: []api.AssessmentPracticeResult{}, Gaps: []api.AssessmentGap{},
Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
NextSteps: []api.AssessmentNextStep{}, Summary: result.Summary, DecidedAt: api.Timestamp(result.DecidedAt),
}), nil
}
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
return api.AssessmentResult{}, errors.New("real result kind is invalid")
}
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
return api.AssessmentResult{}, errors.New("real result track or decision time is incomplete")
}
fields, err := assessmentRealResultFields(result)
if err != nil {
return api.AssessmentResult{}, err
}
if result.Attempt.Kind == domain.AssessmentAttemptKindRoot {
return api.NewAssessmentQualifiedResultAssessmentResult(api.AssessmentQualifiedResult{
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
Kind: api.AssessmentQualifiedResultKindRoot, Mode: api.AssessmentQualifiedResultMode(result.Attempt.Mode),
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
NextSteps: []api.AssessmentNextStep{}, DecidedAt: api.Timestamp(result.DecidedAt),
}), nil
}
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
return api.AssessmentResult{}, errors.New("corrective result chain is incomplete")
}
return api.NewAssessmentCorrectiveResultAssessmentResult(api.AssessmentCorrectiveResult{
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
Kind: api.AssessmentCorrectiveResultKindCorrective, Mode: api.AssessmentCorrectiveResultMode(result.Attempt.Mode),
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
NextSteps: []api.AssessmentNextStep{}, DecidedAt: api.Timestamp(result.DecidedAt),
}), nil
}
type assessmentRealResultResponseFields struct {
rootAttemptID api.NilUUID
chainDeadline api.NilTimestamp
taskLanguage api.NilTaskLanguage
outcome api.AssessmentOutcome
reason api.NilAssessmentNotDeterminedReason
confirmedGrade api.NilGradeCode
previousGrade api.NilGradeCode
strength api.NilAssessmentStrength
limitations []api.AssessmentLimitation
uncertainty api.NilAssessmentUncertainty
basicScore api.NilBasicScore
}
func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult) (assessmentRealResultResponseFields, error) {
fields := assessmentRealResultResponseFields{
outcome: api.AssessmentOutcome(result.Outcome), limitations: make([]api.AssessmentLimitation, 0, len(result.Limitations)),
}
if result.Attempt.Kind == domain.AssessmentAttemptKindCorrective {
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
return assessmentRealResultResponseFields{}, errors.New("corrective result chain is incomplete")
}
fields.rootAttemptID.SetTo(result.Attempt.RootAttemptID.UUID())
fields.chainDeadline.SetTo(api.Timestamp(*result.Attempt.ChainDeadline))
} else {
fields.rootAttemptID.SetToNull()
fields.chainDeadline.SetToNull()
}
if result.Attempt.TaskLanguage == nil {
fields.taskLanguage.SetToNull()
} else {
fields.taskLanguage.SetTo(api.TaskLanguage(*result.Attempt.TaskLanguage))
}
if result.NotDeterminedReason == "" {
fields.reason.SetToNull()
} else {
fields.reason.SetTo(api.AssessmentNotDeterminedReason(result.NotDeterminedReason))
}
fields.confirmedGrade.SetToNull()
fields.previousGrade.SetToNull()
fields.strength.SetToNull()
fields.uncertainty.SetToNull()
if result.BasicScore == nil {
fields.basicScore.SetToNull()
} else {
fields.basicScore.SetTo(api.BasicScore{
Points: result.BasicScore.Points, MaxPoints: result.BasicScore.MaxPoints, PassPoints: result.BasicScore.PassPoints,
})
}
for _, limitation := range result.Limitations {
fields.limitations = append(fields.limitations, api.AssessmentLimitation(limitation))
}
return fields, nil
}
func assessmentResultVersions(snapshot domain.AssessmentAttemptPublicSnapshot) api.AssessmentVersions {
return api.AssessmentVersions{
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
AlgorithmVersion: api.AssessmentVersionLabel(snapshot.AlgorithmVersion),
}
}
func assessmentItemsSeconds(result assessmentusecase.AssessmentAttemptResult) int32 {
seconds := int64(result.DecidedAt.Sub(result.Attempt.StartedAt) / time.Second)
if seconds < 0 || seconds > 1<<31-1 {
return 0
}
return int32(seconds)
}
func nilInt32() api.NilInt32 {
var value api.NilInt32
value.SetToNull()
return value
}
func assessmentCreateInvalid(ctx context.Context, pointer string) api.CreateMyAssessmentAttemptRes {
return (*api.CreateMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, pointer).Response)
}
func assessmentCreateInvalidHeader(ctx context.Context) api.CreateMyAssessmentAttemptRes {
return (*api.CreateMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response)
}
func attemptFieldPointer(err error) string {
fieldError, ok := errors.AsType[*assessmentusecase.AttemptFieldError](err)
if !ok || fieldError == nil {
return ""
}
return fieldError.Pointer
}
func assessmentAttemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot) (api.AssessmentAttempt, error) {
current, err := assessmentCurrentItem(snapshot.CurrentItem)
if err != nil {
return api.AssessmentAttempt{}, err
}
fields := assessmentAttemptFields(snapshot, current)
switch snapshot.Kind {
case domain.AssessmentAttemptKindRoot:
return api.NewAssessmentQualifiedAttemptAssessmentAttempt(api.AssessmentQualifiedAttempt{
ID: snapshot.ID.UUID(), Version: api.AssessmentAttemptVersion(snapshot.Version),
Specialization: fields.specialization, TargetGrade: fields.targetGrade, TaskLanguage: fields.taskLanguage,
Kind: api.AssessmentQualifiedAttemptKindRoot, RootAttemptID: fields.rootAttemptID, ChainDeadline: fields.chainDeadline,
Mode: api.AssessmentQualifiedAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
}), nil
case domain.AssessmentAttemptKindCorrective:
return api.NewAssessmentCorrectiveAttemptAssessmentAttempt(api.AssessmentCorrectiveAttempt{
ID: snapshot.ID.UUID(), Version: api.AssessmentAttemptVersion(snapshot.Version),
Specialization: fields.specialization, TargetGrade: fields.targetGrade, TaskLanguage: fields.taskLanguage,
Kind: api.AssessmentCorrectiveAttemptKindCorrective, RootAttemptID: fields.rootAttemptID, ChainDeadline: fields.chainDeadline,
Mode: api.AssessmentCorrectiveAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
}), nil
case domain.AssessmentAttemptKindDemoExpress:
return api.NewAssessmentExpressAttemptAssessmentAttempt(api.AssessmentExpressAttempt{
ID: snapshot.ID.UUID(), Version: api.AssessmentAttemptVersion(snapshot.Version),
Specialization: fields.specialization, TargetGrade: fields.targetGrade, TaskLanguage: fields.taskLanguage,
Kind: api.AssessmentExpressAttemptKindDemoExpress, RootAttemptID: fields.rootAttemptID, ChainDeadline: fields.chainDeadline,
Mode: api.AssessmentExpressAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
}), nil
default:
return api.AssessmentAttempt{}, errors.New("unknown assessment attempt kind")
}
}
type assessmentAttemptResponseFields struct {
specialization api.NilSpecializationCode
targetGrade api.NilGradeCode
taskLanguage api.NilTaskLanguage
rootAttemptID api.NilUUID
chainDeadline api.NilTimestamp
versions api.AssessmentVersions
startedAt api.Timestamp
expiresAt api.Timestamp
sessions api.NilAssessmentSessions
finishedAt api.NilTimestamp
progress api.AssessmentProgress
currentItem api.NilAssessmentItem
}
func assessmentAttemptFields(snapshot domain.AssessmentAttemptPublicSnapshot, currentItem api.NilAssessmentItem) assessmentAttemptResponseFields {
fields := assessmentAttemptResponseFields{
versions: api.AssessmentVersions{
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
AlgorithmVersion: api.AssessmentVersionLabel(snapshot.AlgorithmVersion),
},
startedAt: api.Timestamp(snapshot.StartedAt), expiresAt: api.Timestamp(snapshot.ExpiresAt),
progress: api.AssessmentProgress{AnsweredItems: snapshot.AnsweredItems, MaxItems: snapshot.MaxItems},
currentItem: currentItem,
}
setAttemptTrackFields(&fields, snapshot)
setAttemptSessionFields(&fields, snapshot)
setAttemptEndFields(&fields, snapshot)
return fields
}
func setAttemptTrackFields(fields *assessmentAttemptResponseFields, snapshot domain.AssessmentAttemptPublicSnapshot) {
if snapshot.Specialization == nil {
fields.specialization.SetToNull()
} else {
fields.specialization.SetTo(api.SpecializationCode(*snapshot.Specialization))
}
if snapshot.TargetGrade == nil {
fields.targetGrade.SetToNull()
} else {
fields.targetGrade.SetTo(api.GradeCode(*snapshot.TargetGrade))
}
if snapshot.TaskLanguage == nil {
fields.taskLanguage.SetToNull()
} else {
fields.taskLanguage.SetTo(api.TaskLanguage(*snapshot.TaskLanguage))
}
if snapshot.RootAttemptID == nil {
fields.rootAttemptID.SetToNull()
} else {
fields.rootAttemptID.SetTo(snapshot.RootAttemptID.UUID())
}
if snapshot.ChainDeadline == nil {
fields.chainDeadline.SetToNull()
} else {
fields.chainDeadline.SetTo(api.Timestamp(*snapshot.ChainDeadline))
}
}
func setAttemptSessionFields(fields *assessmentAttemptResponseFields, snapshot domain.AssessmentAttemptPublicSnapshot) {
if snapshot.MaxSessions <= 0 {
fields.sessions.SetToNull()
return
}
fields.sessions.SetTo(api.AssessmentSessions{
Used: snapshot.SessionsUsed, Max: snapshot.MaxSessions, IdleTimeoutSeconds: snapshot.IdleTimeout,
})
}
func setAttemptEndFields(fields *assessmentAttemptResponseFields, snapshot domain.AssessmentAttemptPublicSnapshot) {
if snapshot.FinishedAt == nil {
fields.finishedAt.SetToNull()
return
}
fields.finishedAt.SetTo(api.Timestamp(*snapshot.FinishedAt))
}
func assessmentCurrentItem(item *domain.AssessmentAttemptPublicItem) (api.NilAssessmentItem, error) {
var current api.NilAssessmentItem
if item == nil {
current.SetToNull()
return current, nil
}
content, err := assessmentItemContent(item.Content)
if err != nil {
return api.NilAssessmentItem{}, err
}
current.SetTo(api.AssessmentItem{
ID: api.AssessmentItemId(item.ID), Sequence: item.Sequence, Prompt: item.Prompt, Content: content,
})
return current, nil
}
func assessmentItemContent(content domain.AssessmentAttemptPublicItemContent) (api.ItemContent, error) {
switch content.Format {
case "number":
var unit api.NilString
if content.Unit == nil {
unit.SetToNull()
} else {
unit.SetTo(*content.Unit)
}
return api.NewNumberItemContentItemContent(api.NumberItemContent{Format: api.NumberItemContentFormatNumber, Unit: unit}), nil
case "order":
elements := make([]api.AssessmentOption, 0, len(content.Elements))
for _, element := range content.Elements {
elements = append(elements, api.AssessmentOption{ID: api.AssessmentOptionId(element.ID), Text: element.Text})
}
return api.NewOrderItemContentItemContent(api.OrderItemContent{Format: api.OrderItemContentFormatOrder, Elements: elements}), nil
default:
return api.ItemContent{}, errors.New("unsupported public assessment item format")
}
}
@@ -0,0 +1,157 @@
package v1
import (
"context"
"errors"
"fmt"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
func (handler *AssessmentHandler) GetMyAssessmentAvailability(
ctx context.Context,
) (api.GetMyAssessmentAvailabilityRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyAssessmentAvailabilityUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
availability, err := handler.operations.GetMyAssessmentAvailability(ctx, principal.UserID)
if err != nil {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
return (*api.GetMyAssessmentAvailabilityForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAssessmentAvailabilityNotImplemented):
return nil, problem.New(ctx, api.ProblemCodeNotImplemented)
default:
return nil, err
}
}
response, err := assessmentAvailabilityResponse(availability)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentAvailability - map response: %w", err)
}
return &api.AssessmentAvailabilityHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func assessmentAvailabilityResponse(
availability assessmentusecase.AssessmentAvailability,
) (api.AssessmentAvailability, error) {
response := api.AssessmentAvailability{Specializations: make([]api.AssessmentSpecializationAvailability, 0, len(availability.Specializations))}
for _, item := range availability.Specializations {
if !item.Specialization.IsKnown() {
return api.AssessmentAvailability{}, errors.New("assessment availability has an unknown specialization")
}
specialization := api.AssessmentSpecializationAvailability{
Specialization: api.SpecializationCode(item.Specialization),
Grades: make([]api.AssessmentGradeAvailability, 0, len(item.Grades)),
}
specialization.ConfirmedGrade.SetToNull()
if item.ConfirmedGrade != nil {
if !item.ConfirmedGrade.IsKnown() {
return api.AssessmentAvailability{}, errors.New("assessment availability has an unknown confirmed grade")
}
specialization.ConfirmedGrade.SetTo(api.GradeCode(*item.ConfirmedGrade))
}
specialization.ActiveAttemptID.SetToNull()
if item.ActiveAttemptID != nil {
if item.ActiveAttemptID.IsZero() {
return api.AssessmentAvailability{}, errors.New("assessment availability has an invalid active attempt ID")
}
specialization.ActiveAttemptID.SetTo(item.ActiveAttemptID.UUID())
}
for _, grade := range item.Grades {
mapped, err := assessmentGradeAvailabilityResponse(grade)
if err != nil {
return api.AssessmentAvailability{}, err
}
specialization.Grades = append(specialization.Grades, mapped)
}
response.Specializations = append(response.Specializations, specialization)
}
return response, nil
}
func assessmentGradeAvailabilityResponse(
grade assessmentusecase.GradeAvailability,
) (api.AssessmentGradeAvailability, error) {
if !grade.Grade.IsKnown() {
return api.AssessmentGradeAvailability{}, errors.New("assessment availability has an unknown grade")
}
response := api.AssessmentGradeAvailability{Grade: api.GradeCode(grade.Grade)}
response.Mode.SetToNull()
response.AvailableAt.SetToNull()
response.TimeLimitSeconds.SetToNull()
response.MaxSessions.SetToNull()
response.MaxItems.SetToNull()
response.PracticeRequired.SetToNull()
status, err := assessmentAvailabilityStatus(grade)
if err != nil {
return api.AssessmentGradeAvailability{}, err
}
response.Status = status
if err := setAssessmentAvailabilityLimits(&response, grade); err != nil {
return api.AssessmentGradeAvailability{}, err
}
return response, nil
}
func assessmentAvailabilityStatus(
grade assessmentusecase.GradeAvailability,
) (api.AssessmentGradeAvailabilityStatus, error) {
switch grade.Status {
case assessmentusecase.AvailabilityStatusAvailable:
return api.AssessmentGradeAvailabilityStatusAvailable, nil
case assessmentusecase.AvailabilityStatusActiveAttempt:
return api.AssessmentGradeAvailabilityStatusActiveAttempt, nil
case assessmentusecase.AvailabilityStatusCooldown:
if grade.AvailableAt == nil || grade.AvailableAt.IsZero() {
return "", errors.New("assessment cooldown has no available time")
}
return api.AssessmentGradeAvailabilityStatusCooldown, nil
case assessmentusecase.AvailabilityStatusInsufficientBank:
return api.AssessmentGradeAvailabilityStatusInsufficientBank, nil
default:
return "", errors.New("assessment availability has an unknown status")
}
}
func setAssessmentAvailabilityLimits(
response *api.AssessmentGradeAvailability,
grade assessmentusecase.GradeAvailability,
) error {
if grade.Status == assessmentusecase.AvailabilityStatusInsufficientBank {
return validateInsufficientBankLimits(grade)
}
if err := validateAssessmentAttemptLimits(grade); err != nil {
return err
}
if grade.Status == assessmentusecase.AvailabilityStatusCooldown {
response.AvailableAt.SetTo(api.Timestamp(grade.AvailableAt.UTC()))
}
response.Mode.SetTo(api.AssessmentRealMode(*grade.Mode))
response.TimeLimitSeconds.SetTo(*grade.TimeLimitSeconds)
response.MaxSessions.SetTo(*grade.MaxSessions)
response.MaxItems.SetTo(*grade.MaxItems)
response.PracticeRequired.SetTo(*grade.PracticeRequired)
return nil
}
func validateInsufficientBankLimits(grade assessmentusecase.GradeAvailability) error {
if grade.Mode != nil || grade.AvailableAt != nil || grade.TimeLimitSeconds != nil || grade.MaxSessions != nil ||
grade.MaxItems != nil || grade.PracticeRequired != nil {
return errors.New("insufficient-bank availability contains attempt limits")
}
return nil
}
func validateAssessmentAttemptLimits(grade assessmentusecase.GradeAvailability) error {
if grade.Mode == nil || *grade.Mode != domain.AssessmentRealModeDemoBasic || grade.TimeLimitSeconds == nil ||
*grade.TimeLimitSeconds <= 0 || grade.MaxSessions == nil || *grade.MaxSessions <= 0 || grade.MaxItems == nil ||
*grade.MaxItems <= 0 || grade.PracticeRequired == nil {
return errors.New("available assessment has incomplete attempt limits")
}
return nil
}
@@ -0,0 +1,99 @@
package v1
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
func TestGetMyAssessmentAvailabilityMapsReadOnlyCandidateProjection(t *testing.T) {
userID := uuid.New()
activeAttemptID := domain.AssessmentAttemptID(uuid.New())
availableAt := time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC)
seconds, sessions, items := int32(3600), int32(2), int32(25)
mode := domain.AssessmentRealModeDemoBasic
practice := false
operations := &assessmentOperationsStub{availability: assessmentusecase.AssessmentAvailability{
Specializations: []assessmentusecase.SpecializationAvailability{{
Specialization: domain.SpecializationCode("backend"), ActiveAttemptID: &activeAttemptID,
Grades: []assessmentusecase.GradeAvailability{
{Grade: domain.GradeIntern, Status: assessmentusecase.AvailabilityStatusActiveAttempt,
Mode: &mode, TimeLimitSeconds: &seconds, MaxSessions: &sessions, MaxItems: &items, PracticeRequired: &practice},
{Grade: domain.GradeJunior, Status: assessmentusecase.AvailabilityStatusCooldown,
Mode: &mode, AvailableAt: &availableAt, TimeLimitSeconds: &seconds, MaxSessions: &sessions,
MaxItems: &items, PracticeRequired: &practice},
{Grade: domain.GradeMiddle, Status: assessmentusecase.AvailabilityStatusInsufficientBank},
},
}},
}}
handler := NewAssessmentHandler(operations)
response, err := handler.GetMyAssessmentAvailability(principalForTest(userID))
if err != nil {
t.Fatalf("GetMyAssessmentAvailability() error = %v", err)
}
headers, ok := response.(*api.AssessmentAvailabilityHeaders)
if !ok || headers.CacheControl != api.CacheControlNoStoreNoStore || operations.availabilityCalls != 1 ||
operations.availabilityUserID != userID {
t.Fatalf("availability response = %T %+v, calls=%d user=%s", response, response, operations.availabilityCalls, operations.availabilityUserID)
}
if len(headers.Response.Specializations) != 1 {
t.Fatalf("specializations = %+v", headers.Response.Specializations)
}
specialization := headers.Response.Specializations[0]
if specialization.Specialization != api.SpecializationCodeBackend || !specialization.ConfirmedGrade.IsNull() {
t.Fatalf("specialization = %+v", specialization)
}
if activeID, found := specialization.ActiveAttemptID.Get(); !found || activeID != activeAttemptID.UUID() {
t.Fatalf("active attempt ID = %+v, %v", specialization.ActiveAttemptID, found)
}
if len(specialization.Grades) != 3 {
t.Fatalf("grade availability = %+v", specialization.Grades)
}
if row := specialization.Grades[0]; row.Status != api.AssessmentGradeAvailabilityStatusActiveAttempt ||
row.Mode.IsNull() || !row.AvailableAt.IsNull() || row.TimeLimitSeconds.IsNull() {
// Active rows carry their mode and limits but never an available_at value.
t.Fatalf("active grade projection = %+v", row)
}
if row := specialization.Grades[1]; row.Status != api.AssessmentGradeAvailabilityStatusCooldown ||
row.AvailableAt.IsNull() || row.AvailableAt.Value != api.Timestamp(availableAt) || row.TimeLimitSeconds.IsNull() {
t.Fatalf("cooldown grade projection = %+v", row)
}
if row := specialization.Grades[2]; row.Status != api.AssessmentGradeAvailabilityStatusInsufficientBank ||
!row.Mode.IsNull() || !row.TimeLimitSeconds.IsNull() || !row.AvailableAt.IsNull() {
t.Fatalf("insufficient-bank projection = %+v", row)
}
}
func TestGetMyAssessmentAvailabilityMapsAuthAndUnavailableMode(t *testing.T) {
operations := &assessmentOperationsStub{availabilityErr: assessmentusecase.ErrAssessmentAvailabilityNotImplemented}
handler := NewAssessmentHandler(operations)
unauthenticated, err := handler.GetMyAssessmentAvailability(noPrincipalContext())
if err != nil {
t.Fatalf("unauthenticated availability error = %v", err)
}
if _, ok := unauthenticated.(*api.GetMyAssessmentAvailabilityUnauthorized); !ok || operations.availabilityCalls != 0 {
t.Fatalf("unauthenticated response = %T, calls=%d", unauthenticated, operations.availabilityCalls)
}
_, err = handler.GetMyAssessmentAvailability(principalForTest(uuid.New()))
var statusError *api.ProblemStatusCode
if !errors.As(err, &statusError) || statusError.GetStatusCode() != 501 {
t.Fatalf("unavailable mode error = %v, want a 501 problem", err)
}
operations.availabilityErr = assessmentusecase.ErrAttemptForbidden
forbidden, err := handler.GetMyAssessmentAvailability(principalForTest(uuid.New()))
if err != nil {
t.Fatalf("forbidden availability error = %v", err)
}
if _, ok := forbidden.(*api.GetMyAssessmentAvailabilityForbidden); !ok {
t.Fatalf("forbidden response = %T", forbidden)
}
}
func noPrincipalContext() context.Context { return context.Background() }
@@ -0,0 +1,190 @@
package v1
import (
"context"
"errors"
"math"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
type AssessmentSignalOperations interface {
RecordSignals(ctx context.Context, command assessmentusecase.RecordSignalsCommand) (domain.AssessmentSignalReceipt, error)
}
// AssessmentSignalHandler maps the typed candidate contract to domain input.
// It never logs or returns event details.
type AssessmentSignalHandler struct {
operations AssessmentSignalOperations
}
func NewAssessmentSignalHandler(operations AssessmentSignalOperations) *AssessmentSignalHandler {
if operations == nil {
panic("v1.NewAssessmentSignalHandler - assessment signal operations must not be nil")
}
return &AssessmentSignalHandler{operations: operations}
}
func (handler *Handler) RecordMyAssessmentAttemptSignals(
ctx context.Context,
request *api.AssessmentSignalBatch,
params api.RecordMyAssessmentAttemptSignalsParams,
) (api.RecordMyAssessmentAttemptSignalsRes, error) {
if handler.assessmentSignals == nil {
return handler.UnimplementedHandler.RecordMyAssessmentAttemptSignals(ctx, request, params)
}
return handler.assessmentSignals.RecordMyAssessmentAttemptSignals(ctx, request, params)
}
func (handler *AssessmentSignalHandler) RecordMyAssessmentAttemptSignals(
ctx context.Context,
request *api.AssessmentSignalBatch,
params api.RecordMyAssessmentAttemptSignalsParams,
) (api.RecordMyAssessmentAttemptSignalsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.RecordMyAssessmentAttemptSignalsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return signalInvalidBody(ctx), nil
}
events, valid := assessmentSignalEvents(request.Events)
if !valid {
return signalInvalidBody(ctx), nil
}
receipt, err := handler.operations.RecordSignals(ctx, assessmentusecase.RecordSignalsCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
IdempotencyKey: params.IdempotencyKey, Events: events,
})
if err != nil {
return signalFailure(ctx, err)
}
return &api.AssessmentSignalReceiptHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.AssessmentSignalReceipt{
Status: api.AssessmentSignalReceiptStatus(receipt.Status()), AcceptedEvents: receipt.AcceptedEvents(),
ReceivedAt: api.Timestamp(receipt.ReceivedAt()),
},
}, nil
}
func assessmentSignalEvents(requestEvents []api.AssessmentSignalEvent) ([]domain.AssessmentSignalEvent, bool) {
if len(requestEvents) == 0 || len(requestEvents) > 50 {
return nil, false
}
events := make([]domain.AssessmentSignalEvent, 0, len(requestEvents))
for _, requestEvent := range requestEvents {
input, valid := assessmentSignalEventInput(requestEvent)
if !valid {
return nil, false
}
event, err := domain.NewAssessmentSignalEvent(input)
if err != nil {
return nil, false
}
events = append(events, event)
}
return events, true
}
func assessmentSignalEventInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
switch requestEvent.Type {
case api.AssessmentFocusLossSignalAssessmentSignalEvent:
return assessmentFocusLossInput(requestEvent)
case api.AssessmentSignalEventCopyAssessmentSignalEvent,
api.AssessmentSignalEventPasteAssessmentSignalEvent,
api.AssessmentSignalEventCutAssessmentSignalEvent:
return assessmentClipboardInput(requestEvent)
case api.AssessmentFullscreenExitSignalAssessmentSignalEvent:
return assessmentFullscreenExitInput(requestEvent)
default:
return domain.AssessmentSignalEventInput{}, false
}
}
func assessmentFocusLossInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
value, ok := requestEvent.GetAssessmentFocusLossSignal()
if !ok || value.Kind != api.AssessmentFocusLossSignalKindFocusLoss {
return domain.AssessmentSignalEventInput{}, false
}
duration := value.DurationMs
return domain.AssessmentSignalEventInput{
Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: uuid.UUID(value.ItemInstanceID),
OccurredAt: time.Time(value.OccurredAt), DurationMS: &duration,
}, true
}
func assessmentClipboardInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
value, ok := requestEvent.GetAssessmentClipboardSignal()
if !ok {
return domain.AssessmentSignalEventInput{}, false
}
kind := domain.AssessmentSignalKind(value.Kind)
if kind != domain.AssessmentSignalKind(requestEvent.Type) {
return domain.AssessmentSignalEventInput{}, false
}
size := value.SizeBytes
return domain.AssessmentSignalEventInput{
Kind: kind, ItemInstanceID: uuid.UUID(value.ItemInstanceID),
OccurredAt: time.Time(value.OccurredAt), SizeBytes: &size,
}, true
}
func assessmentFullscreenExitInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
value, ok := requestEvent.GetAssessmentFullscreenExitSignal()
if !ok || value.Kind != api.AssessmentFullscreenExitSignalKindFullscreenExit {
return domain.AssessmentSignalEventInput{}, false
}
return domain.AssessmentSignalEventInput{
Kind: domain.AssessmentSignalFullscreenExit, 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,
)
}
func signalFailure(ctx context.Context, err error) (api.RecordMyAssessmentAttemptSignalsRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
errors.Is(err, assessmentusecase.ErrAttemptSignalForbidden), errors.Is(err, assessmentusecase.ErrAttemptSignalConsentRequired):
return (*api.RecordMyAssessmentAttemptSignalsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.RecordMyAssessmentAttemptSignalsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptSignalStateConflict):
return (*api.RecordMyAssessmentAttemptSignalsConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
return (*api.RecordMyAssessmentAttemptSignalsUnprocessableEntity)(
&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response,
), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
return (*api.RecordMyAssessmentAttemptSignalsBadRequest)(
&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response,
), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptSignalRequest), errors.Is(err, domain.ErrInvalidAssessmentSignal):
return signalInvalidBody(ctx), nil
case errors.Is(err, assessmentusecase.ErrAttemptSignalRateLimited):
limited, ok := errors.AsType[*assessmentusecase.SignalRateLimitError](err)
if !ok || limited == nil {
return nil, err
}
wait := time.Until(limited.RetryAt)
if wait < time.Second {
wait = time.Second
}
seconds := int32(math.Ceil(wait.Seconds()))
return problem.RateLimited(ctx, seconds), nil
default:
return nil, err
}
}
@@ -0,0 +1,172 @@
package v1
import (
"context"
"errors"
"reflect"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
type assessmentSignalOperationsStub struct {
command assessmentusecase.RecordSignalsCommand
receipt domain.AssessmentSignalReceipt
err error
calls int
}
func (stub *assessmentSignalOperationsStub) RecordSignals(
_ context.Context,
command assessmentusecase.RecordSignalsCommand,
) (domain.AssessmentSignalReceipt, error) {
stub.calls++
stub.command = command
return stub.receipt, stub.err
}
func TestAssessmentSignalHandlerMapsAllowlistedEventVariants(t *testing.T) {
actorID, attemptID, itemID := uuid.New(), uuid.New(), uuid.New()
at := api.Timestamp(time.Date(2026, time.October, 7, 12, 0, 0, 123456000, time.UTC))
duration, size := int32(4500), int32(32)
request := &api.AssessmentSignalBatch{Events: []api.AssessmentSignalEvent{
api.NewAssessmentFocusLossSignalAssessmentSignalEvent(api.AssessmentFocusLossSignal{
Kind: api.AssessmentFocusLossSignalKindFocusLoss, ItemInstanceID: api.AssessmentItemId(itemID),
OccurredAt: at, DurationMs: duration,
}),
api.NewAssessmentSignalEventCopyAssessmentSignalEvent(api.AssessmentClipboardSignal{
Kind: api.AssessmentClipboardSignalKindCopy, ItemInstanceID: api.AssessmentItemId(itemID),
OccurredAt: at, SizeBytes: size,
}),
api.NewAssessmentSignalEventPasteAssessmentSignalEvent(api.AssessmentClipboardSignal{
Kind: api.AssessmentClipboardSignalKindPaste, ItemInstanceID: api.AssessmentItemId(itemID),
OccurredAt: at, SizeBytes: size,
}),
api.NewAssessmentSignalEventCutAssessmentSignalEvent(api.AssessmentClipboardSignal{
Kind: api.AssessmentClipboardSignalKindCut, ItemInstanceID: api.AssessmentItemId(itemID),
OccurredAt: at, SizeBytes: size,
}),
api.NewAssessmentFullscreenExitSignalAssessmentSignalEvent(api.AssessmentFullscreenExitSignal{
Kind: api.AssessmentFullscreenExitSignalKindFullscreenExit, ItemInstanceID: api.AssessmentItemId(itemID),
OccurredAt: at,
}),
}}
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptAccepted, 5, time.Now())
if err != nil {
t.Fatalf("NewAssessmentSignalReceipt() error = %v", err)
}
operations := &assessmentSignalOperationsStub{receipt: receipt}
handler := NewAssessmentSignalHandler(operations)
result, err := handler.RecordMyAssessmentAttemptSignals(principalForTest(actorID), request,
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: attemptID, IdempotencyKey: "event-batch"})
if err != nil {
t.Fatalf("RecordMyAssessmentAttemptSignals() error = %v", err)
}
response, ok := result.(*api.AssessmentSignalReceiptHeaders)
if !ok {
t.Fatalf("RecordMyAssessmentAttemptSignals() result = %T, want receipt headers", result)
}
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.AcceptedEvents != 5 ||
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 {
t.Fatalf("record command = %+v, calls %d", command, operations.calls)
}
wantKinds := []domain.AssessmentSignalKind{
domain.AssessmentSignalFocusLoss, domain.AssessmentSignalCopy, domain.AssessmentSignalPaste,
domain.AssessmentSignalCut, domain.AssessmentSignalFullscreenExit,
}
for index, event := range command.Events {
if event.Kind() != wantKinds[index] || event.ItemInstanceID() != itemID || !event.OccurredAt().Equal(time.Time(at)) {
t.Errorf("event %d = %s / %s / %s", index, event.Kind(), event.ItemInstanceID(), event.OccurredAt())
}
}
if got, ok := command.Events[0].DurationMS(); !ok || got != duration {
t.Errorf("focus duration = %d, %v; want %d, true", got, ok, duration)
}
for _, index := range []int{1, 2, 3} {
if got, ok := command.Events[index].SizeBytes(); !ok || got != size {
t.Errorf("clipboard size at %d = %d, %v; want %d, true", index, got, ok, size)
}
}
}
func TestAssessmentSignalHandlerMapsAuthorizationAndBusinessProblems(t *testing.T) {
for _, testCase := range []struct {
name string
err error
want any
}{
{name: "forbidden", err: assessmentusecase.ErrAttemptSignalConsentRequired, want: (*api.RecordMyAssessmentAttemptSignalsForbidden)(nil)},
{name: "missing attempt", err: assessmentusecase.ErrAttemptNotFound, want: (*api.RecordMyAssessmentAttemptSignalsNotFound)(nil)},
{name: "state conflict", err: assessmentusecase.ErrAttemptSignalStateConflict, want: (*api.RecordMyAssessmentAttemptSignalsConflict)(nil)},
{name: "key reused", err: assessmentusecase.ErrAttemptKeyReused, want: (*api.RecordMyAssessmentAttemptSignalsUnprocessableEntity)(nil)},
{name: "invalid key", err: assessmentusecase.ErrInvalidAttemptKey, want: (*api.RecordMyAssessmentAttemptSignalsBadRequest)(nil)},
} {
t.Run(testCase.name, func(t *testing.T) {
result, err := signalFailure(context.Background(), testCase.err)
if err != nil {
t.Fatalf("signalFailure() error = %v", err)
}
if result == nil || reflect.TypeOf(result) != reflect.TypeOf(testCase.want) {
t.Fatalf("signalFailure() result = %T, want %T", result, testCase.want)
}
})
}
result, err := signalFailure(context.Background(), &assessmentusecase.SignalRateLimitError{RetryAt: time.Now().Add(4 * time.Second)})
if err != nil {
t.Fatalf("signalFailure(rate limit) error = %v", err)
}
limited, ok := result.(*api.TooManyRequestsHeaders)
if !ok {
t.Fatalf("signalFailure(rate limit) result = %T", result)
}
if seconds, present := limited.RetryAfter.Get(); !present || seconds < 1 || seconds > 4 {
t.Fatalf("Retry-After = %d, %v; want 1 to 4 seconds", seconds, present)
}
operations := &assessmentSignalOperationsStub{}
handler := NewAssessmentSignalHandler(operations)
unauthorized, err := handler.RecordMyAssessmentAttemptSignals(context.Background(), &api.AssessmentSignalBatch{}, api.RecordMyAssessmentAttemptSignalsParams{})
if err != nil {
t.Fatalf("unauthenticated RecordMyAssessmentAttemptSignals() error = %v", err)
}
if _, ok := unauthorized.(*api.RecordMyAssessmentAttemptSignalsUnauthorized); !ok || operations.calls != 0 {
t.Fatalf("unauthenticated result = %T, calls %d", unauthorized, operations.calls)
}
}
func TestAssessmentSignalHandlerRejectsWrongVariantAndInternalErrorsPropagate(t *testing.T) {
operations := &assessmentSignalOperationsStub{err: errors.New("private storage failure")}
handler := NewAssessmentSignalHandler(operations)
request := &api.AssessmentSignalBatch{Events: []api.AssessmentSignalEvent{{Type: "unknown"}}}
invalid, err := handler.RecordMyAssessmentAttemptSignals(principalForTest(uuid.New()), request,
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
if err != nil {
t.Fatalf("invalid variant error = %v", err)
}
if _, ok := invalid.(*api.RecordMyAssessmentAttemptSignalsBadRequest); !ok || operations.calls != 0 {
t.Fatalf("invalid variant result = %T, calls %d", invalid, operations.calls)
}
request.Events = []api.AssessmentSignalEvent{
api.NewAssessmentFullscreenExitSignalAssessmentSignalEvent(api.AssessmentFullscreenExitSignal{
Kind: api.AssessmentFullscreenExitSignalKindFullscreenExit, ItemInstanceID: api.AssessmentItemId(uuid.New()),
OccurredAt: api.Timestamp(time.Now()),
}),
}
_, err = handler.RecordMyAssessmentAttemptSignals(principalForTest(uuid.New()), request,
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
if err == nil || err.Error() != "private storage failure" {
t.Fatalf("internal error = %v, want sanitized propagation to responder", err)
}
}
@@ -0,0 +1,237 @@
package v1
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
func TestCreateAssessmentAttemptMapsRootAndPublicSnapshot(t *testing.T) {
userID := uuid.New()
snapshot := assessmentPublicSnapshot()
operations := &assessmentOperationsStub{create: outbound.AssessmentAttemptCreateResult{
Outcome: outbound.AssessmentAttemptCreateOutcome{StatusCode: 201, Response: snapshot},
}}
handler := NewAssessmentHandler(operations)
request := api.NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate(api.AssessmentQualifiedAttemptCreate{
Kind: api.AssessmentQualifiedAttemptCreateKindRoot, Specialization: "backend", TargetGrade: "junior",
TaskLanguage: api.NewNilTaskLanguage(api.TaskLanguage("go")),
})
response, err := handler.CreateMyAssessmentAttempt(principalForTest(userID), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "create-key"})
if err != nil {
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
}
if operations.createCalls != 1 || operations.createCommand.ActorID != userID || operations.createCommand.Kind != domain.AssessmentAttemptKindRoot ||
operations.createCommand.IdempotencyKey != "create-key" || operations.createCommand.Specialization == nil ||
*operations.createCommand.Specialization != "backend" || operations.createCommand.TargetGrade == nil ||
*operations.createCommand.TargetGrade != "junior" || operations.createCommand.TaskLanguage == nil ||
*operations.createCommand.TaskLanguage != "go" {
t.Fatalf("CreateAttempt() command = %+v, calls %d", operations.createCommand, operations.createCalls)
}
headers, ok := response.(*api.AssessmentAttemptHeaders)
if !ok || headers.CacheControl != api.CacheControlNoStoreNoStore {
t.Fatalf("create response = %T %+v, want no-store headers", response, response)
}
qualified, ok := headers.Response.GetAssessmentQualifiedAttempt()
if !ok || qualified.ID != snapshot.ID.UUID() || qualified.Version != api.AssessmentAttemptVersion(snapshot.Version) ||
qualified.CurrentItem.IsNull() || qualified.Progress.MaxItems != snapshot.MaxItems ||
qualified.Versions.AlgorithmVersion != api.AssessmentVersionLabel(snapshot.AlgorithmVersion) {
t.Fatalf("qualified attempt response = %+v, %v", qualified, ok)
}
item, ok := qualified.CurrentItem.Get()
if !ok || item.Prompt != "Choose the number" || !item.Content.IsNumberItemContent() {
t.Fatalf("current item = %+v, %v", item, ok)
}
}
func TestCreateAssessmentAttemptMapsPersistedConflictAndRejectsGuest(t *testing.T) {
operations := &assessmentOperationsStub{create: outbound.AssessmentAttemptCreateResult{
Outcome: outbound.AssessmentAttemptCreateOutcome{StatusCode: 409, ProblemCode: "state_conflict"},
}}
handler := NewAssessmentHandler(operations)
request := api.NewAssessmentExpressAttemptCreateAssessmentAttemptCreate(api.AssessmentExpressAttemptCreate{
Kind: api.AssessmentExpressAttemptCreateKindDemoExpress,
})
response, err := handler.CreateMyAssessmentAttempt(principalForTest(uuid.New()), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "blocked"})
if err != nil {
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
}
if _, ok := response.(*api.CreateMyAssessmentAttemptConflict); !ok {
t.Fatalf("state conflict response = %T, want conflict", response)
}
if operations.createCommand.Kind != domain.AssessmentAttemptKindDemoExpress || operations.createCommand.Specialization != nil {
t.Fatalf("express command = %+v", operations.createCommand)
}
response, err = handler.CreateMyAssessmentAttempt(context.Background(), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "blocked"})
if err != nil {
t.Fatalf("guest CreateMyAssessmentAttempt() error = %v", err)
}
if _, ok := response.(*api.CreateMyAssessmentAttemptUnauthorized); !ok || operations.createCalls != 1 {
t.Fatalf("guest create response = %T, operations called %d", response, operations.createCalls)
}
}
func TestStartAndReadAssessmentAttemptUseVerifiedPrincipal(t *testing.T) {
userID := uuid.New()
snapshot := assessmentPublicSnapshot()
operations := &assessmentOperationsStub{
read: snapshot,
start: outbound.AssessmentAttemptSessionResult{Response: snapshot},
}
handler := NewAssessmentHandler(operations)
ctx := principalForTest(userID)
read, err := handler.GetMyAssessmentAttempt(ctx, api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()})
if err != nil {
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
}
if operations.readUserID != userID || operations.readAttemptID != snapshot.ID {
t.Fatalf("GetMyAttempt() IDs = %s/%s", operations.readUserID, operations.readAttemptID)
}
if _, ok := read.(*api.AssessmentAttemptHeaders); !ok {
t.Fatalf("read response = %T, want attempt headers", read)
}
started, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{
ExpectedVersion: api.AssessmentAttemptVersion(7),
}, api.StartMyAssessmentAttemptSessionParams{AttemptID: snapshot.ID.UUID(), IdempotencyKey: "session-key"})
if err != nil {
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
}
if operations.startCommand.ActorID != userID || operations.startCommand.AttemptID != snapshot.ID ||
operations.startCommand.ExpectedVersion != 7 || operations.startCommand.IdempotencyKey != "session-key" {
t.Fatalf("StartSession() command = %+v", operations.startCommand)
}
if _, ok := started.(*api.AssessmentAttemptHeaders); !ok {
t.Fatalf("start response = %T, want attempt headers", started)
}
}
func TestAssessmentAttemptFailuresMapWithoutExposingInternalErrors(t *testing.T) {
operations := &assessmentOperationsStub{startErr: assessmentusecase.ErrAttemptVersionConflict}
handler := NewAssessmentHandler(operations)
response, err := handler.StartMyAssessmentAttemptSession(principalForTest(uuid.New()),
&api.AssessmentAttemptSessionStart{ExpectedVersion: 3},
api.StartMyAssessmentAttemptSessionParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
if err != nil {
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
}
problem, ok := response.(*api.StartMyAssessmentAttemptSessionPreconditionFailed)
if !ok || api.Problem(*problem).Code != api.ProblemCodeVersionConflict {
t.Fatalf("version conflict response = %T %+v", response, response)
}
operations.readErr = assessmentusecase.ErrAttemptNotFound
read, err := handler.GetMyAssessmentAttempt(principalForTest(uuid.New()), api.GetMyAssessmentAttemptParams{AttemptID: uuid.New()})
if err != nil {
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
}
if _, ok := read.(*api.GetMyAssessmentAttemptNotFound); !ok {
t.Fatalf("missing attempt response = %T", read)
}
operations.createErr = &assessmentusecase.AttemptFieldError{Pointer: "/task_language", Reason: "is not available"}
create, err := handler.CreateMyAssessmentAttempt(principalForTest(uuid.New()), api.NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate(
api.AssessmentQualifiedAttemptCreate{Kind: api.AssessmentQualifiedAttemptCreateKindRoot, Specialization: "backend", TargetGrade: "junior"},
), api.CreateMyAssessmentAttemptParams{IdempotencyKey: "key"})
if err != nil {
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
}
badRequest, ok := create.(*api.CreateMyAssessmentAttemptBadRequest)
if !ok || len(api.Problem(*badRequest).Errors) != 1 || api.Problem(*badRequest).Errors[0].Pointer != "/task_language" {
t.Fatalf("validation response = %T %+v", create, create)
}
operations.startErr = errors.New("private database detail")
if _, err := handler.StartMyAssessmentAttemptSession(principalForTest(uuid.New()),
&api.AssessmentAttemptSessionStart{ExpectedVersion: 1},
api.StartMyAssessmentAttemptSessionParams{AttemptID: uuid.New(), IdempotencyKey: "key"}); err == nil || err.Error() != "private database detail" {
t.Fatalf("unexpected internal error mapping = %v", err)
}
}
func TestConfirmedAttemptResultDoesNotInferStoredGradeFromTarget(t *testing.T) {
result := assessmentusecase.AssessmentAttemptResult{
Attempt: domain.AssessmentAttemptPublicSnapshot{
Kind: domain.AssessmentAttemptKindRoot, TargetGrade: domainCodePointer(domain.GradeCode("junior")),
},
Outcome: domain.AssessmentAttemptOutcomeConfirmed,
}
fields, err := assessmentRealResultFields(result)
if err != nil {
t.Fatalf("assessmentRealResultFields() error = %v", err)
}
if !fields.confirmedGrade.IsNull() {
t.Fatalf("confirmed grade = %+v, want null until a stored grade decision exists", fields.confirmedGrade)
}
}
type assessmentOperationsStub struct {
availabilityCalls int
availabilityUserID uuid.UUID
availability assessmentusecase.AssessmentAvailability
availabilityErr error
createCalls int
createCommand assessmentusecase.CreateAttemptCommand
create outbound.AssessmentAttemptCreateResult
createErr error
read domain.AssessmentAttemptPublicSnapshot
readUserID uuid.UUID
readAttemptID domain.AssessmentAttemptID
readErr error
startCommand assessmentusecase.StartAttemptSessionCommand
start outbound.AssessmentAttemptSessionResult
startErr error
}
func (stub *assessmentOperationsStub) GetMyAssessmentAvailability(
_ context.Context,
userID uuid.UUID,
) (assessmentusecase.AssessmentAvailability, error) {
stub.availabilityCalls++
stub.availabilityUserID = userID
return stub.availability, stub.availabilityErr
}
func (stub *assessmentOperationsStub) CreateAttempt(_ context.Context, command assessmentusecase.CreateAttemptCommand) (outbound.AssessmentAttemptCreateResult, error) {
stub.createCalls++
stub.createCommand = command
return stub.create, stub.createErr
}
func (stub *assessmentOperationsStub) GetMyAttempt(_ context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptPublicSnapshot, error) {
stub.readUserID, stub.readAttemptID = userID, attemptID
return stub.read, stub.readErr
}
func (stub *assessmentOperationsStub) StartSession(_ context.Context, command assessmentusecase.StartAttemptSessionCommand) (outbound.AssessmentAttemptSessionResult, error) {
stub.startCommand = command
return stub.start, stub.startErr
}
func principalForTest(userID uuid.UUID) context.Context {
return context.WithValue(context.Background(), principalContextKey{}, Principal{UserID: userID, EmailVerified: true})
}
func assessmentPublicSnapshot() domain.AssessmentAttemptPublicSnapshot {
started := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
return domain.AssessmentAttemptPublicSnapshot{
ID: domain.AssessmentAttemptID(uuid.New()), Version: 7, Kind: domain.AssessmentAttemptKindRoot,
Mode: domain.AssessmentAttemptModeDemoBasic, State: domain.AssessmentAttemptStateInProgress,
Specialization: domainCodePointer(domain.SpecializationCode("backend")), TargetGrade: domainCodePointer(domain.GradeCode("junior")),
PolicyVersion: 2, BankVersion: "bank-v1", AlgorithmVersion: "assessment.v1", StartedAt: started,
ExpiresAt: started.Add(30 * time.Minute), MaxItems: 10, SessionsUsed: 1, MaxSessions: 2, IdleTimeout: 1800,
CurrentItem: &domain.AssessmentAttemptPublicItem{ID: uuid.New(), Sequence: 1, Prompt: "Choose the number",
Content: domain.AssessmentAttemptPublicItemContent{Format: "number"}}, Practices: []domain.AssessmentAttemptPublicPractice{},
}
}
func domainCodePointer[T ~string](value T) *T {
return &value
}
@@ -0,0 +1,643 @@
package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"math"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
needusecase "lincodex/backend/internal/usecase/need"
)
const (
needCursorVersion = 1
needCursorBytes = 61
defaultNeedLimit = 20
maxNeedCursorTime = uint64(253402300799)
)
// NeedOperations are the owner-scoped need reads and commands served by HTTP.
type NeedOperations interface {
Create(ctx context.Context, command needusecase.CreateCommand) (domain.NeedResponseSnapshot, error)
Get(ctx context.Context, actorID, organizationID, needID uuid.UUID) (domain.Need, error)
List(ctx context.Context, command needusecase.ListCommand) (outbound.NeedPage, error)
Update(ctx context.Context, command needusecase.UpdateCommand) (domain.Need, error)
}
// NeedHandler serves company need routes without trusting membership in a
// request body or retaining tenant data between requests.
type NeedHandler struct {
operations NeedOperations
}
func NewNeedHandler(operations NeedOperations) *NeedHandler {
if operations == nil {
panic("v1.NewNeedHandler - need operations must not be nil")
}
return &NeedHandler{operations: operations}
}
func (handler *Handler) ListOrganizationNeeds(ctx context.Context, params api.ListOrganizationNeedsParams) (api.ListOrganizationNeedsRes, error) {
if handler.need == nil {
return handler.UnimplementedHandler.ListOrganizationNeeds(ctx, params)
}
return handler.need.ListOrganizationNeeds(ctx, params)
}
func (handler *Handler) CreateOrganizationNeed(ctx context.Context, request *api.NeedCreate, params api.CreateOrganizationNeedParams) (api.CreateOrganizationNeedRes, error) {
if handler.need == nil {
return handler.UnimplementedHandler.CreateOrganizationNeed(ctx, request, params)
}
return handler.need.CreateOrganizationNeed(ctx, request, params)
}
func (handler *Handler) GetOrganizationNeed(ctx context.Context, params api.GetOrganizationNeedParams) (api.GetOrganizationNeedRes, error) {
if handler.need == nil {
return handler.UnimplementedHandler.GetOrganizationNeed(ctx, params)
}
return handler.need.GetOrganizationNeed(ctx, params)
}
func (handler *Handler) UpdateOrganizationNeed(ctx context.Context, request *api.NeedUpdate, params api.UpdateOrganizationNeedParams) (api.UpdateOrganizationNeedRes, error) {
if handler.need == nil {
return handler.UnimplementedHandler.UpdateOrganizationNeed(ctx, request, params)
}
return handler.need.UpdateOrganizationNeed(ctx, request, params)
}
func (handler *NeedHandler) CreateOrganizationNeed(
ctx context.Context,
request *api.NeedCreate,
params api.CreateOrganizationNeedParams,
) (api.CreateOrganizationNeedRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.CreateOrganizationNeedUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.CreateOrganizationNeedBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
canonical, err := json.Marshal(request)
if err != nil {
return nil, fmt.Errorf("NeedHandler.CreateOrganizationNeed - encode canonical request")
}
snapshot, err := handler.operations.Create(ctx, needusecase.CreateCommand{
ActorID: principal.UserID, OrganizationID: params.OrgID, IdempotencyKey: params.IdempotencyKey,
CanonicalBody: canonical, Input: createNeedInput(request),
})
if err != nil {
return needCreateFailure(ctx, err)
}
return &api.NeedHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: needResponse(snapshot)}, nil
}
func (handler *NeedHandler) GetOrganizationNeed(
ctx context.Context,
params api.GetOrganizationNeedParams,
) (api.GetOrganizationNeedRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetOrganizationNeedUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
need, err := handler.operations.Get(ctx, principal.UserID, params.OrgID, params.NeedID)
if err != nil {
return needReadFailure(ctx, err)
}
return &api.NeedHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: needResponse(need.ResponseSnapshot())}, nil
}
func (handler *NeedHandler) ListOrganizationNeeds(
ctx context.Context,
params api.ListOrganizationNeedsParams,
) (api.ListOrganizationNeedsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListOrganizationNeedsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, pointer := needListCommand(principal.UserID, params)
if pointer != "" {
return needListInvalid(ctx, pointer), nil
}
page, err := handler.operations.List(ctx, command)
if err != nil {
switch {
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified):
return (*api.ListOrganizationNeedsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.ListOrganizationNeedsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
items := make([]api.NeedSummary, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, needSummaryFromDomain(item))
}
next := api.NilString{}
next.SetToNull()
if page.HasMore && len(page.Items) > 0 {
cursor, err := encodeNeedCursor(principal.UserID, params.OrgID, outbound.NeedCreationPosition(page.Items[len(page.Items)-1]))
if err != nil {
return nil, fmt.Errorf("NeedHandler.ListOrganizationNeeds - encode cursor: %w", err)
}
next.SetTo(cursor)
}
return &api.NeedListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.NeedList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}
func (handler *NeedHandler) UpdateOrganizationNeed(
ctx context.Context,
request *api.NeedUpdate,
params api.UpdateOrganizationNeedParams,
) (api.UpdateOrganizationNeedRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.UpdateOrganizationNeedUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.UpdateOrganizationNeedBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
need, err := handler.operations.Update(ctx, needusecase.UpdateCommand{
ActorID: principal.UserID, OrganizationID: params.OrgID, NeedID: params.NeedID, Input: updateNeedInput(request),
})
if err != nil {
return needUpdateFailure(ctx, err)
}
return &api.NeedHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: needResponse(need.ResponseSnapshot())}, nil
}
func needCreateFailure(ctx context.Context, err error) (api.CreateOrganizationNeedRes, error) {
switch {
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.CreateOrganizationNeedForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.CreateOrganizationNeedNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, needusecase.ErrIdempotencyKeyReused):
return (*api.CreateOrganizationNeedUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, needusecase.ErrInvalidIdempotencyKey):
return (*api.CreateOrganizationNeedBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case errors.Is(err, needusecase.ErrInvalidRequest), errors.Is(err, domain.ErrInvalidNeed):
return (*api.CreateOrganizationNeedBadRequest)(needValidationProblem(ctx, err)), nil
default:
return nil, err
}
}
func needReadFailure(ctx context.Context, err error) (api.GetOrganizationNeedRes, error) {
switch {
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.GetOrganizationNeedForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrNeedNotFound):
return (*api.GetOrganizationNeedNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
func needUpdateFailure(ctx context.Context, err error) (api.UpdateOrganizationNeedRes, error) {
switch {
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.UpdateOrganizationNeedForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrNeedNotFound):
return (*api.UpdateOrganizationNeedNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, domain.ErrNeedVersionConflict), errors.Is(err, outbound.ErrNeedVersionConflict):
return (*api.UpdateOrganizationNeedPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, needusecase.ErrInvalidRequest), errors.Is(err, domain.ErrInvalidNeed):
return (*api.UpdateOrganizationNeedBadRequest)(needValidationProblem(ctx, err)), nil
default:
return nil, err
}
}
func needValidationProblem(ctx context.Context, err error) *api.Problem {
field, ok := errors.AsType[*needusecase.ValidationError](err)
if !ok {
return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response
}
return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer).Response
}
func needListInvalid(ctx context.Context, pointer string) *api.ListOrganizationNeedsBadRequest {
return (*api.ListOrganizationNeedsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response)
}
func needListCommand(actorID uuid.UUID, params api.ListOrganizationNeedsParams) (needusecase.ListCommand, string) {
limit, ok := params.Limit.Get()
if !ok {
limit = defaultNeedLimit
}
if limit < 1 || limit > outbound.MaxNeedPageSize {
return needusecase.ListCommand{}, "limit"
}
command := needusecase.ListCommand{ActorID: actorID, OrganizationID: params.OrgID, Limit: limit}
if cursor, ok := params.Cursor.Get(); ok {
position, err := decodeNeedCursor(cursor, actorID, params.OrgID)
if err != nil {
return needusecase.ListCommand{}, "cursor"
}
command.After = &position
}
return command, ""
}
func encodeNeedCursor(actorID, organizationID uuid.UUID, position outbound.NeedListPosition) (string, error) {
seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond()
if actorID == uuid.Nil || organizationID == uuid.Nil || position.NeedID == uuid.Nil || position.CreatedAt.IsZero() ||
position.CreatedAt.Year() < 1 || position.CreatedAt.Year() > 9999 || seconds < 0 || uint64(seconds) > maxNeedCursorTime ||
nanos < 0 || nanos >= 1_000_000_000 || nanos%int(time.Microsecond) != 0 {
return "", errors.New("need cursor requires an actor, organization, and valid page position")
}
var value [needCursorBytes]byte
value[0] = needCursorVersion
copy(value[1:17], actorID[:])
copy(value[17:33], organizationID[:])
binary.BigEndian.PutUint64(value[33:41], uint64(seconds))
binary.BigEndian.PutUint32(value[41:45], uint32(nanos))
copy(value[45:61], position.NeedID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodeNeedCursor(cursor string, actorID, organizationID uuid.UUID) (outbound.NeedListPosition, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != needCursorBytes || actorID == uuid.Nil || organizationID == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != needCursorVersion ||
uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != organizationID {
return outbound.NeedListPosition{}, errors.New("need cursor is invalid")
}
seconds := binary.BigEndian.Uint64(value[33:41])
nanos := binary.BigEndian.Uint32(value[41:45])
needID := uuid.UUID(value[45:61])
if seconds > uint64(math.MaxInt64) || seconds > maxNeedCursorTime || nanos >= 1_000_000_000 || nanos%1_000 != 0 || needID == uuid.Nil {
return outbound.NeedListPosition{}, errors.New("need cursor position is invalid")
}
createdAt := time.Unix(int64(seconds), int64(nanos)).UTC()
if createdAt.IsZero() {
return outbound.NeedListPosition{}, errors.New("need cursor timestamp is invalid")
}
return outbound.NeedListPosition{CreatedAt: createdAt, NeedID: needID}, nil
}
func createNeedInput(request *api.NeedCreate) needusecase.CreateInput {
input := needusecase.CreateInput{Title: string(request.Title)}
input.VacancyID = uuidField(request.VacancyID.Set, request.VacancyID.Null, request.VacancyID.Value)
input.SourceText = stringField(request.SourceText.Set, request.SourceText.Null, string(request.SourceText.Value))
input.Specialization = specializationInput(request.Specialization.Set, request.Specialization.Null, request.Specialization.Value)
input.Grade = gradeInput(request.Grade.Set, request.Grade.Null, request.Grade.Value)
input.Domain = domainInput(request.Domain.Set, request.Domain.Null, request.Domain.Value)
input.WorkFormats = workFormatsInput(request.WorkFormats.Set, request.WorkFormats.Null, request.WorkFormats.Value)
input.Location = locationInput(request.Location.Set, request.Location.Null, request.Location.Value)
input.Salary = salaryInput(request.Salary.Set, request.Salary.Null, request.Salary.Value)
input.RequiredSkills = skillInputs(request.RequiredSkills)
input.DesiredSkills = skillInputs(request.DesiredSkills)
input.Tasks = taskInputs(request.Tasks)
return input
}
func updateNeedInput(request *api.NeedUpdate) needusecase.UpdateInput {
input := needusecase.UpdateInput{ExpectedVersion: int64(request.ExpectedVersion)}
if request.Title.Set {
input.Title = needusecase.Field[string]{Set: true, Value: string(request.Title.Value)}
}
input.VacancyID = uuidField(request.VacancyID.Set, request.VacancyID.Null, request.VacancyID.Value)
input.SourceText = stringField(request.SourceText.Set, request.SourceText.Null, string(request.SourceText.Value))
input.Specialization = specializationInput(request.Specialization.Set, request.Specialization.Null, request.Specialization.Value)
input.Grade = gradeInput(request.Grade.Set, request.Grade.Null, request.Grade.Value)
input.Domain = domainInput(request.Domain.Set, request.Domain.Null, request.Domain.Value)
input.WorkFormats = workFormatsInput(request.WorkFormats.Set, request.WorkFormats.Null, request.WorkFormats.Value)
input.Location = locationInput(request.Location.Set, request.Location.Null, request.Location.Value)
input.Salary = salaryInput(request.Salary.Set, request.Salary.Null, request.Salary.Value)
input.RequiredSkills = skillInputs(request.RequiredSkills)
input.DesiredSkills = skillInputs(request.DesiredSkills)
input.Tasks = taskInputs(request.Tasks)
return input
}
func uuidField(set, null bool, value uuid.UUID) needusecase.Field[uuid.UUID] {
return needusecase.Field[uuid.UUID]{Set: set, Null: null, Value: value}
}
func stringField(set, null bool, value string) needusecase.Field[string] {
return needusecase.Field[string]{Set: set, Null: null, Value: value}
}
func specializationInput(set, null bool, value api.NeedSpecializationInput) needusecase.Field[needusecase.Decision[domain.SpecializationCode]] {
return needusecase.Field[needusecase.Decision[domain.SpecializationCode]]{
Set: set, Null: null, Value: needusecase.Decision[domain.SpecializationCode]{Value: domain.SpecializationCode(value.Value), Status: domain.NeedValueStatus(value.Status)},
}
}
func gradeInput(set, null bool, value api.NeedGradeInput) needusecase.Field[needusecase.Decision[domain.GradeCode]] {
return needusecase.Field[needusecase.Decision[domain.GradeCode]]{
Set: set, Null: null, Value: needusecase.Decision[domain.GradeCode]{Value: domain.GradeCode(value.Value), Status: domain.NeedValueStatus(value.Status)},
}
}
func domainInput(set, null bool, value api.NeedDomainInput) needusecase.Field[needusecase.Decision[string]] {
return needusecase.Field[needusecase.Decision[string]]{
Set: set, Null: null, Value: needusecase.Decision[string]{Value: string(value.Value), Status: domain.NeedValueStatus(value.Status)},
}
}
func workFormatsInput(set, null bool, value api.NeedWorkFormatsInput) needusecase.Field[needusecase.Decision[[]domain.NeedWorkFormat]] {
formats := make([]domain.NeedWorkFormat, 0, len(value.Value))
for _, format := range value.Value {
formats = append(formats, domain.NeedWorkFormat(format))
}
return needusecase.Field[needusecase.Decision[[]domain.NeedWorkFormat]]{
Set: set, Null: null, Value: needusecase.Decision[[]domain.NeedWorkFormat]{Value: formats, Status: domain.NeedValueStatus(value.Status)},
}
}
func locationInput(set, null bool, value api.NeedLocationInput) needusecase.Field[needusecase.Decision[string]] {
return needusecase.Field[needusecase.Decision[string]]{
Set: set, Null: null, Value: needusecase.Decision[string]{Value: string(value.Value), Status: domain.NeedValueStatus(value.Status)},
}
}
func salaryInput(set, null bool, value api.NeedSalaryInput) needusecase.Field[needusecase.Decision[domain.NeedSalaryRange]] {
rangeValue := domain.NeedSalaryRange{
SalaryFrom: int64(value.Value.SalaryFrom), SalaryTo: int64(value.Value.SalaryTo),
Currency: string(value.Value.Currency), Period: string(value.Value.Period), TaxBasis: string(value.Value.TaxBasis),
}
return needusecase.Field[needusecase.Decision[domain.NeedSalaryRange]]{
Set: set, Null: null, Value: needusecase.Decision[domain.NeedSalaryRange]{Value: rangeValue, Status: domain.NeedValueStatus(value.Status)},
}
}
func skillInputs(values []api.NeedSkillInput) []needusecase.SkillInput {
if values == nil {
return nil
}
result := make([]needusecase.SkillInput, 0, len(values))
for _, value := range values {
result = append(result, needusecase.SkillInput{Name: string(value.Name), Status: domain.NeedItemStatus(value.Status)})
}
return result
}
func taskInputs(values []api.NeedTaskInput) []needusecase.TaskInput {
if values == nil {
return nil
}
result := make([]needusecase.TaskInput, 0, len(values))
for _, value := range values {
result = append(result, needusecase.TaskInput{Text: string(value.Text), Status: domain.NeedItemStatus(value.Status)})
}
return result
}
func needResponse(snapshot domain.NeedResponseSnapshot) api.Need {
needSnapshot := snapshot.Need
return api.Need{
ID: needSnapshot.ID, OrganizationID: needSnapshot.OrganizationID,
VacancyID: needNullableUUID(needSnapshot.VacancyID), Title: api.NeedTitle(needSnapshot.Title),
SourceText: needNullableSourceText(needSnapshot.SourceText), Version: api.NeedVersion(needSnapshot.Version),
RequirementsVersion: api.NeedVersion(needSnapshot.RequirementsVersion),
Requirements: needRequirements(needSnapshot.Requirements), Readiness: needReadiness(snapshot.Readiness),
Recommendations: needRecommendations(snapshot.Recommendations),
CreatedAt: api.Timestamp(needSnapshot.CreatedAt), UpdatedAt: api.Timestamp(needSnapshot.UpdatedAt),
}
}
func needSummaryFromDomain(need domain.Need) api.NeedSummary {
snapshot := need.Snapshot()
return api.NeedSummary{
ID: snapshot.ID, VacancyID: needNullableUUID(snapshot.VacancyID), Title: api.NeedTitle(snapshot.Title),
Version: api.NeedVersion(snapshot.Version), Specialization: needSpecialization(snapshot.Requirements.Specialization),
Grade: needGrade(snapshot.Requirements.Grade), Readiness: needReadiness(need.Readiness()),
CreatedAt: api.Timestamp(snapshot.CreatedAt), UpdatedAt: api.Timestamp(snapshot.UpdatedAt),
}
}
func needRequirements(requirements domain.NeedRequirements) api.NeedRequirementSet {
return api.NeedRequirementSet{
Specialization: needSpecialization(requirements.Specialization), Grade: needGrade(requirements.Grade),
RequiredSkills: needSkills(requirements.RequiredSkills), DesiredSkills: needSkills(requirements.DesiredSkills),
Tasks: needTasks(requirements.Tasks), Domain: needDomain(requirements.Domain),
WorkFormats: needWorkFormats(requirements.WorkFormats), Location: needLocation(requirements.Location),
Salary: needSalary(requirements.Salary),
}
}
func needSpecialization(value domain.NeedValue[domain.SpecializationCode]) api.NeedSpecialization {
result := api.NeedSpecialization{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
if value.Value == nil {
result.Value.SetToNull()
} else {
result.Value.SetTo(api.SpecializationCode(*value.Value))
}
return result
}
func needGrade(value domain.NeedValue[domain.GradeCode]) api.NeedGrade {
result := api.NeedGrade{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
if value.Value == nil {
result.Value.SetToNull()
} else {
result.Value.SetTo(api.GradeCode(*value.Value))
}
return result
}
func needDomain(value domain.NeedValue[string]) api.NeedDomain {
result := api.NeedDomain{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
if value.Value == nil {
result.Value.SetToNull()
} else {
result.Value.SetTo(api.NeedDomainName(*value.Value))
}
return result
}
func needLocation(value domain.NeedValue[string]) api.NeedLocation {
result := api.NeedLocation{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
if value.Value == nil {
result.Value.SetToNull()
} else {
result.Value.SetTo(api.NeedLocationName(*value.Value))
}
return result
}
func needWorkFormats(value domain.NeedValue[[]domain.NeedWorkFormat]) api.NeedWorkFormats {
result := api.NeedWorkFormats{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
if value.Value == nil {
result.Value = nil
return result
}
result.Value = make([]api.WorkFormat, 0, len(*value.Value))
for _, format := range *value.Value {
result.Value = append(result.Value, api.WorkFormat(format))
}
return result
}
func needSalary(value domain.NeedValue[domain.NeedSalaryRange]) api.NeedSalary {
result := api.NeedSalary{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
if value.Value == nil {
result.Value.SetToNull()
return result
}
rangeValue := api.SalaryRange{
SalaryFrom: api.RubAmount(value.Value.SalaryFrom), SalaryTo: api.RubAmount(value.Value.SalaryTo),
Currency: api.CurrencyCode(value.Value.Currency), Period: api.SalaryPeriod(value.Value.Period),
TaxBasis: api.SalaryTaxBasis(value.Value.TaxBasis),
}
result.Value.SetTo(rangeValue)
return result
}
func needSkills(values []domain.NeedSkill) []api.NeedSkill {
result := make([]api.NeedSkill, 0, len(values))
for _, value := range values {
item := api.NeedSkill{Name: api.SkillName(value.Name), Status: api.NeedItemStatus(value.Status), Source: needValueSource(value.Source)}
if value.TaxonomyCode == nil {
item.TaxonomyCode.SetToNull()
} else {
item.TaxonomyCode.SetTo(api.SkillTaxonomyCode(*value.TaxonomyCode))
}
result = append(result, item)
}
return result
}
func needTasks(values []domain.NeedTask) []api.NeedTask {
result := make([]api.NeedTask, 0, len(values))
for _, value := range values {
result = append(result, api.NeedTask{Text: api.NeedTaskText(value.Text), Status: api.NeedItemStatus(value.Status), Source: needValueSource(value.Source)})
}
return result
}
func needReadiness(readiness domain.NeedReadinessReport) api.NeedReadinessReport {
missing := make([]api.NeedMissingField, 0, len(readiness.MissingFields))
for _, field := range readiness.MissingFields {
missing = append(missing, api.NeedMissingField{
Field: api.NeedFieldName(field.Field), Reason: api.NeedMissingReason(field.Reason), Question: field.Question,
})
}
return api.NeedReadinessReport{Status: api.NeedReadinessStatus(readiness.Status), MissingFields: missing}
}
func needRecommendations(recommendations domain.NeedCategoryRecommendations) api.NeedCategoryRecommendations {
result := api.NeedCategoryRecommendations{
Status: api.NeedRecommendationStatus(recommendations.Status),
RequirementsVersion: api.NeedVersion(recommendations.RequirementsVersion),
Categories: make([]api.NeedCategoryRecommendation, 0, len(recommendations.Categories)),
}
if recommendations.PolicyVersion == nil {
result.PolicyVersion.SetToNull()
} else {
result.PolicyVersion.SetTo(*recommendations.PolicyVersion)
}
if recommendations.AlgorithmVersion == nil {
result.AlgorithmVersion.SetToNull()
} else {
result.AlgorithmVersion.SetTo(api.NeedVersionLabel(*recommendations.AlgorithmVersion))
}
if recommendations.ComputedAt == nil {
result.ComputedAt.SetToNull()
} else {
result.ComputedAt.SetTo(api.Timestamp(*recommendations.ComputedAt))
}
for _, category := range recommendations.Categories {
result.Categories = append(result.Categories, needCategoryRecommendation(category))
}
return result
}
func needCategoryRecommendation(value domain.NeedCategoryRecommendation) api.NeedCategoryRecommendation {
result := api.NeedCategoryRecommendation{
Specialization: api.SpecializationCode(value.Specialization), Grade: api.GradeCode(value.Grade),
SkillOverlap: api.NeedSkillOverlap{Share: value.SkillOverlap.Share},
Money: api.NeedMoneyFit{Status: api.NeedMoneyStatus(value.Money.Status)}, Supply: api.NeedSupplyBand(value.Supply),
}
if value.Score == nil {
result.Score.SetToNull()
} else {
result.Score.SetTo(*value.Score)
}
if value.Money.Share == nil {
result.Money.Share.SetToNull()
} else {
result.Money.Share.SetTo(*value.Money.Share)
}
result.SkillOverlap.CoveredSkills = needSkillNames(value.SkillOverlap.CoveredSkills)
result.SkillOverlap.UncoveredSkills = needSkillNames(value.SkillOverlap.UncoveredSkills)
return result
}
func needSkillNames(values []string) []api.SkillName {
result := make([]api.SkillName, 0, len(values))
for _, value := range values {
result = append(result, api.SkillName(value))
}
return result
}
func needValueSource(value domain.NeedValueSource) api.NeedValueSource {
result := api.NeedValueSource{Origin: api.NeedValueOrigin(value.Origin)}
setNeedSourceOptionals(&result, value)
return result
}
func needNullableSource(value *domain.NeedValueSource) api.NilNeedValueSource {
var result api.NilNeedValueSource
if value == nil {
result.SetToNull()
return result
}
result.SetTo(needValueSource(*value))
return result
}
func setNeedSourceOptionals(result *api.NeedValueSource, value domain.NeedValueSource) {
if value.Quote == nil {
result.Quote.SetToNull()
} else {
result.Quote.SetTo(api.NeedSourceQuote(*value.Quote))
}
if value.ExtractedInVersion == nil {
result.ExtractedInVersion.SetToNull()
} else {
result.ExtractedInVersion.SetTo(api.NeedVersion(*value.ExtractedInVersion))
}
if value.ExtractionVersion == nil {
result.ExtractionVersion.SetToNull()
} else {
result.ExtractionVersion.SetTo(api.NeedVersionLabel(*value.ExtractionVersion))
}
}
func needNullableUUID(value *uuid.UUID) api.NilUUID {
var result api.NilUUID
if value == nil {
result.SetToNull()
} else {
result.SetTo(*value)
}
return result
}
func needNullableSourceText(value *string) api.NilNeedSourceText {
var result api.NilNeedSourceText
if value == nil {
result.SetToNull()
} else {
result.SetTo(api.NeedSourceText(*value))
}
return result
}
@@ -0,0 +1,126 @@
package v1
import (
"encoding/base64"
"encoding/binary"
"encoding/json"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestNeedCreateMappingPreservesAbsenceNullAndEmptyLists(t *testing.T) {
request := &api.NeedCreate{Title: api.NeedTitle("Payments backend"), RequiredSkills: []api.NeedSkillInput{}}
request.SourceText.SetTo(api.NeedSourceText("Requirements: Go"))
request.VacancyID.SetToNull()
input := createNeedInput(request)
if input.Title != "Payments backend" || !input.SourceText.Set || input.SourceText.Null || input.SourceText.Value != "Requirements: Go" {
t.Fatalf("create mapping lost title or source text: %+v", input)
}
if !input.VacancyID.Set || !input.VacancyID.Null {
t.Fatalf("explicit null vacancy mapped as %+v", input.VacancyID)
}
if input.Grade.Set || input.Specialization.Set || input.RequiredSkills == nil || len(input.RequiredSkills) != 0 || input.DesiredSkills != nil {
t.Fatalf("create mapping did not distinguish absent fields from an empty list: %+v", input)
}
}
func TestNeedUpdateMappingPreservesFieldPresenceAndListReplacement(t *testing.T) {
request := &api.NeedUpdate{ExpectedVersion: 4, RequiredSkills: []api.NeedSkillInput{}}
request.Title.SetTo(api.NeedTitle("Platform backend"))
request.SourceText.SetToNull()
input := updateNeedInput(request)
if input.ExpectedVersion != 4 || !input.Title.Set || input.Title.Null || input.Title.Value != "Platform backend" {
t.Fatalf("update mapping lost expected version or title: %+v", input)
}
if !input.SourceText.Set || !input.SourceText.Null || input.RequiredSkills == nil || len(input.RequiredSkills) != 0 || input.DesiredSkills != nil {
t.Fatalf("update mapping did not preserve null and list replacement: %+v", input)
}
}
func TestNeedResponseDoesNotExposePrivateSuppressionState(t *testing.T) {
createdAt := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
need, err := domain.NewNeed(domain.NeedSnapshot{
ID: uuid.Must(uuid.NewV7()), OrganizationID: uuid.Must(uuid.NewV7()), Title: "Payments backend",
Version: 1, RequirementsVersion: 1, Requirements: domain.EmptyNeedRequirements(),
RejectedSuggestions: []domain.NeedRejectedSuggestion{{Field: domain.NeedRejectedSkills, Value: "postgresql"}},
CreatedAt: createdAt, UpdatedAt: createdAt,
})
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
encoded, err := json.Marshal(needResponse(need.ResponseSnapshot()))
if err != nil {
t.Fatalf("marshal public need: %v", err)
}
if strings.Contains(string(encoded), "rejected_suggestions") || strings.Contains(string(encoded), "postgresql") {
t.Fatalf("public need exposed private suppression state: %s", encoded)
}
if !strings.Contains(string(encoded), `"recommendations":{"status":"not_available"`) {
t.Fatalf("need response did not report the unavailable calculator honestly: %s", encoded)
}
}
func TestNeedCursorIsBoundToActorAndOrganization(t *testing.T) {
actorID := uuid.Must(uuid.NewV7())
organizationID := uuid.Must(uuid.NewV7())
position := outbound.NeedListPosition{
CreatedAt: time.Date(2026, time.October, 7, 10, 0, 0, 123456000, time.UTC),
NeedID: uuid.Must(uuid.NewV7()),
}
cursor, err := encodeNeedCursor(actorID, organizationID, position)
if err != nil {
t.Fatalf("encodeNeedCursor() error = %v", err)
}
decoded, err := decodeNeedCursor(cursor, actorID, organizationID)
if err != nil || decoded.NeedID != position.NeedID || !decoded.CreatedAt.Equal(position.CreatedAt) {
t.Fatalf("decodeNeedCursor() = %+v, %v, want %+v", decoded, err, position)
}
if _, err := decodeNeedCursor(cursor, uuid.Must(uuid.NewV7()), organizationID); err == nil {
t.Fatal("decodeNeedCursor() accepted a cursor from another actor")
}
if _, err := decodeNeedCursor(cursor, actorID, uuid.Must(uuid.NewV7())); err == nil {
t.Fatal("decodeNeedCursor() accepted a cursor from another organization")
}
encoded, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
t.Fatalf("decode cursor bytes: %v", err)
}
encoded[33] = 0x80
invalidTimestamp := base64.RawURLEncoding.EncodeToString(encoded)
if _, err := decodeNeedCursor(invalidTimestamp, actorID, organizationID); err == nil {
t.Fatal("decodeNeedCursor() accepted an out-of-range timestamp")
}
encoded, err = base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
t.Fatalf("decode cursor bytes: %v", err)
}
binary.BigEndian.PutUint64(encoded[33:41], maxNeedCursorTime+1)
outsideDateTime := base64.RawURLEncoding.EncodeToString(encoded)
if _, err := decodeNeedCursor(outsideDateTime, actorID, organizationID); err == nil {
t.Fatal("decodeNeedCursor() accepted a timestamp outside the contract date-time range")
}
encoded, err = base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
t.Fatalf("decode cursor bytes: %v", err)
}
binary.BigEndian.PutUint32(encoded[41:45], 123456001)
subMicrosecond := base64.RawURLEncoding.EncodeToString(encoded)
if _, err := decodeNeedCursor(subMicrosecond, actorID, organizationID); err == nil {
t.Fatal("decodeNeedCursor() accepted precision that PostgreSQL cannot preserve")
}
if _, err := encodeNeedCursor(actorID, organizationID, outbound.NeedListPosition{
CreatedAt: time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC), NeedID: position.NeedID,
}); err == nil {
t.Fatal("encodeNeedCursor() accepted a timestamp outside the contract date-time range")
}
}
@@ -0,0 +1,657 @@
package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateprivacy"
"lincodex/backend/internal/usecase/candidateview"
)
const (
privacyCursorVersion = 1
privacyCursorBytes = 46
defaultPrivacyLimit = 20
privacyCursorEvents = 1
privacyCursorHidden = 2
privacyCursorAccess = 3
)
// CandidateViewOperations serves private previews, owner access history, and
// organization-scoped anonymous card reads.
type CandidateViewOperations interface {
GetOrganizationCard(ctx context.Context, actorID, organizationID uuid.UUID, handle string) (domain.AnonymousCandidateViewDTO, error)
GetMyCardPreview(ctx context.Context, actorID uuid.UUID) (candidateview.PreviewResult, error)
ListMyCardAccessHistory(ctx context.Context, query outbound.CandidateCardAccessListQuery) (outbound.CandidateCardAccessListPage, error)
}
// CandidatePrivacyOperations serves candidate-owned publication and privacy
// settings.
type CandidatePrivacyOperations interface {
GetMyPrivacySettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error)
SetMyPublication(ctx context.Context, userID uuid.UUID, expectedVersion int64, state domain.PublicationState, fields []domain.CardField) (domain.Publication, error)
SetMySearchStatus(ctx context.Context, userID uuid.UUID, expectedVersion int64, value domain.SearchStatusValue) (domain.SearchStatus, time.Time, error)
ListMyPrivacyHistory(ctx context.Context, query outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error)
ListMyHiddenOrganizations(ctx context.Context, query outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error)
HideOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error)
UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) error
}
// PrivacyHandler binds the privacy read and settings use cases to the v1 API.
type PrivacyHandler struct {
views CandidateViewOperations
settings CandidatePrivacyOperations
publicOrigin string
}
func NewPrivacyHandler(views CandidateViewOperations, settings CandidatePrivacyOperations, publicOrigin string) *PrivacyHandler {
if views == nil || settings == nil {
panic("v1.NewPrivacyHandler - view and settings operations must not be nil")
}
return &PrivacyHandler{views: views, settings: settings, publicOrigin: publicOrigin}
}
func (handler *Handler) GetMyCardPreview(ctx context.Context) (api.GetMyCardPreviewRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.GetMyCardPreview(ctx)
}
return handler.privacy.GetMyCardPreview(ctx)
}
func (handler *Handler) GetMyPrivacySettings(ctx context.Context) (api.GetMyPrivacySettingsRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.GetMyPrivacySettings(ctx)
}
return handler.privacy.GetMyPrivacySettings(ctx)
}
func (handler *Handler) GetOrganizationCandidateCard(ctx context.Context, params api.GetOrganizationCandidateCardParams) (api.GetOrganizationCandidateCardRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.GetOrganizationCandidateCard(ctx, params)
}
return handler.privacy.GetOrganizationCandidateCard(ctx, params)
}
func (handler *Handler) HideOrganization(ctx context.Context, params api.HideOrganizationParams) (api.HideOrganizationRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.HideOrganization(ctx, params)
}
return handler.privacy.HideOrganization(ctx, params)
}
func (handler *Handler) ListMyCardAccessHistory(ctx context.Context, params api.ListMyCardAccessHistoryParams) (api.ListMyCardAccessHistoryRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.ListMyCardAccessHistory(ctx, params)
}
return handler.privacy.ListMyCardAccessHistory(ctx, params)
}
func (handler *Handler) ListMyHiddenOrganizations(ctx context.Context, params api.ListMyHiddenOrganizationsParams) (api.ListMyHiddenOrganizationsRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.ListMyHiddenOrganizations(ctx, params)
}
return handler.privacy.ListMyHiddenOrganizations(ctx, params)
}
func (handler *Handler) ListMyPrivacyHistory(ctx context.Context, params api.ListMyPrivacyHistoryParams) (api.ListMyPrivacyHistoryRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.ListMyPrivacyHistory(ctx, params)
}
return handler.privacy.ListMyPrivacyHistory(ctx, params)
}
func (handler *Handler) SetMyPublication(ctx context.Context, request *api.PublicationUpdate) (api.SetMyPublicationRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.SetMyPublication(ctx, request)
}
return handler.privacy.SetMyPublication(ctx, request)
}
func (handler *Handler) SetMySearchStatus(ctx context.Context, request *api.SearchStatusUpdate) (api.SetMySearchStatusRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.SetMySearchStatus(ctx, request)
}
return handler.privacy.SetMySearchStatus(ctx, request)
}
func (handler *Handler) UnhideOrganization(ctx context.Context, params api.UnhideOrganizationParams) (api.UnhideOrganizationRes, error) {
if handler.privacy == nil {
return handler.UnimplementedHandler.UnhideOrganization(ctx, params)
}
return handler.privacy.UnhideOrganization(ctx, params)
}
func (handler *PrivacyHandler) GetMyCardPreview(ctx context.Context) (api.GetMyCardPreviewRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyCardPreviewUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
preview, err := handler.views.GetMyCardPreview(ctx, principal.UserID)
if err != nil {
if errors.Is(err, candidateview.ErrForbidden) {
return (*api.GetMyCardPreviewForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
return &api.CardPreviewHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: cardPreviewResponse(preview)}, nil
}
func (handler *PrivacyHandler) GetMyPrivacySettings(ctx context.Context) (api.GetMyPrivacySettingsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyPrivacySettingsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
settings, err := handler.settings.GetMyPrivacySettings(ctx, principal.UserID)
if err != nil {
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
return (*api.GetMyPrivacySettingsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
return &api.PrivacySettingsHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: privacySettingsResponse(settings)}, nil
}
func (handler *PrivacyHandler) GetOrganizationCandidateCard(ctx context.Context, params api.GetOrganizationCandidateCardParams) (api.GetOrganizationCandidateCardRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetOrganizationCandidateCardUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
view, err := handler.views.GetOrganizationCard(ctx, principal.UserID, params.OrgID, string(params.CandidateHandle))
if err != nil {
switch {
case errors.Is(err, candidateview.ErrForbidden):
return (*api.GetOrganizationCandidateCardForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, candidateview.ErrCandidateCardNotFound), errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.GetOrganizationCandidateCardNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, candidateview.ErrInvalidCandidateHandle):
return (*api.GetOrganizationCandidateCardBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationPath, "/candidate_handle").Response), nil
}
if limited, ok := candidateViewRateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
return &api.AnonymousCardContentHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: anonymousCardResponse(view)}, nil
}
func (handler *PrivacyHandler) ListMyCardAccessHistory(ctx context.Context, params api.ListMyCardAccessHistoryParams) (api.ListMyCardAccessHistoryRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyCardAccessHistoryUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorAccess)
if pointer != "" {
return (*api.ListMyCardAccessHistoryBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
var after *outbound.CandidateCardAccessPosition
if cursor != nil {
position := outbound.CandidateCardAccessPosition{OccurredAt: cursor.at, ID: cursor.id}
after = &position
}
page, err := handler.views.ListMyCardAccessHistory(ctx, outbound.CandidateCardAccessListQuery{CandidateID: principal.UserID, After: after, Limit: limit})
if err != nil {
if errors.Is(err, candidateview.ErrForbidden) || errors.Is(err, candidateprivacy.ErrForbidden) {
return (*api.ListMyCardAccessHistoryForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
items := make([]api.CardAccess, 0, len(page.Items))
for _, access := range page.Items {
organization := api.NilPrivacyOrganization{}
if name := page.OrganizationNames[access.OrganizationID()]; name != "" {
organization.SetTo(api.PrivacyOrganization{ID: access.OrganizationID(), Name: name})
} else {
organization.SetToNull()
}
items = append(items, api.CardAccess{
ID: access.ID(), Kind: api.CardAccessKind(access.Kind()), OccurredAt: api.Timestamp(access.OccurredAt()), Organization: organization,
})
}
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
last := page.Items[len(page.Items)-1]
return encodePrivacyCursor(principal.UserID, privacyCursorAccess, last.OccurredAt(), last.ID())
})
if err != nil {
return nil, fmt.Errorf("PrivacyHandler.ListMyCardAccessHistory - encode cursor: %w", err)
}
return &api.CardAccessListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.CardAccessList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}
func (handler *PrivacyHandler) ListMyHiddenOrganizations(ctx context.Context, params api.ListMyHiddenOrganizationsParams) (api.ListMyHiddenOrganizationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyHiddenOrganizationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorHidden)
if pointer != "" {
return (*api.ListMyHiddenOrganizationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
var after *outbound.HiddenOrganizationPosition
if cursor != nil {
position := outbound.HiddenOrganizationPosition{HiddenAt: cursor.at, OrganizationID: cursor.id}
after = &position
}
page, err := handler.settings.ListMyHiddenOrganizations(ctx, outbound.HiddenOrganizationListQuery{UserID: principal.UserID, After: after, Limit: limit})
if err != nil {
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
return (*api.ListMyHiddenOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
items := make([]api.HiddenOrganization, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, hiddenOrganizationResponse(item))
}
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
last := page.Items[len(page.Items)-1]
return encodePrivacyCursor(principal.UserID, privacyCursorHidden, last.HiddenAt, last.OrganizationID)
})
if err != nil {
return nil, fmt.Errorf("PrivacyHandler.ListMyHiddenOrganizations - encode cursor: %w", err)
}
return &api.HiddenOrganizationListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.HiddenOrganizationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}
func (handler *PrivacyHandler) ListMyPrivacyHistory(ctx context.Context, params api.ListMyPrivacyHistoryParams) (api.ListMyPrivacyHistoryRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyPrivacyHistoryUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorEvents)
if pointer != "" {
return (*api.ListMyPrivacyHistoryBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
var after *outbound.CandidatePrivacyEventPosition
if cursor != nil {
position := outbound.CandidatePrivacyEventPosition{OccurredAt: cursor.at, ID: cursor.id}
after = &position
}
page, err := handler.settings.ListMyPrivacyHistory(ctx, outbound.CandidatePrivacyEventListQuery{UserID: principal.UserID, After: after, Limit: limit})
if err != nil {
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
return (*api.ListMyPrivacyHistoryForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
items := make([]api.PrivacyEvent, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, privacyEventResponse(item))
}
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
last := page.Items[len(page.Items)-1]
return encodePrivacyCursor(principal.UserID, privacyCursorEvents, last.OccurredAt, last.ID)
})
if err != nil {
return nil, fmt.Errorf("PrivacyHandler.ListMyPrivacyHistory - encode cursor: %w", err)
}
return &api.PrivacyEventListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.PrivacyEventList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}
func (handler *PrivacyHandler) SetMyPublication(ctx context.Context, request *api.PublicationUpdate) (api.SetMyPublicationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SetMyPublicationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.SetMyPublicationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if request == nil {
return (*api.SetMyPublicationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
fields := make([]domain.CardField, 0, len(request.Fields))
for _, field := range request.Fields {
fields = append(fields, domain.CardField(field))
}
publication, err := handler.settings.SetMyPublication(ctx, principal.UserID, int64(request.ExpectedVersion), domain.PublicationState(request.State), fields)
if err != nil {
switch {
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
return (*api.SetMyPublicationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, domain.ErrVisibilityVersionConflict):
return (*api.SetMyPublicationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, domain.ErrPublicationConsentRequired):
return (*api.SetMyPublicationConflict)(privacyStateConflict(ctx, api.ProblemFieldLocationBody, "/state", "consent_required")), nil
case errors.Is(err, domain.ErrInvalidVisibility):
return (*api.SetMyPublicationBadRequest)(&privacyVisibilityInvalid(ctx, err).Response), nil
default:
return nil, err
}
}
return &api.PublicationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: publicationResponse(publication)}, nil
}
func (handler *PrivacyHandler) SetMySearchStatus(ctx context.Context, request *api.SearchStatusUpdate) (api.SetMySearchStatusRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SetMySearchStatusUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.SetMySearchStatusForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if request == nil {
return (*api.SetMySearchStatusBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
status, asOf, err := handler.settings.SetMySearchStatus(ctx, principal.UserID, int64(request.ExpectedVersion), domain.SearchStatusValue(request.Value))
if err != nil {
switch {
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
return (*api.SetMySearchStatusForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, domain.ErrVisibilityVersionConflict):
return (*api.SetMySearchStatusPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, domain.ErrInvalidVisibility):
return (*api.SetMySearchStatusBadRequest)(&privacyVisibilityInvalid(ctx, err).Response), nil
default:
return nil, err
}
}
return &api.SearchStatusHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: searchStatusResponse(status, asOf)}, nil
}
func (handler *PrivacyHandler) HideOrganization(ctx context.Context, params api.HideOrganizationParams) (api.HideOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.HideOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.HideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
hidden, err := handler.settings.HideOrganization(ctx, principal.UserID, params.OrgID)
if err != nil {
switch {
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
return (*api.HideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrCandidatePrivacyOrganizationNotVisible), errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.HideOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, outbound.ErrCandidateHiddenOrganizationLimit):
return (*api.HideOrganizationConflict)(privacyStateConflict(ctx, api.ProblemFieldLocationPath, "/org_id", "limit_reached")), nil
default:
return nil, err
}
}
return &api.HiddenOrganizationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: hiddenOrganizationResponse(hidden)}, nil
}
func (handler *PrivacyHandler) UnhideOrganization(ctx context.Context, params api.UnhideOrganizationParams) (api.UnhideOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.UnhideOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.UnhideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if err := handler.settings.UnhideOrganization(ctx, principal.UserID, params.OrgID); err != nil {
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
return (*api.UnhideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
return &api.UnhideOrganizationNoContent{CacheControl: api.CacheControlNoStoreNoStore}, nil
}
type privacyCursor struct {
at time.Time
id uuid.UUID
}
func privacyPageParams(limit api.OptInt32, cursor api.OptString, owner uuid.UUID, kind byte) (int32, *privacyCursor, string) {
pageLimit, set := limit.Get()
if !set {
pageLimit = defaultPrivacyLimit
}
if pageLimit < 1 || pageLimit > outbound.MaxPrivacyPageSize {
return 0, nil, "limit"
}
value, set := cursor.Get()
if !set {
return pageLimit, nil, ""
}
position, err := decodePrivacyCursor(value, owner, kind)
if err != nil {
return 0, nil, "cursor"
}
return pageLimit, &position, ""
}
func encodePrivacyCursor(owner uuid.UUID, kind byte, at time.Time, id uuid.UUID) (string, error) {
at = at.UTC()
seconds, nanos := at.Unix(), at.Nanosecond()
if owner == uuid.Nil || id == uuid.Nil || kind < privacyCursorEvents || kind > privacyCursorAccess || at.IsZero() ||
at.Year() < 1 || at.Year() > 9999 || nanos < 0 || nanos >= 1_000_000_000 || nanos%1_000 != 0 {
return "", errors.New("privacy cursor requires an owner and valid page position")
}
var value [privacyCursorBytes]byte
value[0], value[1] = privacyCursorVersion, kind
copy(value[2:18], owner[:])
writePrivacyCursorSeconds(value[18:26], seconds)
binary.BigEndian.PutUint32(value[26:30], uint32(nanos))
copy(value[30:46], id[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodePrivacyCursor(cursor string, owner uuid.UUID, kind byte) (privacyCursor, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != privacyCursorBytes || owner == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != privacyCursorVersion || value[1] != kind ||
uuid.UUID(value[2:18]) != owner {
return privacyCursor{}, errors.New("privacy cursor is invalid")
}
seconds := decodePrivacyCursorSeconds(value[18:26])
nanos := binary.BigEndian.Uint32(value[26:30])
id := uuid.UUID(value[30:46])
if nanos >= 1_000_000_000 || nanos%1_000 != 0 || id == uuid.Nil {
return privacyCursor{}, errors.New("privacy cursor position is invalid")
}
at := time.Unix(seconds, int64(nanos)).UTC()
if at.IsZero() || at.Year() < 1 || at.Year() > 9999 {
return privacyCursor{}, errors.New("privacy cursor timestamp is invalid")
}
return privacyCursor{at: at, id: id}, nil
}
func writePrivacyCursorSeconds(encoded []byte, seconds int64) {
encoded[0] = byte((seconds >> 56) & 0xff)
encoded[1] = byte((seconds >> 48) & 0xff)
encoded[2] = byte((seconds >> 40) & 0xff)
encoded[3] = byte((seconds >> 32) & 0xff)
encoded[4] = byte((seconds >> 24) & 0xff)
encoded[5] = byte((seconds >> 16) & 0xff)
encoded[6] = byte((seconds >> 8) & 0xff)
encoded[7] = byte(seconds & 0xff)
}
func decodePrivacyCursorSeconds(encoded []byte) int64 {
high := int64(binary.BigEndian.Uint32(encoded[:4]))
low := int64(binary.BigEndian.Uint32(encoded[4:]))
return high<<32 | low
}
func privacyNextCursor(hasMore bool, itemCount int, encode func() (string, error)) (api.NilString, error) {
var next api.NilString
next.SetToNull()
if !hasMore {
return next, nil
}
if itemCount == 0 {
return api.NilString{}, errors.New("privacy page has_more without items")
}
if hasMore {
cursor, err := encode()
if err != nil {
return api.NilString{}, err
}
next.SetTo(cursor)
}
return next, nil
}
func cardPreviewResponse(preview candidateview.PreviewResult) api.CardPreview {
state := api.PublicationStateClosed
if preview.Published {
state = api.PublicationStatePublished
}
fields := make(api.CardFieldSet, 0, len(preview.Fields.Fields()))
for _, field := range preview.Fields.Fields() {
fields = append(fields, api.CardField(field))
}
card := api.NilAnonymousCardContent{}
if preview.Card == nil {
card.SetToNull()
} else {
card.SetTo(anonymousCardResponse(*preview.Card))
}
return api.CardPreview{State: state, Fields: fields, Card: card, GeneratedAt: api.Timestamp(preview.GeneratedAt)}
}
func anonymousCardResponse(view domain.AnonymousCandidateViewDTO) api.AnonymousCardContent {
content := api.AnonymousCardContent{Pseudonym: view.Pseudonym}
for _, category := range view.Categories {
content.Categories = append(content.Categories, api.CardCategory{
Specialization: api.SpecializationCode(category.Specialization), Grade: api.GradeCode(category.Grade),
Strength: api.CardCategoryStrength(category.Strength),
})
}
for _, skill := range view.Skills {
content.Stack = append(content.Stack, api.AnonymousCardContentStackItem(skill))
}
for _, assessment := range view.SelfAssessment {
grade := api.OptNilGradeCode{}
if assessment.DeclaredGrade == nil {
grade.SetToNull()
} else {
grade.SetTo(api.GradeCode(*assessment.DeclaredGrade))
}
content.SelfAssessment = append(content.SelfAssessment, api.CardSelfAssessment{
Specialization: api.SpecializationCode(assessment.Specialization),
ConfirmationStatus: api.CardSelfAssessmentConfirmationStatus(assessment.ConfirmationStatus),
DeclaredGrade: grade,
})
}
content.ExperienceBand.SetToNull()
if view.ExperienceBand != nil {
content.ExperienceBand.SetTo(api.CandidateExperienceBand(*view.ExperienceBand))
}
for _, format := range view.WorkFormats {
content.WorkFormats = append(content.WorkFormats, api.CandidateWorkFormat(format))
}
content.SalaryCompatibility.SetToNull()
if view.SalaryCompatibility != nil {
content.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*view.SalaryCompatibility))
}
return content
}
func privacySettingsResponse(settings outbound.CandidatePrivacySettings) api.PrivacySettings {
return api.PrivacySettings{
Publication: publicationResponse(settings.Publication),
SearchStatus: searchStatusResponse(settings.SearchStatus, settings.AsOf),
HiddenOrganizationsTotal: int(settings.HiddenCount),
}
}
func publicationResponse(publication domain.Publication) api.Publication {
response := api.Publication{State: api.PublicationState(publication.State()), Version: api.PublicationVersion(publication.Version())}
response.ClosedReason.SetToNull()
if reason := publication.ClosedReason(); reason != "" {
response.ClosedReason.SetTo(api.PublicationClosedReason(reason))
}
response.ConsentID.SetToNull()
if consentID := publication.ConsentRecordID(); consentID != uuid.Nil {
response.ConsentID.SetTo(consentID)
}
response.PublishedAt.SetToNull()
if publishedAt := publication.PublishedAt(); !publishedAt.IsZero() {
response.PublishedAt.SetTo(api.Timestamp(publishedAt))
}
for _, field := range publication.Fields().Fields() {
response.Fields = append(response.Fields, api.CardField(field))
}
if response.Fields == nil {
response.Fields = api.CardFieldSet{}
}
return response
}
func searchStatusResponse(status domain.SearchStatus, asOf time.Time) api.SearchStatus {
response := api.SearchStatus{Value: api.SearchStatusValue(status.Effective(asOf)), Lapsed: status.Lapsed(asOf), Version: api.SearchStatusVersion(status.Version())}
response.ConfirmedAt.SetToNull()
if confirmedAt := status.ConfirmedAt(); !confirmedAt.IsZero() {
response.ConfirmedAt.SetTo(api.Timestamp(confirmedAt))
}
response.LapsesAt.SetToNull()
if lapsesAt := status.LapsesAt(); !lapsesAt.IsZero() {
response.LapsesAt.SetTo(api.Timestamp(lapsesAt))
}
return response
}
func privacyEventResponse(event outbound.CandidatePrivacyEventRecord) api.PrivacyEvent {
response := api.PrivacyEvent{ID: event.ID, Kind: api.PrivacyEventKind(event.Kind), OccurredAt: api.Timestamp(event.OccurredAt)}
if event.Fields == nil {
response.Fields = nil
} else {
response.Fields = make(api.CardFieldSet, 0, len(event.Fields.Fields()))
for _, field := range event.Fields.Fields() {
response.Fields = append(response.Fields, api.CardField(field))
}
}
response.ConsentID.SetToNull()
if event.ConsentRecordID != uuid.Nil {
response.ConsentID.SetTo(event.ConsentRecordID)
}
response.Organization.SetToNull()
if event.OrganizationID != uuid.Nil && event.OrganizationName != "" {
response.Organization.SetTo(api.PrivacyOrganization{ID: event.OrganizationID, Name: event.OrganizationName})
}
return response
}
func hiddenOrganizationResponse(hidden outbound.HiddenOrganizationRecord) api.HiddenOrganization {
return api.HiddenOrganization{
Organization: api.PrivacyOrganization{ID: hidden.OrganizationID, Name: hidden.OrganizationName},
HiddenAt: api.Timestamp(hidden.HiddenAt),
}
}
func privacyVisibilityInvalid(ctx context.Context, err error) *api.ProblemStatusCode {
field, ok := errors.AsType[*domain.VisibilityFieldError](err)
if !ok {
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
}
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer)
}
func privacyStateConflict(ctx context.Context, location api.ProblemFieldLocation, pointer, code string) *api.Problem {
response := problem.New(ctx, api.ProblemCodeStateConflict).Response
response.Errors = []api.ProblemFieldError{{
In: location, Pointer: pointer, Code: code,
Message: "The requested setting cannot be applied in the current state.",
}}
return &response
}
func candidateViewRateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) {
limited, ok := errors.AsType[*candidateview.RateLimitedError](err)
if !ok {
return nil, false
}
return problem.RateLimited(ctx, wholeSeconds(time.Until(limited.RetryAt))), true
}
@@ -0,0 +1,294 @@
package v1
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
)
func TestPrivacyGetOrganizationCandidateCardMapsClosedProjection(t *testing.T) {
userID, organizationID := uuid.New(), uuid.New()
view := domain.AnonymousCandidateViewDTO{
Pseudonym: "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
Categories: []domain.CandidateViewCategory{{
Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStrong,
}},
Skills: []domain.CandidateViewSkillCode{"go"},
SelfAssessment: []domain.CandidateViewSelfAssessment{{
Specialization: domain.SpecializationBackend, ConfirmationStatus: domain.CandidateViewConfirmationUnconfirmed,
}},
}
views := &privacyViewStub{card: view}
handler := NewPrivacyHandler(views, &privacySettingsStub{}, "https://app.example.test")
ctx := privacyHTTPContext(userID, "")
response, err := handler.GetOrganizationCandidateCard(ctx, api.GetOrganizationCandidateCardParams{
OrgID: organizationID, CandidateHandle: api.CandidateHandle(view.Pseudonym),
})
if err != nil {
t.Fatalf("GetOrganizationCandidateCard() error = %v", err)
}
body, ok := response.(*api.AnonymousCardContentHeaders)
if !ok {
t.Fatalf("GetOrganizationCandidateCard() response = %T, want AnonymousCardContentHeaders", response)
}
if body.CacheControl != api.CacheControlNoStoreNoStore || body.Response.Pseudonym != view.Pseudonym ||
len(body.Response.Categories) != 1 || body.Response.Categories[0].Strength != api.CardCategoryStrengthStrong ||
len(body.Response.Stack) != 1 || body.Response.Stack[0] != "go" ||
len(body.Response.SelfAssessment) != 1 || body.Response.SelfAssessment[0].ConfirmationStatus != api.CardSelfAssessmentConfirmationStatusUnconfirmed {
t.Fatalf("anonymous content mapping = %+v", body)
}
if views.actorID != userID || views.organizationID != organizationID || views.handle != view.Pseudonym {
t.Fatalf("read scope = actor %s organization %s handle %q", views.actorID, views.organizationID, views.handle)
}
if strings.Contains(view.String(), userID.String()) {
t.Fatal("anonymous view string exposed the internal account ID")
}
views.err = &candidateview.RateLimitedError{RetryAt: time.Now().Add(2 * time.Second)}
limited, err := handler.GetOrganizationCandidateCard(ctx, api.GetOrganizationCandidateCardParams{
OrgID: organizationID, CandidateHandle: api.CandidateHandle(view.Pseudonym),
})
if err != nil {
t.Fatalf("rate-limited GetOrganizationCandidateCard() error = %v", err)
}
limitedBody, ok := limited.(*api.TooManyRequestsHeaders)
if !ok || !limitedBody.RetryAfter.IsSet() || limitedBody.RetryAfter.Value < 1 {
t.Fatalf("rate-limit response = %#v, want 429 and Retry-After", limited)
}
}
func TestPrivacyPublicationMapsConsentConflictAndVersionErrors(t *testing.T) {
userID := uuid.New()
settings := &privacySettingsStub{publicationErr: domain.ErrPublicationConsentRequired}
handler := NewPrivacyHandler(&privacyViewStub{}, settings, "https://app.example.test")
ctx := privacyHTTPContext(userID, "https://app.example.test")
request := &api.PublicationUpdate{ExpectedVersion: 0, State: api.PublicationStatePublished, Fields: []api.CardField{api.CardFieldStack}}
response, err := handler.SetMyPublication(ctx, request)
if err != nil {
t.Fatalf("SetMyPublication() error = %v", err)
}
conflict, ok := response.(*api.SetMyPublicationConflict)
if !ok || conflict.Code != api.ProblemCodeStateConflict || len(conflict.Errors) != 1 ||
conflict.Errors[0].Pointer != "/state" || conflict.Errors[0].Code != "consent_required" {
t.Fatalf("publication consent response = %#v, want a scoped consent_required conflict", response)
}
if settings.userID != userID || settings.publicationExpectedVersion != 0 || settings.publicationState != domain.PublicationPublished ||
len(settings.publicationFields) != 1 || settings.publicationFields[0] != domain.CardFieldStack {
t.Fatalf("publication command = actor %s version %d state %q fields %v", settings.userID, settings.publicationExpectedVersion, settings.publicationState, settings.publicationFields)
}
settings.publicationErr = domain.ErrVisibilityVersionConflict
response, err = handler.SetMyPublication(ctx, request)
if err != nil {
t.Fatalf("stale SetMyPublication() error = %v", err)
}
precondition, ok := response.(*api.SetMyPublicationPreconditionFailed)
if !ok || precondition.Code != api.ProblemCodeVersionConflict {
t.Fatalf("publication version response = %#v, want 412 version_conflict", response)
}
}
func TestPrivacyListsRejectForeignAndMalformedCursorsBeforeRead(t *testing.T) {
ownerID := uuid.New()
views := &privacyViewStub{}
handler := NewPrivacyHandler(views, &privacySettingsStub{}, "https://app.example.test")
ctx := privacyHTTPContext(ownerID, "")
encoded, err := encodePrivacyCursor(ownerID, privacyCursorAccess, time.Date(2026, 10, 7, 12, 0, 0, 123000, time.UTC), uuid.New())
if err != nil {
t.Fatalf("encodePrivacyCursor() error = %v", err)
}
if _, err := decodePrivacyCursor(encoded, uuid.New(), privacyCursorAccess); err == nil {
t.Fatal("decodePrivacyCursor() accepted a cursor belonging to another owner")
}
if _, err := decodePrivacyCursor(encoded, ownerID, privacyCursorEvents); err == nil {
t.Fatal("decodePrivacyCursor() accepted a cursor from another listing")
}
response, err := handler.ListMyCardAccessHistory(ctx, api.ListMyCardAccessHistoryParams{Cursor: api.NewOptString("malformed")})
if err != nil {
t.Fatalf("invalid-cursor list error = %v", err)
}
badCursor, ok := response.(*api.ListMyCardAccessHistoryBadRequest)
if !ok || badCursor.Code != api.ProblemCodeValidationFailed || views.accessCalls != 0 {
t.Fatalf("invalid cursor response = %#v, read calls = %d", response, views.accessCalls)
}
}
func TestPrivacyCursorRoundTripsSignedTimestampBoundaries(t *testing.T) {
ownerID := uuid.MustParse("00112233-4455-6677-8899-aabbccddeeff")
recordID := uuid.MustParse("ffeeddcc-bbaa-9988-7766-554433221100")
times := map[string]time.Time{
"current positive time": time.Date(2026, 10, 7, 12, 34, 56, 123456000, time.UTC),
"before unix epoch": time.Unix(-1, 123456000).UTC(),
"end of year 9999": time.Date(9999, 12, 31, 23, 59, 59, 999999000, time.UTC),
}
for name, want := range times {
t.Run(name, func(t *testing.T) {
cursor, err := encodePrivacyCursor(ownerID, privacyCursorAccess, want, recordID)
if err != nil {
t.Fatalf("encodePrivacyCursor() error = %v", err)
}
got, err := decodePrivacyCursor(cursor, ownerID, privacyCursorAccess)
if err != nil {
t.Fatalf("decodePrivacyCursor() error = %v", err)
}
if !got.at.Equal(want) || got.id != recordID {
t.Fatalf("decoded cursor = (%s, %s), want (%s, %s)", got.at, got.id, want, recordID)
}
})
}
}
func TestPrivacyCursorAcceptsExistingVersionOneToken(t *testing.T) {
const legacyCursor = "AQMAESIzRFVmd4iZqrvM3e7___________8HW8oA_-7dzLuqmYh3ZlVEMyIRAA"
ownerID := uuid.MustParse("00112233-4455-6677-8899-aabbccddeeff")
wantID := uuid.MustParse("ffeeddcc-bbaa-9988-7766-554433221100")
wantTime := time.Unix(-1, 123456000).UTC()
got, err := decodePrivacyCursor(legacyCursor, ownerID, privacyCursorAccess)
if err != nil {
t.Fatalf("decodePrivacyCursor(existing token) error = %v", err)
}
if !got.at.Equal(wantTime) || got.id != wantID {
t.Fatalf("decoded legacy cursor = (%s, %s), want (%s, %s)", got.at, got.id, wantTime, wantID)
}
}
func TestPrivacyWriteRejectsOriginBeforeCallingSettings(t *testing.T) {
userID := uuid.New()
settings := &privacySettingsStub{}
handler := NewPrivacyHandler(&privacyViewStub{}, settings, "https://app.example.test")
request := &api.SearchStatusUpdate{ExpectedVersion: 0, Value: api.SearchStatusValueLooking}
response, err := handler.SetMySearchStatus(privacyHTTPContext(userID, "https://attacker.example.test"), request)
if err != nil {
t.Fatalf("SetMySearchStatus() error = %v", err)
}
forbidden, ok := response.(*api.SetMySearchStatusForbidden)
if !ok || forbidden.Code != api.ProblemCodeCsrfCheckFailed || settings.searchCalls != 0 {
t.Fatalf("cross-origin response = %#v, search calls = %d", response, settings.searchCalls)
}
}
func TestPrivacyMappingKeepsNullAndEmptyPublicationFieldsDistinct(t *testing.T) {
userID := uuid.New()
closed, err := domain.NewPublication(userID)
if err != nil {
t.Fatalf("NewPublication() error = %v", err)
}
response := publicationResponse(closed)
if response.State != api.PublicationStateClosed || response.Version != 0 || response.ClosedReason.IsNull() ||
response.ClosedReason.Value != api.PublicationClosedReasonNeverPublished || response.Fields == nil || len(response.Fields) != 0 ||
!response.ConsentID.IsNull() || !response.PublishedAt.IsNull() {
t.Fatalf("closed publication response = %+v", response)
}
search, err := domain.NewSearchStatus(userID)
if err != nil {
t.Fatalf("NewSearchStatus() error = %v", err)
}
searchResponse := searchStatusResponse(search, time.Now())
if searchResponse.Value != api.SearchStatusValueNotLooking || searchResponse.Lapsed || !searchResponse.ConfirmedAt.IsNull() || !searchResponse.LapsesAt.IsNull() {
t.Fatalf("initial search status response = %+v", searchResponse)
}
}
func privacyHTTPContext(userID uuid.UUID, origin string) context.Context {
request := httptest.NewRequest(http.MethodGet, "https://app.example.test/", nil)
if origin != "" {
request.Header.Set("Origin", origin)
}
capture := &privacyRequestContextCapture{}
httpmiddleware.SessionRequestMetadata()(capture).ServeHTTP(httptest.NewRecorder(), request)
return context.WithValue(capture.context, principalContextKey{}, Principal{UserID: userID, EmailVerified: true})
}
type privacyRequestContextCapture struct{ context context.Context }
func (capture *privacyRequestContextCapture) ServeHTTP(_ http.ResponseWriter, request *http.Request) {
// The middleware supplies the request context that carries origin metadata.
capture.context = request.Context()
}
type privacyViewStub struct {
card domain.AnonymousCandidateViewDTO
preview candidateview.PreviewResult
access outbound.CandidateCardAccessListPage
err error
actorID uuid.UUID
organizationID uuid.UUID
handle string
accessCalls int
}
func (stub *privacyViewStub) GetOrganizationCard(_ context.Context, actorID, organizationID uuid.UUID, handle string) (domain.AnonymousCandidateViewDTO, error) {
stub.actorID, stub.organizationID, stub.handle = actorID, organizationID, handle
return stub.card, stub.err
}
func (stub *privacyViewStub) GetMyCardPreview(context.Context, uuid.UUID) (candidateview.PreviewResult, error) {
return stub.preview, stub.err
}
func (stub *privacyViewStub) ListMyCardAccessHistory(context.Context, outbound.CandidateCardAccessListQuery) (outbound.CandidateCardAccessListPage, error) {
stub.accessCalls++
return stub.access, stub.err
}
type privacySettingsStub struct {
settings outbound.CandidatePrivacySettings
publication domain.Publication
publicationErr error
userID uuid.UUID
publicationExpectedVersion int64
publicationState domain.PublicationState
publicationFields []domain.CardField
searchCalls int
err error
}
func (stub *privacySettingsStub) GetMyPrivacySettings(context.Context, uuid.UUID) (outbound.CandidatePrivacySettings, error) {
return stub.settings, stub.err
}
func (stub *privacySettingsStub) SetMyPublication(_ context.Context, userID uuid.UUID, expectedVersion int64, state domain.PublicationState, fields []domain.CardField) (domain.Publication, error) {
stub.userID = userID
stub.publicationExpectedVersion, stub.publicationState = expectedVersion, state
stub.publicationFields = append([]domain.CardField(nil), fields...)
return stub.publication, stub.publicationErr
}
func (stub *privacySettingsStub) SetMySearchStatus(context.Context, uuid.UUID, int64, domain.SearchStatusValue) (domain.SearchStatus, time.Time, error) {
stub.searchCalls++
return domain.SearchStatus{}, time.Time{}, stub.err
}
func (stub *privacySettingsStub) ListMyPrivacyHistory(context.Context, outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error) {
return outbound.CandidatePrivacyEventPage{}, stub.err
}
func (stub *privacySettingsStub) ListMyHiddenOrganizations(context.Context, outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error) {
return outbound.HiddenOrganizationPage{}, stub.err
}
func (stub *privacySettingsStub) HideOrganization(context.Context, uuid.UUID, uuid.UUID) (outbound.HiddenOrganizationRecord, error) {
return outbound.HiddenOrganizationRecord{}, stub.err
}
func (stub *privacySettingsStub) UnhideOrganization(context.Context, uuid.UUID, uuid.UUID) error {
return stub.err
}
@@ -0,0 +1,489 @@
package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
supportcase "lincodex/backend/internal/usecase/supportcase"
)
const (
supportCaseCursorVersion = 1
supportCaseCursorBytes = 45
defaultSupportCaseLimit = 20
maxSupportCaseCursorUnixSeconds = uint64(253_402_300_799)
)
// SupportOperations serves owner-scoped support-case creation and reads.
type SupportOperations interface {
Create(ctx context.Context, command supportcase.CreateCommand) (supportcase.CreateResult, error)
GetMyCase(ctx context.Context, ownerID uuid.UUID, id domain.SupportCaseID) (domain.SupportCase, error)
ListMyCases(ctx context.Context, command supportcase.ListCommand) (outbound.SupportCaseListPage, error)
}
// SupportHandler serves support-case operations without accepting an owner
// identity from the request body or path.
type SupportHandler struct {
operations SupportOperations
now func() time.Time
}
func NewSupportHandler(operations SupportOperations) *SupportHandler {
if operations == nil {
panic("v1.NewSupportHandler - support operations must not be nil")
}
return &SupportHandler{operations: operations, now: time.Now}
}
func (handler *Handler) CreateMySupportCase(
ctx context.Context,
request api.SupportCaseCreate,
params api.CreateMySupportCaseParams,
) (api.CreateMySupportCaseRes, error) {
if handler.support == nil {
return handler.UnimplementedHandler.CreateMySupportCase(ctx, request, params)
}
return handler.support.CreateMySupportCase(ctx, request, params)
}
func (handler *Handler) GetMySupportCase(
ctx context.Context,
params api.GetMySupportCaseParams,
) (api.GetMySupportCaseRes, error) {
if handler.support == nil {
return handler.UnimplementedHandler.GetMySupportCase(ctx, params)
}
return handler.support.GetMySupportCase(ctx, params)
}
func (handler *Handler) ListMySupportCases(
ctx context.Context,
params api.ListMySupportCasesParams,
) (api.ListMySupportCasesRes, error) {
if handler.support == nil {
return handler.UnimplementedHandler.ListMySupportCases(ctx, params)
}
return handler.support.ListMySupportCases(ctx, params)
}
func (handler *SupportHandler) CreateMySupportCase(
ctx context.Context,
request api.SupportCaseCreate,
params api.CreateMySupportCaseParams,
) (api.CreateMySupportCaseRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.CreateMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
canonicalBody, err := json.Marshal(request)
if err != nil {
return nil, fmt.Errorf("SupportHandler.CreateMySupportCase - encode canonical request")
}
command, valid := supportCaseCreateCommand(request)
if !valid {
return (*api.CreateMySupportCaseBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
command.ActorID = principal.UserID
command.IdempotencyKey = params.IdempotencyKey
command.CanonicalBody = canonicalBody
result, err := handler.operations.Create(ctx, command)
if err != nil {
return supportCaseCreateFailure(ctx, err)
}
response, err := supportCaseResponse(result.Case, result.TargetLate)
if err != nil {
return nil, fmt.Errorf("SupportHandler.CreateMySupportCase - map case: %w", err)
}
return &api.SupportCaseHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: response,
}, nil
}
func (handler *SupportHandler) GetMySupportCase(
ctx context.Context,
params api.GetMySupportCaseParams,
) (api.GetMySupportCaseRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
supportCase, err := handler.operations.GetMyCase(ctx, principal.UserID, domain.SupportCaseID(params.CaseID))
if err != nil {
return supportCaseReadFailure(ctx, err)
}
late := supportCase.ResponseTarget().IsLate(handler.now().UTC())
response, err := supportCaseResponse(supportCase, late)
if err != nil {
return nil, fmt.Errorf("SupportHandler.GetMySupportCase - map case: %w", err)
}
return &api.SupportCaseHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: response,
}, nil
}
func (handler *SupportHandler) ListMySupportCases(
ctx context.Context,
params api.ListMySupportCasesParams,
) (api.ListMySupportCasesRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMySupportCasesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, pointer := supportCaseListCommand(principal.UserID, params)
if pointer != "" {
return supportCaseListInvalid(ctx, pointer), nil
}
page, err := handler.operations.ListMyCases(ctx, command)
if err != nil {
switch {
case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified),
errors.Is(err, outbound.ErrUserNotFound):
return (*api.ListMySupportCasesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
default:
return nil, err
}
}
items := make([]api.SupportCaseSummary, 0, len(page.Items))
for _, item := range page.Items {
late := supportResponseTargetLate(item.ResponseTarget, handler.now().UTC())
summary, err := supportCaseSummaryResponse(item, late)
if err != nil {
return nil, fmt.Errorf("SupportHandler.ListMySupportCases - map summary: %w", err)
}
items = append(items, summary)
}
next := api.NilString{}
next.SetToNull()
if page.HasMore && len(page.Items) > 0 {
cursor, err := encodeSupportCaseCursor(principal.UserID, outbound.SupportCasePositionOf(page.Items[len(page.Items)-1]))
if err != nil {
return nil, fmt.Errorf("SupportHandler.ListMySupportCases - encode cursor: %w", err)
}
next.SetTo(cursor)
}
return &api.SupportCaseListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.SupportCaseList{
Items: items,
Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next},
},
}, nil
}
func supportCaseCreateCommand(request api.SupportCaseCreate) (supportcase.CreateCommand, bool) {
var command supportcase.CreateCommand
switch request.Type {
case api.SupportCaseCreateSupportSupportCaseCreate:
value := request.SupportCaseCreateSupport
command.Type = domain.SupportCaseTypeSupport
command.Description = string(value.Description)
if object, ok := value.Object.Get(); ok {
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(object.Type), ID: object.ID}
}
if target, ok := value.AssessmentTarget.Get(); ok {
command.AssessmentTarget = &domain.SupportCaseAssessmentTarget{
Specialization: domain.SpecializationCode(target.Specialization), Grade: domain.GradeCode(target.Grade),
}
}
case api.SupportCaseCreateComplaintSupportCaseCreate:
value := request.SupportCaseCreateComplaint
command.Type = domain.SupportCaseTypeComplaint
command.Description = string(value.Description)
command.ComplaintReason = supportComplaintReasonPointer(domain.SupportCaseComplaintReason(value.ComplaintReason))
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID}
case api.SupportCaseCreateGradeAppealSupportCaseCreate:
value := request.SupportCaseCreateGradeAppeal
command.Type = domain.SupportCaseTypeGradeAppeal
command.Description = string(value.Description)
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID}
case api.SupportCaseCreateAnticheatAppealSupportCaseCreate:
value := request.SupportCaseCreateAnticheatAppeal
command.Type = domain.SupportCaseTypeAnticheatAppeal
command.Description = string(value.Description)
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID}
case api.SupportCaseCreateManualAssessmentSupportCaseCreate:
value := request.SupportCaseCreateManualAssessment
command.Type = domain.SupportCaseTypeManualAssessment
command.Description = string(value.Description)
command.AssessmentTarget = &domain.SupportCaseAssessmentTarget{
Specialization: domain.SpecializationCode(value.AssessmentTarget.Specialization),
Grade: domain.GradeCode(value.AssessmentTarget.Grade),
}
if object, ok := value.Object.Get(); ok {
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(object.Type), ID: object.ID}
}
default:
return supportcase.CreateCommand{}, false
}
return command, true
}
func supportCaseCreateFailure(ctx context.Context, err error) (api.CreateMySupportCaseRes, error) {
switch {
case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified):
return (*api.CreateMySupportCaseForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrUserNotFound):
return (*api.CreateMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
case errors.Is(err, outbound.ErrSupportCaseNotFound):
return (*api.CreateMySupportCaseNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, supportcase.ErrStateConflict), errors.Is(err, outbound.ErrSupportCaseConflict):
return (*api.CreateMySupportCaseConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case errors.Is(err, supportcase.ErrIdempotencyKeyReused):
return (*api.CreateMySupportCaseUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, supportcase.ErrInvalidIdempotencyKey):
return (*api.CreateMySupportCaseBadRequest)(
&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response,
), nil
case errors.Is(err, supportcase.ErrRateLimited):
limited, ok := errors.AsType[*supportcase.RateLimitedError](err)
if !ok || limited == nil {
return nil, errors.New("SupportHandler.CreateMySupportCase - rate limit error has no retry interval")
}
return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), nil
case errors.Is(err, supportcase.ErrInvalidCreateRequest), errors.Is(err, domain.ErrInvalidSupportCase):
fieldError, ok := errors.AsType[*domain.SupportCaseFieldError](err)
if !ok {
return (*api.CreateMySupportCaseBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
return (*api.CreateMySupportCaseBadRequest)(
&problem.InvalidField(ctx, api.ProblemFieldLocationBody, fieldError.Pointer).Response,
), nil
default:
return nil, err
}
}
func supportCaseReadFailure(ctx context.Context, err error) (api.GetMySupportCaseRes, error) {
switch {
case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified),
errors.Is(err, outbound.ErrUserNotFound):
return (*api.GetMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
case errors.Is(err, outbound.ErrSupportCaseNotFound):
return (*api.GetMySupportCaseNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
func supportCaseListCommand(actorID uuid.UUID, params api.ListMySupportCasesParams) (supportcase.ListCommand, string) {
limit, ok := params.Limit.Get()
if !ok {
limit = defaultSupportCaseLimit
}
if limit < 1 || limit > outbound.MaxSupportCasePageSize {
return supportcase.ListCommand{}, "limit"
}
command := supportcase.ListCommand{ActorID: actorID, Limit: limit}
if cursor, ok := params.Cursor.Get(); ok {
position, err := decodeSupportCaseCursor(cursor, actorID)
if err != nil {
return supportcase.ListCommand{}, "cursor"
}
command.After = &position
}
return command, ""
}
func supportCaseListInvalid(ctx context.Context, pointer string) *api.ListMySupportCasesBadRequest {
return (*api.ListMySupportCasesBadRequest)(
&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response,
)
}
func encodeSupportCaseCursor(actorID uuid.UUID, position outbound.SupportCaseListPosition) (string, error) {
seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond()
if actorID == uuid.Nil || position.ID.IsZero() || !validSupportCaseCursorTime(position.CreatedAt) ||
seconds < 0 || nanos < 0 || nanos >= 1_000_000_000 {
return "", errors.New("support case cursor requires an actor and a valid position")
}
var value [supportCaseCursorBytes]byte
value[0] = supportCaseCursorVersion
copy(value[1:17], actorID[:])
binary.BigEndian.PutUint64(value[17:25], uint64(seconds))
binary.BigEndian.PutUint32(value[25:29], uint32(nanos))
caseID := position.ID.UUID()
copy(value[29:45], caseID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodeSupportCaseCursor(cursor string, actorID uuid.UUID) (outbound.SupportCaseListPosition, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != supportCaseCursorBytes || actorID == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != supportCaseCursorVersion ||
uuid.UUID(value[1:17]) != actorID {
return outbound.SupportCaseListPosition{}, errors.New("support case cursor is invalid")
}
nanos := binary.BigEndian.Uint32(value[25:29])
caseID := uuid.UUID(value[29:45])
seconds := binary.BigEndian.Uint64(value[17:25])
if nanos >= 1_000_000_000 || caseID == uuid.Nil || seconds > maxSupportCaseCursorUnixSeconds {
return outbound.SupportCaseListPosition{}, errors.New("support case cursor position is invalid")
}
createdAt := time.Unix(int64(seconds), int64(nanos)).UTC()
if !validSupportCaseCursorTime(createdAt) {
return outbound.SupportCaseListPosition{}, errors.New("support case cursor timestamp is invalid")
}
return outbound.SupportCaseListPosition{CreatedAt: createdAt, ID: domain.SupportCaseID(caseID)}, nil
}
func validSupportCaseCursorTime(value time.Time) bool {
utc := value.UTC()
return !value.IsZero() && utc.Year() >= 1 && utc.Year() <= 9999 && value.Unix() >= 0 &&
value.Nanosecond()%int(time.Microsecond) == 0
}
func supportCaseResponse(supportCase domain.SupportCase, targetLate bool) (api.SupportCase, error) {
snapshot := supportCase.Snapshot()
target, err := checkedSupportResponseTarget(snapshot.ResponseTarget, targetLate)
if err != nil {
return api.SupportCase{}, err
}
response := api.SupportCase{
ID: snapshot.ID.UUID(), Number: api.SupportCaseNumber(snapshot.Number),
Type: api.SupportCaseType(snapshot.Type), Status: api.SupportCaseStatus(snapshot.Status),
Description: api.SupportCaseDescription(snapshot.Description),
ResponseTarget: target,
History: make([]api.SupportCaseEvent, 0, len(snapshot.History)),
CreatedAt: api.Timestamp(snapshot.CreatedAt), UpdatedAt: api.Timestamp(snapshot.UpdatedAt),
}
response.Object = supportCaseObject(snapshot.Object)
response.AssessmentTarget = supportCaseAssessmentTarget(snapshot.AssessmentTarget)
response.ComplaintReason = supportCaseComplaintReason(snapshot.ComplaintReason)
response.RubricVersion = supportCaseInt32(snapshot.RubricVersion)
response.Decision = supportCaseDecision(snapshot.Decision)
for _, event := range snapshot.History {
response.History = append(response.History, supportCaseEvent(event))
}
return response, nil
}
func supportCaseSummaryResponse(summary domain.SupportCaseSummary, targetLate bool) (api.SupportCaseSummary, error) {
target, err := checkedSupportResponseTarget(summary.ResponseTarget, targetLate)
if err != nil {
return api.SupportCaseSummary{}, err
}
response := api.SupportCaseSummary{
ID: summary.ID.UUID(), Number: api.SupportCaseNumber(summary.Number),
Type: api.SupportCaseType(summary.Type), Status: api.SupportCaseStatus(summary.Status),
Object: supportCaseObject(summary.Object), AssessmentTarget: supportCaseAssessmentTarget(summary.AssessmentTarget),
ResponseTarget: target, CreatedAt: api.Timestamp(summary.CreatedAt), UpdatedAt: api.Timestamp(summary.UpdatedAt),
}
if summary.DecisionOutcome == nil {
response.DecisionOutcome.SetToNull()
} else {
response.DecisionOutcome.SetTo(api.SupportCaseDecisionOutcome(*summary.DecisionOutcome))
}
return response, nil
}
func checkedSupportResponseTarget(snapshot domain.SupportResponseTargetSnapshot, late bool) (api.SupportResponseTarget, error) {
if _, err := domain.NewSupportResponseTarget(snapshot); err != nil {
return api.SupportResponseTarget{}, err
}
response := api.SupportResponseTarget{
Kind: api.SupportResponseTargetKindOperationalGoal,
BusinessDays: int32(snapshot.BusinessDays), DueAt: api.Timestamp(snapshot.DueAt),
Late: late, PolicyVersion: snapshot.PolicyVersion,
}
if snapshot.AnsweredAt == nil {
response.AnsweredAt.SetToNull()
} else {
response.AnsweredAt.SetTo(api.Timestamp(*snapshot.AnsweredAt))
}
return response, nil
}
func supportResponseTargetLate(snapshot domain.SupportResponseTargetSnapshot, at time.Time) bool {
target, err := domain.NewSupportResponseTarget(snapshot)
return err == nil && target.IsLate(at)
}
func supportCaseObject(reference *domain.SupportCaseReference) api.NilSupportCaseObjectReference {
var result api.NilSupportCaseObjectReference
if reference == nil {
result.SetToNull()
return result
}
result.SetTo(api.SupportCaseObjectReference{Type: api.SupportCaseObjectType(reference.Type), ID: reference.ID})
return result
}
func supportCaseAssessmentTarget(target *domain.SupportCaseAssessmentTarget) api.NilSupportCaseAssessmentTarget {
var result api.NilSupportCaseAssessmentTarget
if target == nil {
result.SetToNull()
return result
}
result.SetTo(api.SupportCaseAssessmentTarget{
Specialization: api.SpecializationCode(target.Specialization), Grade: api.GradeCode(target.Grade),
})
return result
}
func supportCaseComplaintReason(reason *domain.SupportCaseComplaintReason) api.NilSupportCaseComplaintReason {
var result api.NilSupportCaseComplaintReason
if reason == nil {
result.SetToNull()
return result
}
result.SetTo(api.SupportCaseComplaintReason(*reason))
return result
}
func supportCaseInt32(value *int32) api.NilInt32 {
var result api.NilInt32
if value == nil {
result.SetToNull()
return result
}
result.SetTo(*value)
return result
}
func supportCaseDecision(decision *domain.SupportCaseDecisionSnapshot) api.NilSupportCaseDecision {
var result api.NilSupportCaseDecision
if decision == nil {
result.SetToNull()
return result
}
result.SetTo(api.SupportCaseDecision{
Outcome: api.SupportCaseDecisionOutcome(decision.Outcome),
Reason: api.SupportCasePublicText(decision.Reason), DecidedAt: api.Timestamp(decision.DecidedAt),
})
return result
}
func supportCaseEvent(event domain.SupportCaseEventSnapshot) api.SupportCaseEvent {
result := api.SupportCaseEvent{
Sequence: event.Sequence, Kind: api.SupportCaseEventKind(event.Kind),
Actor: api.SupportCaseActorKind(event.Actor), OccurredAt: api.Timestamp(event.OccurredAt),
}
if event.Status == nil {
result.Status.SetToNull()
} else {
result.Status.SetTo(api.SupportCaseStatus(*event.Status))
}
if event.Message == nil {
result.Message.SetToNull()
} else {
result.Message.SetTo(api.SupportCasePublicText(*event.Message))
}
return result
}
func supportComplaintReasonPointer(value domain.SupportCaseComplaintReason) *domain.SupportCaseComplaintReason {
return &value
}
@@ -0,0 +1,216 @@
package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
supportcase "lincodex/backend/internal/usecase/supportcase"
)
func TestSupportCaseCreateCommandMapsManualRequestWithoutPriorAttempt(t *testing.T) {
request := api.SupportCaseCreate{
Type: api.SupportCaseCreateManualAssessmentSupportCaseCreate,
SupportCaseCreateManualAssessment: api.SupportCaseCreateManualAssessment{
Type: api.SupportCaseCreateManualAssessmentTypeManualAssessment,
Description: api.SupportCaseDescription("Please assess my Go skills."),
AssessmentTarget: api.SupportCaseAssessmentTarget{
Specialization: api.SpecializationCodeBackend,
Grade: api.GradeCodeJunior,
},
},
}
command, valid := supportCaseCreateCommand(request)
if !valid || command.Type != domain.SupportCaseTypeManualAssessment || command.Description != "Please assess my Go skills." ||
command.AssessmentTarget == nil || command.AssessmentTarget.Specialization != domain.SpecializationBackend ||
command.AssessmentTarget.Grade != domain.GradeJunior || command.Object != nil {
t.Fatalf("supportCaseCreateCommand() = %+v, %v; want a standalone manual-assessment request", command, valid)
}
}
func TestSupportCaseCursorIsBoundToOwnerAndStoredPrecision(t *testing.T) {
ownerID := uuid.Must(uuid.NewV7())
position := outbound.SupportCaseListPosition{
CreatedAt: time.Date(2026, time.October, 7, 10, 0, 0, 123456000, time.UTC),
ID: domain.SupportCaseID(uuid.Must(uuid.NewV7())),
}
cursor, err := encodeSupportCaseCursor(ownerID, position)
if err != nil {
t.Fatalf("encodeSupportCaseCursor() error = %v", err)
}
decoded, err := decodeSupportCaseCursor(cursor, ownerID)
if err != nil || decoded.ID != position.ID || !decoded.CreatedAt.Equal(position.CreatedAt) {
t.Fatalf("decodeSupportCaseCursor() = %+v, %v, want %+v", decoded, err, position)
}
if _, err := decodeSupportCaseCursor(cursor, uuid.Must(uuid.NewV7())); err == nil {
t.Fatal("decodeSupportCaseCursor() accepted a cursor from another owner")
}
if _, err := encodeSupportCaseCursor(ownerID, outbound.SupportCaseListPosition{
CreatedAt: position.CreatedAt.Add(time.Nanosecond), ID: position.ID,
}); err == nil {
t.Fatal("encodeSupportCaseCursor() accepted precision PostgreSQL cannot preserve")
}
for _, invalidTime := range []time.Time{
time.Unix(-1, 0).UTC(),
time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC),
} {
if _, err := encodeSupportCaseCursor(ownerID, outbound.SupportCaseListPosition{CreatedAt: invalidTime, ID: position.ID}); err == nil {
t.Errorf("encodeSupportCaseCursor() accepted unsupported time %v", invalidTime)
}
}
for name, mutate := range map[string]func([]byte){
"out-of-range year": func(value []byte) {
binary.BigEndian.PutUint64(value[17:25], uint64(time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC).Unix()))
},
"sub-microsecond precision": func(value []byte) {
binary.BigEndian.PutUint32(value[25:29], 1)
},
} {
t.Run(name, func(t *testing.T) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
t.Fatalf("DecodeString() error = %v", err)
}
mutate(value)
invalid := base64.RawURLEncoding.EncodeToString(value)
if _, err := decodeSupportCaseCursor(invalid, ownerID); err == nil {
t.Fatal("decodeSupportCaseCursor() accepted an unsupported position")
}
})
}
}
func TestSupportCaseRateLimitErrorPreservesRetryAfter(t *testing.T) {
result, err := supportCaseCreateFailure(principalTestContext(), &supportcase.RateLimitedError{
RetryAfter: 1500 * time.Millisecond,
})
if err != nil {
t.Fatalf("supportCaseCreateFailure() error = %v", err)
}
response, ok := result.(*api.TooManyRequestsHeaders)
if !ok {
t.Fatalf("supportCaseCreateFailure() result = %T, want *TooManyRequestsHeaders", result)
}
if seconds, present := response.RetryAfter.Get(); !present || seconds != 2 {
t.Fatalf("Retry-After = %d, %v; want 2 seconds", seconds, present)
}
}
func TestSupportCaseReadAuthorizationFailuresUseDocumented401(t *testing.T) {
for _, operation := range []string{"get", "list"} {
for _, failure := range []error{supportcase.ErrForbidden, supportcase.ErrEmailNotVerified} {
t.Run(operation+"/"+failure.Error(), func(t *testing.T) {
operations := &supportOperationsStub{getError: failure, listError: failure}
handler := NewSupportHandler(operations)
if operation == "get" {
result, err := handler.GetMySupportCase(principalTestContext(), api.GetMySupportCaseParams{CaseID: uuid.Must(uuid.NewV7())})
if err != nil {
t.Fatalf("GetMySupportCase() error = %v", err)
}
if _, ok := result.(*api.GetMySupportCaseUnauthorized); !ok {
t.Fatalf("GetMySupportCase() result = %T, want documented 401", result)
}
return
}
result, err := handler.ListMySupportCases(principalTestContext(), api.ListMySupportCasesParams{})
if err != nil {
t.Fatalf("ListMySupportCases() error = %v", err)
}
if _, ok := result.(*api.ListMySupportCasesUnauthorized); !ok {
t.Fatalf("ListMySupportCases() result = %T, want documented 401", result)
}
})
}
}
}
func TestSupportCaseHandlerBindsCreateToPrincipalAndReturnsNoStore(t *testing.T) {
ctx := principalTestContext()
principal, ok := PrincipalFromContext(ctx)
if !ok {
t.Fatal("principalTestContext() did not set a principal")
}
createdAt := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
responseTarget, err := domain.DemoSupportPolicy().ResponseTarget(domain.SupportCaseTypeSupport, 4, createdAt)
if err != nil {
t.Fatalf("ResponseTarget() error = %v", err)
}
supportCase, err := domain.NewSupportCase(domain.NewSupportCaseInput{
Number: "SC-2026-000123", OwnerID: principal.UserID, Type: domain.SupportCaseTypeSupport,
Description: "Please help with my account.", ResponseTarget: responseTarget, CreatedAt: createdAt,
})
if err != nil {
t.Fatalf("NewSupportCase() error = %v", err)
}
operations := &supportOperationsStub{createResult: supportcase.CreateResult{Case: supportCase}}
handler := NewSupportHandler(operations)
request := api.SupportCaseCreate{
Type: api.SupportCaseCreateSupportSupportCaseCreate,
SupportCaseCreateSupport: api.SupportCaseCreateSupport{
Type: api.SupportCaseCreateSupportTypeSupport,
Description: api.SupportCaseDescription("Please help with my account."),
},
}
result, err := handler.CreateMySupportCase(ctx, request, api.CreateMySupportCaseParams{IdempotencyKey: "support-key-1"})
if err != nil {
t.Fatalf("CreateMySupportCase() error = %v", err)
}
response, ok := result.(*api.SupportCaseHeaders)
if !ok {
t.Fatalf("CreateMySupportCase() result type = %T, want *SupportCaseHeaders", result)
}
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.ID != supportCase.ID().UUID() ||
response.Response.Type != api.SupportCaseTypeSupport || response.Response.Description != "Please help with my account." {
t.Fatalf("CreateMySupportCase() response = %+v", response)
}
if operations.createCommand.ActorID != principal.UserID || operations.createCommand.IdempotencyKey != "support-key-1" ||
operations.createCommand.Description != "Please help with my account." || len(operations.createCommand.CanonicalBody) == 0 {
t.Fatalf("create command did not preserve authenticated scope and body: %+v", operations.createCommand)
}
}
func TestSupportCaseHandlerRejectsMissingPrincipalBeforeCallingOperations(t *testing.T) {
operations := &supportOperationsStub{}
handler := NewSupportHandler(operations)
_, err := handler.GetMySupportCase(context.Background(), api.GetMySupportCaseParams{CaseID: uuid.Must(uuid.NewV7())})
if err != nil {
t.Fatalf("GetMySupportCase() error = %v", err)
}
if operations.getCalls != 0 {
t.Fatalf("operations.GetMyCase calls = %d, want none", operations.getCalls)
}
}
type supportOperationsStub struct {
createCommand supportcase.CreateCommand
createResult supportcase.CreateResult
createError error
getResult domain.SupportCase
getError error
getCalls int
listPage outbound.SupportCaseListPage
listError error
}
func (stub *supportOperationsStub) Create(_ context.Context, command supportcase.CreateCommand) (supportcase.CreateResult, error) {
stub.createCommand = command
return stub.createResult, stub.createError
}
func (stub *supportOperationsStub) GetMyCase(_ context.Context, _ uuid.UUID, _ domain.SupportCaseID) (domain.SupportCase, error) {
stub.getCalls++
return stub.getResult, stub.getError
}
func (stub *supportOperationsStub) ListMyCases(_ context.Context, _ supportcase.ListCommand) (outbound.SupportCaseListPage, error) {
return stub.listPage, stub.listError
}
var _ SupportOperations = (*supportOperationsStub)(nil)