// Code generated by ogen, DO NOT EDIT. package api import ( "context" "net/http" "time" "github.com/go-faster/errors" ht "github.com/ogen-go/ogen/http" "github.com/ogen-go/ogen/middleware" "github.com/ogen-go/ogen/ogenerrors" "github.com/ogen-go/ogen/otelogen" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/metric" semconv "go.opentelemetry.io/otel/semconv/v1.39.0" "go.opentelemetry.io/otel/trace" ) type codeRecorder struct { http.ResponseWriter status int } func (c *codeRecorder) WriteHeader(status int) { c.status = status c.ResponseWriter.WriteHeader(status) } func (c *codeRecorder) Unwrap() http.ResponseWriter { return c.ResponseWriter } // handleAcceptMyInvitationRequest handles AcceptMyInvitation operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // an allowed Origin, and an Idempotency-Key. The candidate comes from the session. // // Only an acceptance of the current terms version with the consent C4 creates access to contacts (PRD // FR12). The body names the `terms_version` the candidate read and accepts, the `expected_version` of // the invitation, and `consent_c4`: the C4 text version that the candidate saw, `accepted: true`, and // the contact fields the candidate selected. At least one field is required and nothing is preselected // or defaulted, so a grant never covers a field the candidate did not choose. The fields come only // from the candidate's profile; the request never carries contact values. // // Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from // `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the // invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the // fields, the invitation, the terms version, and the text version and its hash, creates the contact // grant for exactly those fields, and writes the audit event. The response is the invitation with // `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden // from the organization: the grant alone does not guarantee a read, and the organization reads only // while the visibility allows it. // // 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 // version_conflict, the repository status for a stale version, and records nothing; this is the stale // terms case, for example after the organization raised the salary, and the client reads the // invitation again and shows the new terms for a new decision. A state that does not allow an // acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, // the planned `counter`, or a command received at the deadline or later, which is late. A terminal // state and a passed deadline are checked before the versions: the server first applies the due // expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its // versions are stale, so it shows the final state instead of rereading and retrying. The repository // rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on // `state_conflict` to show the final state. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of // fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, // answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` // that a later raise advanced; no second consent, grant, or audit event is created. A different terms // version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed // fields is a matter of the consent operations. Of two concurrent acceptances only one makes the // transition. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 // idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat // on an accepted invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever // the versions), the versions (412), any other state that does not allow an acceptance (409 // state_conflict), then the consent rules (400 with the pointer `/consent_c4/text_version` for a text // version that is not the published one, or `/consent_c4/fields/0` for a field that the profile does // not hold). The schema rejects a missing `terms_version`, an empty or repeated field list, an unknown // field kind, `accepted` other than true, and unknown fields such as `email` or `phone`. The general // rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored // under the key; 400, 412, and 429 are not. // // POST /api/v1/me/invitations/{invitation_id}/accept func (s *Server) handleAcceptMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("AcceptMyInvitation"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}/accept"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), AcceptMyInvitationOperation, 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: AcceptMyInvitationOperation, ID: "AcceptMyInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, AcceptMyInvitationOperation, 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, AcceptMyInvitationOperation, 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 := decodeAcceptMyInvitationParams(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.decodeAcceptMyInvitationRequest(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 AcceptMyInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: AcceptMyInvitationOperation, OperationSummary: "Accept the current terms and disclose the selected contacts.", OperationID: "AcceptMyInvitation", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "invitation_id", In: "path", }: params.InvitationID, { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *InvitationAcceptance Params = AcceptMyInvitationParams Response = AcceptMyInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackAcceptMyInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.AcceptMyInvitation(ctx, request, params) return response, err }, ) } else { response, err = s.h.AcceptMyInvitation(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 := encodeAcceptMyInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleCancelMyInvitationRequest handles CancelMyInvitation operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // an allowed Origin, and an Idempotency-Key. The candidate comes from the session. // // Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): // `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. // In the same transaction the server revokes the contact grant that the acceptance of this invitation // created, with the reason `participation_cancelled`, so the next contact read of the organization // answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the // organization as a whole, which closes all of them, belongs to the consent operations. // // Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance // and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an // acceptance, and carries no reason; a withdrawal is the organization's command and keeps the grant. // Before an answer the client offers the decline. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a cancellation of an invitation that is already `cancelled_by_candidate` answers 200 with it // even with a new key or an older `expected_version`. A terminal state other than // `cancelled_by_candidate` answers 409 state_conflict even with a stale `expected_version`; otherwise // a stale `expected_version` answers 412 version_conflict. The deadline does not limit a cancellation. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 // idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat // on a cancelled invitation (200), a terminal state (409 state_conflict, whatever the version), then // the version (412). The general rate limit can answer 429 with Retry-After before any check. 404 and // 409 state_conflict are stored under the key; 400, 412, and 429 are not. // // POST /api/v1/me/invitations/{invitation_id}/cancel func (s *Server) handleCancelMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("CancelMyInvitation"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}/cancel"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), CancelMyInvitationOperation, 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: CancelMyInvitationOperation, ID: "CancelMyInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, CancelMyInvitationOperation, 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, CancelMyInvitationOperation, 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 := decodeCancelMyInvitationParams(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.decodeCancelMyInvitationRequest(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 CancelMyInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: CancelMyInvitationOperation, OperationSummary: "Cancel the participation in an invitation and revoke its contact grant.", OperationID: "CancelMyInvitation", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "invitation_id", In: "path", }: params.InvitationID, { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *InvitationCommand Params = CancelMyInvitationParams Response = CancelMyInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackCancelMyInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.CancelMyInvitation(ctx, request, params) return response, err }, ) } else { response, err = s.h.CancelMyInvitation(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 := encodeCancelMyInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleConfirmEmailRequest handles ConfirmEmail operation. // // Public operation without a session. The verification link has the form // `/verify-email#token=`: the token travels in the URL fragment, so it never // reaches a server log or a Referer header. The page first removes the fragment with // `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it // posts the token here. A link scanner that only fetches the page therefore does not consume the // token. // // The server looks up the token by its hash and, in one transaction, checks that it is unused, not // expired, and bound to the current registration version, marks it used, and marks the email verified. // Only one of several parallel requests with the same token succeeds. An expired token of the current // registration answers verification_token_expired; an unknown, used, replaced, or superseded token // answers verification_token_invalid, even when that token is also expired. Neither refusal changes // anything. For both, the client offers a new link and sign-in, because the address may already be // verified. // // Confirmation also requires the password chosen for the registration that issued this token. A token // from a replaced registration cannot apply another registration's password or scenario. The server // checks the password against the token's pending password hash before consuming the token, then // applies that token's password, scenario, and onboarding step only if the current registration's C1 // consent matches its registration version. A wrong password or token without pending registration // data answers verification_token_invalid and leaves the account and token unchanged. // // A repeated confirmation with an already used token is not an idempotent 200: exactly one request may // succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after // either outcome is sign-in anyway. // // Success does not start a session: the link may be opened on another device or by a mail scanner, and // a session must come only from the password. The response returns the scenario and the saved // onboarding step so the client can continue after sign-in. The operation is rate-limited and requires // an allowed Origin. Missing Origin, the special value `null`, or an Origin other than the configured // public application origin answers csrf_check_failed. // // POST /api/v1/identity/email-verifications func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ConfirmEmail"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/identity/email-verifications"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ConfirmEmailOperation, 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: ConfirmEmailOperation, ID: "ConfirmEmail", } ) params, err := decodeConfirmEmailParams(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.decodeConfirmEmailRequest(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 ConfirmEmailRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ConfirmEmailOperation, OperationSummary: "Verify an email with the one-time token from the link.", OperationID: "ConfirmEmail", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "Origin", In: "header", }: params.Origin, }, Raw: r, } type ( Request = *EmailVerificationRequest Params = ConfirmEmailParams Response = ConfirmEmailRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackConfirmEmailParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ConfirmEmail(ctx, request, params) return response, err }, ) } else { response, err = s.h.ConfirmEmail(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 := encodeConfirmEmailResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleCreateMyAssessmentAttemptRequest handles CreateMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real // assessment names a specialization, target grade, and task language; the server picks `demo_basic` or // `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A // corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain // and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a // chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5 // minutes, has no category or target grade, and creates no qualification evidence or percentile. // Creation starts session 1. The self-assessed grade only chooses where a real test starts and adds no // points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted // for the time passed, so a new attempt adds evidence instead of starting the measurement over. // // A specialization has at most one active real attempt. A new root attempt cannot start while one is // active, during a retry or promotion interval, past the root quota, or when the bank is insufficient; // each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot. // Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its // root, target a strictly lower grade not already attempted in that chain, and remain inside the // root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its // own item, practice, and session limits, but spends no additional root slot and cannot reset the // chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can // be tested at once. An expired or incomplete attempt does not create a free new chain; an // insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside // real-assessment availability, quotas, retry intervals, and qualification history. // // The limits are server-side: `expires_at` and `sessions` come from the policy version, the client // clock never extends them, and after them the attempt accepts no work command. For a corrective // attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits // the attempt is also bounded by the item limit of its policy. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 // state_conflict response and creates nothing, so a lost response never creates a second attempt. A // different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a // corrected retry is evaluated again. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 // idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` // for a specialization that is not in the questionnaire or `/task_language` for a language that the // bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with // Retry-After before any of them; it is not stored. // // POST /api/v1/me/assessment-attempts func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("CreateMyAssessmentAttempt"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), CreateMyAssessmentAttemptOperation, 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: CreateMyAssessmentAttemptOperation, ID: "CreateMyAssessmentAttempt", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, CreateMyAssessmentAttemptOperation, 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, CreateMyAssessmentAttemptOperation, 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 := decodeCreateMyAssessmentAttemptParams(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.decodeCreateMyAssessmentAttemptRequest(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 CreateMyAssessmentAttemptRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: CreateMyAssessmentAttemptOperation, OperationSummary: "Start a real, corrective, or training assessment attempt.", OperationID: "CreateMyAssessmentAttempt", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = AssessmentAttemptCreate Params = CreateMyAssessmentAttemptParams Response = CreateMyAssessmentAttemptRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackCreateMyAssessmentAttemptParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.CreateMyAssessmentAttempt(ctx, request, params) return response, err }, ) } else { response, err = s.h.CreateMyAssessmentAttempt(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 := encodeCreateMyAssessmentAttemptResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleCreateMySupportCaseRequest handles CreateMySupportCase operation. // // Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and // an Idempotency-Key. The author is the account of the session; the body has no user, account, or // organization field. A case is reachable from any screen, including a screen that denies access to an // assessment: being refused an action never removes the path to a case about it. // // The client sends only what the user states: `type`, a non-blank `description`, and the fields of the // type. It never sets the status, the decision, the outcome, the priority, the response target, the // rubric, the assignee, or the moderator: every variant has `additionalProperties: false`, so such // fields answer 400. Attachments are not part of the MVP; they are planned as an optional field and // change no existing one. // // Types, accounts, and allowed references: // // Type | Accounts | Object reference | Other fields // --------------------+---------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------ // `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` that the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` // `complaint` | candidate | required; an `organization` that the caller can see or an `invitation` addressed to the caller | required `complaint_reason`; `offer_content` and `salary_terms_violation` require an invitation // `grade_appeal` | candidate | required; `assessment_attempt` of the caller in a terminal state, so it has a result, or a `support_case` of the caller of type `manual_assessment` that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt | none // `anticheat_appeal` | candidate | required; `assessment_attempt` of the caller with an anti-cheat review decision | none // `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` // // An organization is visible to a candidate when it sent the candidate an invitation or when the // organization contract shows the candidate its profile, and to an employer account when the account // has an active membership in it. Invitations are in the contract but not implemented yet, so until // they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not // either, so until review decisions are implemented, every anti-cheat appeal answers 409 // state_conflict. The schema rejects an object type that the case type does not accept, for example an // organization in a grade appeal. // // Ownership of the reference: the server checks the object against the session account on every // create. An unknown object and an object of someone else, such as another candidate's attempt, // another account's case, or an invitation addressed to another person, both answer 404 not_found, so // a reference never reveals whether a foreign object exists. An own case that a grade appeal cannot // dispute, because it is not a manual assessment, is not resolved yet, or was resolved with another // outcome, answers 409 state_conflict. An identifier that is not a UUID fails validation with the // pointer `/object/id`. The case stores only the type and the identifier of the object. // // Limits: an attempt and a resolved manual assessment each accept at most one grade appeal, and an // attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a // support case that references the appeal as `support_case`. A specialization accepts one open manual // assessment, and an object accepts one open complaint; open means not `resolved` or `closed`. A // second one answers 409 state_conflict. A grade appeal of an attempt that is still active also // answers 409. Every create that passed authentication, validation, and the account scenario counts // against a per-account limit from the product policy, including replays, 404, and 409, so the limit // also bounds probing of references; over the limit the server answers 429 with Retry-After and // creates nothing. // // Description check: the schema pattern `\S` uses the ECMAScript white space set in both generated // validators (ogen converts it for Go), so a description of spaces such as U+00A0 or U+3000 already // fails validation with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which // Go `unicode.IsSpace` includes, so the server also applies a domain check: a description whose every // character is `unicode.IsSpace` or U+FEFF answers 400 validation_failed with the pointer // `/description`. This check comes with the implementation; generated Zod accepts a description of // NEL, and the server stays authoritative. // // The new case gets a number and the status `submitted`. A grade appeal, an anti-cheat appeal, and a // manual assessment are moved to `waiting_expert` by a `system` event in the same transaction, so the // 201 already shows that status with both events; a support case and a complaint stay `submitted`. // Each case gets a response target from the product policy version and the configured business // calendar: 5 business days for a manual assessment and 10 for an appeal (PRD FR18 and C3), and a // policy value for support and complaints. The target is an operational goal, not a deadline set by // law. A manual assessment fixes the published rubric version of the category, or null when the // category has none yet; the expert assesses with the same rubric as the automated assessment, and the // request assigns no category by itself. Creating a case never grants, revokes, or changes a consent, // a grade, or an attempt. // // Replies: the case itself is the channel. Support replies and decisions appear in the public // `history` and `decision`. The server may also notify the verified email address of the account that // the case changed, with the case number and a link, never with the description, the reply, or // assessment details. No request field names another address or contact, so the operation cannot send // mail to an address that the user typed. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 with the same // number and creates nothing, so a lost response never opens a second case. The replay is the snapshot // stored at creation, following the repository convention; the client reads the current status and // history with GetMySupportCase. 404 and 409 state_conflict are stored and replayed as well. A // different body with the same key answers 422 idempotency_key_reused. 400, 403, and 429 are never // stored. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer account with a type other than `support`), the // per-account case limit (429), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain // rules (400 with the pointer `/description` for a text of only Unicode spaces or `/object/type` for a // complaint reason that requires an invitation), the object reference (404 not_found), then the state // of the object and the limits (409 state_conflict). The general rate limit can answer 429 with // Retry-After before any check. // // POST /api/v1/me/support-cases func (s *Server) handleCreateMySupportCaseRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("CreateMySupportCase"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/support-cases"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), CreateMySupportCaseOperation, 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: CreateMySupportCaseOperation, ID: "CreateMySupportCase", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, CreateMySupportCaseOperation, 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, CreateMySupportCaseOperation, 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 := decodeCreateMySupportCaseParams(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.decodeCreateMySupportCaseRequest(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 CreateMySupportCaseRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: CreateMySupportCaseOperation, OperationSummary: "Open a support case, a complaint, an appeal, or a manual assessment request.", OperationID: "CreateMySupportCase", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = SupportCaseCreate Params = CreateMySupportCaseParams Response = CreateMySupportCaseRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackCreateMySupportCaseParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.CreateMySupportCase(ctx, request, params) return response, err }, ) } else { response, err = s.h.CreateMySupportCase(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 := encodeCreateMySupportCaseResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleCreateOrganizationRequest handles CreateOrganization operation. // // Requires the session cookie of an employer account with a confirmed email, the CSRF token of that // session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the // session: the body has no owner, membership, role, verification, or version field, and unknown fields // fail validation. // // The server creates the organization and the owner membership of the caller (role `owner`, state // `active`) in one transaction, so an organization never exists without its owner. The organization // starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be // requested: the creator of a company with a corporate domain, a long description, or many // representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of // the server that do not exist yet. Only `name` is required; the rest of the card can be completed // with UpdateOrganization. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates // nothing, so a lost response never creates a second organization. A different body with the same key // answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. // Two requests with different keys are two organizations; the product may limit the number of // organizations per account (open question), which would answer 409 `state_conflict` without a change // of the schema. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409 // idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a // website that is not an https URL of a host name, `/name` for a name with surrounding whitespace). // The general rate limit can answer 429 with Retry-After before any check; 429 is never stored. // // POST /api/v1/organizations func (s *Server) handleCreateOrganizationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("CreateOrganization"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/organizations"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), CreateOrganizationOperation, 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: CreateOrganizationOperation, ID: "CreateOrganization", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, CreateOrganizationOperation, 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, CreateOrganizationOperation, 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 := decodeCreateOrganizationParams(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.decodeCreateOrganizationRequest(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 CreateOrganizationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: CreateOrganizationOperation, OperationSummary: "Create an organization; the caller becomes its owner.", OperationID: "CreateOrganization", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *OrganizationCreate Params = CreateOrganizationParams Response = CreateOrganizationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackCreateOrganizationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.CreateOrganization(ctx, request, params) return response, err }, ) } else { response, err = s.h.CreateOrganization(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 := encodeCreateOrganizationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleCreateOrganizationInvitationRequest handles CreateOrganizationInvitation operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF // token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The organization // comes from the path and the server-side membership; the body has no organization, membership, or // role field. In the MVP only the owner of the organization may create an invitation. // // The draft is addressed to one person from a search result of this organization: `candidate_handle` // is the opaque handle of that card, never an email address, a phone number, or an account identifier. // The server resolves the handle for this organization only. An unknown handle, a handle of another // organization, and a profile that the organization may no longer see, because the candidate revoked // the publication C2 or hid the profile from it, all answer 400 with the pointer `/candidate_handle`, // so a handle never reveals which case applies. `need` is optional: a direct invitation has none, and // a need given must be a need of the organization with a `requirements_version` that it has had, // otherwise 400 with the pointer `/need`. `response_period_days` is 3, 7, or 14 and defaults to 7. // // The terms are complete from the start (PRD FR12): the role, the specialization and the grade, the // offer type, the tasks, the team, the technology stack, the work formats and the place of work, the // communication method, the salary range in RUB with its tax basis, and the package. Each package // condition is either `provided` with a description or explicitly `not_provided`; leaving one out // fails validation. A draft without the tax basis or the communication method therefore cannot exist. // The draft is created as version 1 with terms version 1, and the candidate does not see it until // SendOrganizationInvitation. // // Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, // `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in // integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the // candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a // range because of the minimum, since a rejection would reveal it. Creating a draft is an // indicator-relevant setting: it counts against the limit shared by the whole organization with the // ranges of needs, at most three settings a day, and against the withheld counter, after five settings // within seven days the indicator is `withheld` for seven days from the fifth, on every draft and // invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the // limit the server answers 429 with Retry-After and creates nothing. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates // nothing, so a lost response never creates a second draft. A different body with the same key answers // 422 idempotency_key_reused. 400 and 429 are never stored. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 // forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a // pointer: `/candidate_handle`, `/need`, `/terms/salary/salary_to` for a reversed range or a width // outside 10-40%, `/terms/location` for the `office` or `hybrid` format without a place of work, or // `/terms/tech_stack/1` for a repeated technology), then the salary limit (429). The schema already // rejects a missing term or package condition, a salary bound that is not a positive multiple of 1000, // an unknown currency, period, or tax basis, and unknown fields such as `state`, `version`, // `salary_fit`, `candidate_email`, or `salary_minimum`. The general rate limit can answer 429 with // Retry-After before any check. // // POST /api/v1/organizations/{org_id}/invitations func (s *Server) handleCreateOrganizationInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("CreateOrganizationInvitation"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), CreateOrganizationInvitationOperation, 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: CreateOrganizationInvitationOperation, ID: "CreateOrganizationInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, CreateOrganizationInvitationOperation, 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, CreateOrganizationInvitationOperation, 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 := decodeCreateOrganizationInvitationParams(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.decodeCreateOrganizationInvitationRequest(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 CreateOrganizationInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: CreateOrganizationInvitationOperation, OperationSummary: "Create an invitation draft for one candidate.", OperationID: "CreateOrganizationInvitation", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *OrganizationInvitationCreate Params = CreateOrganizationInvitationParams Response = CreateOrganizationInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackCreateOrganizationInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.CreateOrganizationInvitation(ctx, request, params) return response, err }, ) } else { response, err = s.h.CreateOrganizationInvitation(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 := encodeCreateOrganizationInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleCreateOrganizationNeedRequest handles CreateOrganizationNeed operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF // token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The organization // comes from the path and the server-side membership; the body has no organization, membership, or // role field. In the MVP only the owner of the organization may create a need; the other roles of PRD // FR07 are planned. // // A need does not require a vacancy: `vacancy_id` is optional and nullable. When it is given, it must // name a vacancy of the same organization; until vacancies exist in the contract, any vacancy // identifier answers 400 with the pointer `/vacancy_id`, the same for an unknown vacancy and one of // another organization. // // Only `title` is required. A field is sent as a decision `{value, status}` and a list item as // `{name or text, status}`; on creation the status must be `confirmed`, and the value becomes a // confirmed manual value. When `source_text` is given, the server extracts suggestions for the absent // fields with deterministic rules and a dictionary before it answers, so creation works while the ML // service is disabled; every suggestion has the status `extracted`, the origin extracted_from_text, a // quote where the extractor found one, and the extractor version, and it waits for a member to confirm // it. A field that the text does not state stays `unknown` with null value and source; the server // never guesses a grade, a format, or a salary. ML suggestions with quotes are planned as an // asynchronous addition that creates a new version and never overwrites a confirmed value. // // The need is saved even when critical fields are missing: the response is 201 with version 1, and // `readiness.missing_fields` names each critical field without a confirmed value with a specific // question. `recommendations` is computed by the server from the confirmed requirements only; the // request cannot set a recommendation, its score, or its components. Creating a need never contacts a // candidate or sends an invitation. // // Salary limit: setting a salary range counts against a limit shared by the whole organization, every // member and every need, on creation as on a change: at most three range settings a day (PRD FR13, // enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. // After five settings within seven days the money component of the recommendations is `withheld` for // seven days. The limit keeps an organization from probing hidden candidate minimums with new needs // instead of edits; repeated range changes also feed the private organization risk signals. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates // nothing, so a lost response never creates a second need. A different body with the same key answers // 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 // forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a // pointer: `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose // width is outside 10-40%, `/required_skills/1/name` for a repeated skill, `/grade/status` or // `/required_skills/0/status` for `extracted`, which a new need cannot have, or `/vacancy_id`), then // the salary limit (429). The schema already rejects unknown fields such as `rec_score`, `members`, or // `candidate_minimum`, a field sent as a bare value instead of `{value, status}`, a salary bound that // is not a positive multiple of 1000, and an unknown currency, period, or tax basis. The general rate // limit can answer 429 with Retry-After before any check. 429 is never stored. // // POST /api/v1/organizations/{org_id}/needs func (s *Server) handleCreateOrganizationNeedRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("CreateOrganizationNeed"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/needs"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), CreateOrganizationNeedOperation, 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: CreateOrganizationNeedOperation, ID: "CreateOrganizationNeed", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, CreateOrganizationNeedOperation, 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, CreateOrganizationNeedOperation, 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 := decodeCreateOrganizationNeedParams(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.decodeCreateOrganizationNeedRequest(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 CreateOrganizationNeedRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: CreateOrganizationNeedOperation, OperationSummary: "Create a need of an organization from a form, a text, or both.", OperationID: "CreateOrganizationNeed", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *NeedCreate Params = CreateOrganizationNeedParams Response = CreateOrganizationNeedRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackCreateOrganizationNeedParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.CreateOrganizationNeed(ctx, request, params) return response, err }, ) } else { response, err = s.h.CreateOrganizationNeed(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 := encodeCreateOrganizationNeedResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleDeclineMyInvitationRequest handles DeclineMyInvitation operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // an allowed Origin, and an Idempotency-Key. The candidate comes from the session. // // Allowed in `delivered`, `viewed`, and the planned `counter`, before `response_deadline_at`. Moves // the invitation to the terminal state `declined` with the reason and the optional comment; no consent // and no access arise (PRD FR12). A timely decline counts as an answer for the responsiveness metrics, // not as a consent or a hire. The reason is one of InvitationDeclineReason, including the neutral // `other`; no reason requires a comment. // // Visibility: the organization sees only the state `declined` and `responded_at`. It never sees the // reason or the comment of an individual decline, because a reason such as `salary` would tell it that // the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size // (planned); the comment is never shown to the organization, published, logged, or sent in a // notification. The candidate reads both back in `decline`. A new invitation of the same organization // to this candidate is possible only after the 30-day pause. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a decline of an invitation that is already `declined` with the same reason and comment answers // 200 with it even with a new key or an older `expected_version`. A terminal state, another reason or // comment on a declined invitation, and a command at the deadline or later answer 409 state_conflict // even with a stale `expected_version`; otherwise a stale `expected_version` answers 412 // version_conflict. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 // idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat // on a declined invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever // the version), the version (412), then any other state that does not allow a decline (409 // state_conflict). The schema rejects an unknown reason, an empty comment or one of only white space, // a comment over 500 characters, and unknown fields. The general rate limit can answer 429 with // Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 // are not. // // POST /api/v1/me/invitations/{invitation_id}/decline func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("DeclineMyInvitation"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}/decline"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), DeclineMyInvitationOperation, 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: DeclineMyInvitationOperation, ID: "DeclineMyInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, DeclineMyInvitationOperation, 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, DeclineMyInvitationOperation, 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 := decodeDeclineMyInvitationParams(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.decodeDeclineMyInvitationRequest(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 DeclineMyInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: DeclineMyInvitationOperation, OperationSummary: "Decline an invitation with a structured reason.", OperationID: "DeclineMyInvitation", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "invitation_id", In: "path", }: params.InvitationID, { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *InvitationDeclineRequest Params = DeclineMyInvitationParams Response = DeclineMyInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackDeclineMyInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.DeclineMyInvitation(ctx, request, params) return response, err }, ) } else { response, err = s.h.DeclineMyInvitation(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 := encodeDeclineMyInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleFinalizeMyAssessmentAttemptRequest handles FinalizeMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the // result: the decision may continue the attempt, and one response type keeps that unambiguous for // every generated client. When the returned state is `completed`, the client reads the result with // GetMyAssessmentResult. // // Finalize is a work command and requires an active session. After `idle_timeout_seconds` of // inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest // `expected_version`; finalize never starts a session. GET attempt and result operations do not change // state. A command or background transition may commit a due deadline outcome. // // Allowed in `ready_to_finalize`, where every required part is done, and in // `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server // decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: // // - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and // completes the attempt. It never offers an additional practice. // - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection // completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the // demo policy) on the first finalize, while time and sessions remain, completes nothing: the server // appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers // 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no // new attempt. The next finalize, after its verdict, decides with the added evidence; a probability // still below confirmation gives `not_confirmed`. An attempt offers at most one additional // practice. // - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the // current evidence. A retry of the first finalize with a new key cannot decline by accident: it // carries the version from before the offer and answers 412. // // A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the // same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers // 200 with that attempt even with a new key or an older `expected_version`; the result is computed // once. When `expires_at` passes or the session limit is reached, a command or background transition // finalizes `ready_to_finalize` without offering an additional practice. A finalize after this // 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. // // 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), // the attempt (404 not_found; a due deadline transition may be committed, but this request never // starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state // (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under // the key; 400 and 412 are not. // // POST /api/v1/me/assessment-attempts/{attempt_id}/finalize func (s *Server) handleFinalizeMyAssessmentAttemptRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("FinalizeMyAssessmentAttempt"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/finalize"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), FinalizeMyAssessmentAttemptOperation, 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: FinalizeMyAssessmentAttemptOperation, ID: "FinalizeMyAssessmentAttempt", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, FinalizeMyAssessmentAttemptOperation, 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, FinalizeMyAssessmentAttemptOperation, 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 := decodeFinalizeMyAssessmentAttemptParams(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.decodeFinalizeMyAssessmentAttemptRequest(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 FinalizeMyAssessmentAttemptRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: FinalizeMyAssessmentAttemptOperation, OperationSummary: "Ask for the grade decision of an assessment attempt.", OperationID: "FinalizeMyAssessmentAttempt", 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 = *AssessmentFinalization Params = FinalizeMyAssessmentAttemptParams Response = FinalizeMyAssessmentAttemptRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackFinalizeMyAssessmentAttemptParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.FinalizeMyAssessmentAttempt(ctx, request, params) return response, err }, ) } else { response, err = s.h.FinalizeMyAssessmentAttempt(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 := encodeFinalizeMyAssessmentAttemptResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetConsentTextRequest handles GetConsentText operation. // // Public operation without a session. Returns the current text of a consent that is given before an // account exists; only `c1` is available. The registration page shows this text and sends its // `text_version` with RegisterAccount, and the server hashes the same stored text when it records the // acceptance. If the text changes while the page is open, RegisterAccount answers 400 // validation_failed with the pointer `/consent_c1/text_version`, and the page reads the text again. An // unknown purpose fails parameter validation with 400. // // GET /api/v1/identity/consent-texts/{purpose} func (s *Server) handleGetConsentTextRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetConsentText"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/identity/consent-texts/{purpose}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetConsentTextOperation, 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: GetConsentTextOperation, ID: "GetConsentText", } ) params, err := decodeGetConsentTextParams(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 GetConsentTextRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetConsentTextOperation, OperationSummary: "Read the currently published text of a registration consent.", OperationID: "GetConsentText", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "purpose", In: "path", }: params.Purpose, }, Raw: r, } type ( Request = struct{} Params = GetConsentTextParams Response = GetConsentTextRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetConsentTextParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetConsentText(ctx, params) return response, err }, ) } else { response, err = s.h.GetConsentText(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 := encodeGetConsentTextResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetCurrentAccountRequest handles GetCurrentAccount operation. // // Requires the session cookie. The account comes from the session, never from a request parameter. The // client uses `scenario` and `onboarding_step` to return the user to the unfinished onboarding step. A // missing, unknown, expired, or revoked session answers 401 unauthenticated. An unverified account // never has a session, because login answers 403 email_not_verified for it, so this operation also // answers 401 for such an account. // // GET /api/v1/identity/me func (s *Server) handleGetCurrentAccountRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetCurrentAccount"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/identity/me"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetCurrentAccountOperation, 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: GetCurrentAccountOperation, ID: "GetCurrentAccount", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetCurrentAccountOperation, 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 } } var rawBody []byte var response GetCurrentAccountRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetCurrentAccountOperation, OperationSummary: "Read the account of the current session.", OperationID: "GetCurrentAccount", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = GetCurrentAccountRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetCurrentAccount(ctx) return response, err }, ) } else { response, err = s.h.GetCurrentAccount(ctx) } 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 := encodeGetCurrentAccountResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetCurrentSessionRequest handles GetCurrentSession operation. // // Requires the session cookie. Returns the account and the CSRF token of the current session, so the // client can restore the token after a page reload or after 403 csrf_check_failed. A missing, unknown, // expired, or revoked session answers 401 unauthenticated. Cross-origin pages cannot read the token, // because the API sends no Access-Control-Allow-Origin header. // // GET /api/v1/identity/sessions/current func (s *Server) handleGetCurrentSessionRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetCurrentSession"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/identity/sessions/current"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetCurrentSessionOperation, 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: GetCurrentSessionOperation, ID: "GetCurrentSession", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetCurrentSessionOperation, 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 } } var rawBody []byte var response GetCurrentSessionRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetCurrentSessionOperation, OperationSummary: "Read the current session and its CSRF token.", OperationID: "GetCurrentSession", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = GetCurrentSessionRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetCurrentSession(ctx) return response, err }, ) } else { response, err = s.h.GetCurrentSession(ctx) } 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 := encodeGetCurrentSessionResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetHealthzRequest handles GetHealthz operation. // // Check whether the API process is responding. // // GET /api/v1/healthz func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetHealthz"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/healthz"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetHealthzOperation, 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 ) var rawBody []byte var response *HealthResponse if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetHealthzOperation, OperationSummary: "Check whether the API process is responding.", OperationID: "GetHealthz", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = *HealthResponse ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetHealthz(ctx) return response, err }, ) } else { response, err = s.h.GetHealthz(ctx) } 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 := encodeGetHealthzResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetMyAssessmentAttemptRequest handles GetMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account. Returns the stored attempt projection with its // state, fixed versions, time and session limits, progress, the item to answer now, and the practices. // This GET is read-only: it never starts or resumes a work session, consumes session quota, advances // the version, or commits expiry or finalization. A reload, a retried request, or a new session // returns the same item instance with the same text and option order; a lost connection never creates // a new attempt. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with // StartMyAssessmentAttemptSession. The response never says whether an earlier answer was correct and // never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or // anti-cheat signals. // // When the deadline passes, this read still returns the stored state and deadline. A command or // background transition commits the due outcome; if the stored state is still active, // GetMyAssessmentResult answers 409 until that transition is committed. The client polls this // operation while a practice is `pending`, but polling alone never changes attempt state. // // The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 // not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account // answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or // attempt history. // // GET /api/v1/me/assessment-attempts/{attempt_id} func (s *Server) handleGetMyAssessmentAttemptRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMyAssessmentAttempt"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyAssessmentAttemptOperation, 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: GetMyAssessmentAttemptOperation, ID: "GetMyAssessmentAttempt", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentAttemptOperation, 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 := decodeGetMyAssessmentAttemptParams(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 GetMyAssessmentAttemptRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMyAssessmentAttemptOperation, OperationSummary: "Read an assessment attempt of the current candidate.", OperationID: "GetMyAssessmentAttempt", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "attempt_id", In: "path", }: params.AttemptID, }, Raw: r, } type ( Request = struct{} Params = GetMyAssessmentAttemptParams Response = GetMyAssessmentAttemptRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetMyAssessmentAttemptParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMyAssessmentAttempt(ctx, params) return response, err }, ) } else { response, err = s.h.GetMyAssessmentAttempt(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 := encodeGetMyAssessmentAttemptResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetMyAssessmentAvailabilityRequest handles GetMyAssessmentAvailability operation. // // Requires the session cookie of a candidate account; the candidate comes from the session. For each // specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every // grade whether an attempt can start now, in which mode, and with which limits: the time limit, the // session limit, the item limit, and whether a code practice is required. The client shows them before // the start, together with the method and the signals that are collected, and resumes an active // attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt. // // `insufficient_bank` is the state of a category whose bank is not published or has too few families // that this candidate has not seen; the server limits attempts instead of repeating families. // `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with // that date and offer support. Specializations and their retry intervals are independent. Attempts // that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations // and never cause a `cooldown`. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account // answers 403 forbidden. // // GET /api/v1/me/assessment-availability func (s *Server) handleGetMyAssessmentAvailabilityRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMyAssessmentAvailability"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/assessment-availability"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyAssessmentAvailabilityOperation, 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: GetMyAssessmentAvailabilityOperation, ID: "GetMyAssessmentAvailability", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentAvailabilityOperation, 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 } } var rawBody []byte var response GetMyAssessmentAvailabilityRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMyAssessmentAvailabilityOperation, OperationSummary: "Read which assessment attempts the current candidate can start.", OperationID: "GetMyAssessmentAvailability", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = GetMyAssessmentAvailabilityRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMyAssessmentAvailability(ctx) return response, err }, ) } else { response, err = s.h.GetMyAssessmentAvailability(ctx) } 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 := encodeGetMyAssessmentAvailabilityResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetMyAssessmentResultRequest handles GetMyAssessmentResult operation. // // Requires the session cookie of a candidate account. Returns the immutable result of a terminal // attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy, // bank, and algorithm versions, decision, previously confirmed grade, calibration status and // limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time // as a separate label, and allowed next steps. A corrective result also carries the root attempt and // its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no // category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later // policy, bank, or algorithm version never changes a result. // // Fields that the method does not compute are null and never zero: a `demo_basic` result has null // `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, // seeds, hidden checks, or anti-cheat signals. // // An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active // and has no result yet. This GET is read-only and never commits a due transition. If a deadline has // passed but the due transition is not yet stored by a command or background worker, the attempt // remains active for this read and answers 409; wait for the transition and retry. An attempt of // another candidate answers 404 not_found, the same as an unknown identifier. An employer account // answers 403 forbidden; employers see only the current category through a separate projection, never // this result or the attempt history. // // GET /api/v1/me/assessment-attempts/{attempt_id}/result func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMyAssessmentResult"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/result"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyAssessmentResultOperation, 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: GetMyAssessmentResultOperation, ID: "GetMyAssessmentResult", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentResultOperation, 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 := decodeGetMyAssessmentResultParams(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 GetMyAssessmentResultRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMyAssessmentResultOperation, OperationSummary: "Read the result of an assessment attempt of the current candidate.", OperationID: "GetMyAssessmentResult", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "attempt_id", In: "path", }: params.AttemptID, }, Raw: r, } type ( Request = struct{} Params = GetMyAssessmentResultParams Response = GetMyAssessmentResultRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetMyAssessmentResultParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMyAssessmentResult(ctx, params) return response, err }, ) } else { response, err = s.h.GetMyAssessmentResult(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 := encodeGetMyAssessmentResultResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // 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`. // // 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. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account // answers 403 forbidden. // // GET /api/v1/me/privacy/preview func (s *Server) handleGetMyCardPreviewRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMyCardPreview"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/privacy/preview"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyCardPreviewOperation, 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: GetMyCardPreviewOperation, ID: "GetMyCardPreview", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMyCardPreviewOperation, 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 } } var rawBody []byte var response GetMyCardPreviewRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMyCardPreviewOperation, OperationSummary: "Preview the anonymous card that organizations would read.", OperationID: "GetMyCardPreview", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = GetMyCardPreviewRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMyCardPreview(ctx) return response, err }, ) } else { response, err = s.h.GetMyCardPreview(ctx) } 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 := encodeGetMyCardPreviewResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetMyConsentTextRequest handles GetMyConsentText operation. // // Requires a verified session. Returns the current published text and version of c1, c2, c3, or c5 so // the user can read the exact text before an explicit settings grant. C4 is excluded: its text // includes an organization snapshot and it is granted only during invitation acceptance. The response // is private and is not cached. // // GET /api/v1/me/consent-texts/{purpose} func (s *Server) handleGetMyConsentTextRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMyConsentText"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/consent-texts/{purpose}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyConsentTextOperation, 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: GetMyConsentTextOperation, ID: "GetMyConsentText", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMyConsentTextOperation, 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 := decodeGetMyConsentTextParams(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 GetMyConsentTextRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMyConsentTextOperation, OperationSummary: "Read a current consent text for account settings.", OperationID: "GetMyConsentText", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "purpose", In: "path", }: params.Purpose, }, Raw: r, } type ( Request = struct{} Params = GetMyConsentTextParams Response = GetMyConsentTextRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetMyConsentTextParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMyConsentText(ctx, params) return response, err }, ) } else { response, err = s.h.GetMyConsentText(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 := encodeGetMyConsentTextResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetMyInvitationRequest handles GetMyInvitation operation. // // Requires the session cookie of a candidate account. The candidate comes from the session; the // invitation must be addressed to this candidate. // // Returns the organization, the current terms version with the full terms, the state, and the // deadline. While an acceptance is possible (`delivered` or `viewed` before the deadline), // `contact_consent` holds the published text of the consent C4 for this organization and the kinds of // contact that the profile holds, with nothing preselected; otherwise it is null. It is null as well // when the profile holds no contact: a grant must cover at least one field, so the client asks the // candidate to add a contact to the profile before accepting. After an answer the response holds the // candidate's own decline or the contact grant that the acceptance created, with the selected kinds, // its status, and whether the organization can read it now (`readable`, with `blocked_by` `visibility` // when the profile is not published or is hidden from the organization), never contact values. The // response never carries the candidate's handle, the need of the organization, the salary indicator of // the organization, or any contact or salary minimum of the candidate. // // Reading has no side effect on the invitation: it never records a view. The client records that the // candidate opened the terms with ViewMyInvitation, an explicit command, so a prefetch, a retry, or a // cache refresh never changes the state that the organization sees. The only change a read can cause // is the due expiry: a read at the deadline or later first applies the server transition to `expired` // with `invitation_timeout`, which would happen without the read as well, and the response shows it. // Reading earlier terms versions is planned as a separate operation. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer // account answers 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown // identifier all answer 404 not_found, so identifiers cannot be enumerated. An `invitation_id` that is // not a UUID answers 400 validation_failed with the path pointer. // // GET /api/v1/me/invitations/{invitation_id} func (s *Server) handleGetMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMyInvitation"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyInvitationOperation, 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: GetMyInvitationOperation, ID: "GetMyInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMyInvitationOperation, 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 := decodeGetMyInvitationParams(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 GetMyInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMyInvitationOperation, OperationSummary: "Open the terms of an invitation addressed to the current candidate.", OperationID: "GetMyInvitation", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "invitation_id", In: "path", }: params.InvitationID, }, Raw: r, } type ( Request = struct{} Params = GetMyInvitationParams Response = GetMyInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetMyInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMyInvitation(ctx, params) return response, err }, ) } else { response, err = s.h.GetMyInvitation(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 := encodeGetMyInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetMyPrivacySettingsRequest handles GetMyPrivacySettings operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from // a request parameter. Returns the publication of the candidate card, the search status, and the // number of hidden organizations in one read. The response is `Cache-Control: no-store`. // // A profile is closed by default. A candidate who never published reads `publication.state` `closed` // with `closed_reason` `never_published`, an empty field set, and version 0; creating or saving the // profile (`SaveMyProfile`) never publishes it, and no operation of the profile, the questionnaire, or // an assessment changes these settings. The C2 consent, the search status, and the hidden // organizations are three independent settings: the C2 record in the consent ledger proves that the // candidate accepted the publication text, the publication records which fields are published, and the // search status is a statement of the candidate that is not a consent. A change of one never changes // another, and none of them ever makes the candidate more visible by itself: the search status lapses // to the non-public `not_looking`, a revoked C2 closes the card, and a new C2 grant publishes nothing. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account // answers 403 forbidden. // // GET /api/v1/me/privacy func (s *Server) handleGetMyPrivacySettingsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMyPrivacySettings"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/privacy"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyPrivacySettingsOperation, 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: GetMyPrivacySettingsOperation, ID: "GetMyPrivacySettings", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMyPrivacySettingsOperation, 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 } } var rawBody []byte var response GetMyPrivacySettingsRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMyPrivacySettingsOperation, OperationSummary: "Read the visibility settings of the current candidate.", OperationID: "GetMyPrivacySettings", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = GetMyPrivacySettingsRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMyPrivacySettings(ctx) return response, err }, ) } else { response, err = s.h.GetMyPrivacySettings(ctx) } 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 := encodeGetMyPrivacySettingsResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetMyProfileRequest handles GetMyProfile operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from // a request parameter. A candidate who has not saved the profile yet gets 200 with version 0, every // single field `unknown`, and empty lists rather than 404, so the client reads the version for the // first save in the same way as for later ones and a missing profile is not an error state. // // The profile is personal data that only its owner reads: full name, contacts, work history, and the // lowest salary. It is a private resource and never an organization-visible one; organizations see a // candidate through the anonymous card and, after an accepted invitation, through the contact grant, // and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and // the server never writes its values to logs, metrics, URLs, or events. // // Every value carries its confirmation state and provenance, and every claim has trust level 0. The // self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results // establish and which no request writes. The profile needs no file, no ML extraction, and no FSP // account. // // `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices // refer to this response's `experience` array and are scoped to the same `version`; each pair is // either `needs_confirmation` or `confirmed`. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account // answers 403 forbidden. // // GET /api/v1/me/profile func (s *Server) handleGetMyProfileRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMyProfile"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/profile"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyProfileOperation, 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: GetMyProfileOperation, ID: "GetMyProfile", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMyProfileOperation, 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 } } var rawBody []byte var response GetMyProfileRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMyProfileOperation, OperationSummary: "Read the private profile of the current candidate.", OperationID: "GetMyProfile", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = GetMyProfileRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMyProfile(ctx) return response, err }, ) } else { response, err = s.h.GetMyProfile(ctx) } 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 := encodeGetMyProfileResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetMyQuestionnaireRequest handles GetMyQuestionnaire operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from // a request parameter. A candidate who has not saved the questionnaire yet gets 200 with version 0 and // no specializations rather than 404, so the client reads the version for the first save in the same // way as for later ones and a missing questionnaire is not an error state. // // The response never contains a confirmed grade or a category; those come only from assessment // results. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer // account answers 403 forbidden. // // GET /api/v1/me/questionnaire func (s *Server) handleGetMyQuestionnaireRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMyQuestionnaire"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/questionnaire"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyQuestionnaireOperation, 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: GetMyQuestionnaireOperation, ID: "GetMyQuestionnaire", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMyQuestionnaireOperation, 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 } } var rawBody []byte var response GetMyQuestionnaireRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMyQuestionnaireOperation, OperationSummary: "Read the questionnaire of the current candidate.", OperationID: "GetMyQuestionnaire", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = GetMyQuestionnaireRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMyQuestionnaire(ctx) return response, err }, ) } else { response, err = s.h.GetMyQuestionnaire(ctx) } 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 := encodeGetMyQuestionnaireResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetMySupportCaseRequest handles GetMySupportCase operation. // // Requires the session cookie of a candidate or an employer account. Returns the case with its number, // type, object reference, status, response target, decision, and public history. The owner reads the // case whatever happened to the object since then: a revoked access, a closed invitation, or a refused // test never hides the case from its author. // // The case never contains the identity of a moderator, an expert, or a support agent, internal notes, // evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. // `decision` is null until the case is `resolved`. // // The history lists every public event and is never truncated: the server keeps a case within 200 // events by rejecting a staff event that would leave no room for the terminal one. // // The case must belong to the account of the session: a case of another account, including another // member of the same organization, answers 404 not_found, the same as an unknown identifier, so // identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" // state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with // the path pointer. // // GET /api/v1/me/support-cases/{case_id} func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetMySupportCase"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/support-cases/{case_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetMySupportCaseOperation, 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: GetMySupportCaseOperation, ID: "GetMySupportCase", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetMySupportCaseOperation, 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 := decodeGetMySupportCaseParams(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 GetMySupportCaseRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetMySupportCaseOperation, OperationSummary: "Read a support case of the current account.", OperationID: "GetMySupportCase", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "case_id", In: "path", }: params.CaseID, }, Raw: r, } type ( Request = struct{} Params = GetMySupportCaseParams Response = GetMySupportCaseRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetMySupportCaseParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetMySupportCase(ctx, params) return response, err }, ) } else { response, err = s.h.GetMySupportCase(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 := encodeGetMySupportCaseResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetOrganizationRequest handles GetOrganization operation. // // Requires the session cookie of a verified employer account with an active owner membership in // `org_id`. The organization comes from the path and is checked against the membership that the server // holds for the session account on every request; the identifier itself grants nothing. // // Returns the profile with its current `version`, the verification level (`verification`), and the // card as a candidate sees it (`candidate_card`). The verification level is always the one the server // holds: it never rises because the profile is complete, because the organization has members, or // because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations // returns it with the membership. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden; an account without an active membership in the organization, // including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 // not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers // 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer. // // GET /api/v1/organizations/{org_id} func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetOrganization"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationOperation, 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: GetOrganizationOperation, ID: "GetOrganization", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationOperation, 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 := decodeGetOrganizationParams(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 GetOrganizationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetOrganizationOperation, OperationSummary: "Read an organization managed by the caller.", OperationID: "GetOrganization", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, }, Raw: r, } type ( Request = struct{} Params = GetOrganizationParams Response = GetOrganizationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetOrganizationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetOrganization(ctx, params) return response, err }, ) } else { response, err = s.h.GetOrganization(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 := encodeGetOrganizationResponse(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 // organization and the role come from the server-side membership, never from the request. In the MVP // only the owner of the organization reads invitations. // // Returns the invitation with the current terms version, the state, the deadline, the coarse salary // indicator `salary_fit`, and `contact_access`. The candidate appears only as the opaque // `candidate_handle`: before and after an acceptance this response never carries the candidate's name, // email address, phone number, or other contact, the exact salary minimum, or the reason and comment // of a decline. Contact values come only from GetOrganizationInvitationContacts while // `contact_access.status` is `available`. Reading earlier terms versions is planned as a separate // operation. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden; an account without an active membership in the organization, an // unknown organization, an unknown invitation, and an invitation of another organization all answer // 404 not_found, so identifiers cannot be probed; a member whose role does not allow reading the // invitation answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 // validation_failed with the path pointer. // // GET /api/v1/organizations/{org_id}/invitations/{invitation_id} func (s *Server) handleGetOrganizationInvitationRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetOrganizationInvitation"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationInvitationOperation, 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: GetOrganizationInvitationOperation, ID: "GetOrganizationInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationInvitationOperation, 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 := decodeGetOrganizationInvitationParams(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 GetOrganizationInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetOrganizationInvitationOperation, OperationSummary: "Read an invitation of an organization.", OperationID: "GetOrganizationInvitation", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "invitation_id", In: "path", }: params.InvitationID, }, Raw: r, } type ( Request = struct{} Params = GetOrganizationInvitationParams Response = GetOrganizationInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetOrganizationInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetOrganizationInvitation(ctx, params) return response, err }, ) } else { response, err = s.h.GetOrganizationInvitation(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 := encodeGetOrganizationInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetOrganizationInvitationContactsRequest handles GetOrganizationInvitationContacts operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP // only the owner of the organization reads contacts; the other roles of PRD FR07 are planned. // // This is the only operation that returns contact values, and its response is separate from the terms // and from the invitation. It answers only while a grant created by the acceptance of this invitation // is active and the read is allowed now: on every request the server checks the membership, the // consent C4 for this organization, the grant and its fields, and the current visibility of the // profile (C2 and the organizations the candidate hid the profile from), with no cache in between, so // a revocation closes the next read at once. The response holds exactly the fields that the grant // covers; every other field is null. A grant of organization A never answers for organization B. // // Without such a grant the contacts do not exist for the caller, and the operation answers 404 // not_found, the same as for an unknown invitation: before an acceptance, after a decline or an // expiry, after the candidate revoked C4 or cancelled the participation, after the candidate closed // the visibility, and while a grant created when the profile was not published or was hidden from the // organization stays blocked. The answer does not tell which applies; `contact_access` of // GetOrganizationInvitation tells the organization whether access is `not_granted`, `available`, or // `closed`, without the reason, and the candidate sees `readable` and `blocked_by` on the grant. // Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens // a closed grant; only a new explicit C4 creates a new one. // // Every successful read is recorded in the access audit (planned with the contact access history), and // the response has `Cache-Control: no-store`. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden; an account without an active membership in the organization, an // unknown organization, an unknown invitation, an invitation of another organization, and an // invitation without an active readable grant all answer 404 not_found; a member whose role does not // allow reading contacts answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID // answers 400 validation_failed with the path pointer. // // GET /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts func (s *Server) handleGetOrganizationInvitationContactsRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetOrganizationInvitationContacts"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationInvitationContactsOperation, 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: GetOrganizationInvitationContactsOperation, ID: "GetOrganizationInvitationContacts", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationInvitationContactsOperation, 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 := decodeGetOrganizationInvitationContactsParams(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 GetOrganizationInvitationContactsRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetOrganizationInvitationContactsOperation, OperationSummary: "Read the contacts that the candidate disclosed to the organization.", OperationID: "GetOrganizationInvitationContacts", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "invitation_id", In: "path", }: params.InvitationID, }, Raw: r, } type ( Request = struct{} Params = GetOrganizationInvitationContactsParams Response = GetOrganizationInvitationContactsRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetOrganizationInvitationContactsParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetOrganizationInvitationContacts(ctx, params) return response, err }, ) } else { response, err = s.h.GetOrganizationInvitationContacts(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 := encodeGetOrganizationInvitationContactsResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetOrganizationNeedRequest handles GetOrganizationNeed operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. The // organization and the role come from the server-side membership, never from the request. In the MVP // only the owner of the organization reads needs; the other roles of PRD FR07 are planned. // // Returns the current version of the need: `version`, the requirements with the confirmation state and // provenance of each field (`status`, and `source` with the origin, the quote, the version whose text // the quote belongs to, and the extractor version), the readiness with `missing_fields`, and the // category recommendations of the server. A field with status `unknown` has null value and source; an // `extracted` value is a suggestion that waits for confirmation and never feeds search or // recommendations. // // Versions: every committed change creates a new immutable `version`, and this operation always // returns the latest one. `requirements_version` is the version in which the confirmed requirements // were last changed; a change of the title, the vacancy link, the text, or suggestions only keeps it. // Search runs, selection snapshots, and invitations refer to a need by its identifier and // `requirements_version`, so they keep the requirements they used, and only a new // `requirements_version` calls for a new selection snapshot. Reading and comparing earlier versions // (PRD FR10) are planned as separate operations that return the same NeedRequirementSet for a given // version; they add no field here. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden; an account without an active membership in the organization, an // unknown organization, an unknown need, and a need of another organization all answer 404 not_found, // so identifiers cannot be probed; a member whose role does not allow reading the need answers 403 // forbidden. An `org_id` or `need_id` that is not a UUID answers 400 validation_failed with the path // pointer. // // GET /api/v1/organizations/{org_id}/needs/{need_id} func (s *Server) handleGetOrganizationNeedRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetOrganizationNeed"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/needs/{need_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationNeedOperation, 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: GetOrganizationNeedOperation, ID: "GetOrganizationNeed", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationNeedOperation, 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 := decodeGetOrganizationNeedParams(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 GetOrganizationNeedRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetOrganizationNeedOperation, OperationSummary: "Read the current version of a need of an organization.", OperationID: "GetOrganizationNeed", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "need_id", In: "path", }: params.NeedID, }, Raw: r, } type ( Request = struct{} Params = GetOrganizationNeedParams Response = GetOrganizationNeedRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGetOrganizationNeedParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetOrganizationNeed(ctx, params) return response, err }, ) } else { response, err = s.h.GetOrganizationNeed(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 := encodeGetOrganizationNeedResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGetSpecializationCatalogRequest handles GetSpecializationCatalog operation. // // Public operation without a session. Returns the directions with their specializations, the // assessment availability of each specialization, and the grade scale. The candidate picks // specializations and self-assessed grades from this catalog for the questionnaire, and the client // joins the codes stored in the questionnaire with the titles here. // // The catalog is public because it is the same for every caller and contains no personal data: the // product shows it before registration, and a public read lets intermediaries and the browser cache // it. It reveals nothing beyond what the landing pages already show. // // A category is a specialization together with a confirmed grade. Task languages and the stack are // attributes of a chosen specialization and never appear as categories. `test_availability` is derived // from the published task banks at the time of the request, so it changes when a bank is published, // without a contract change: the MVP opens an assessment only for a category with a published bank, // and every other specialization is marked `in_development`. Presence in the catalog never means that // its test is ready. // // GET /api/v1/specializations func (s *Server) handleGetSpecializationCatalogRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GetSpecializationCatalog"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/specializations"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GetSpecializationCatalogOperation, 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 ) var rawBody []byte var response *SpecializationCatalog if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GetSpecializationCatalogOperation, OperationSummary: "Read the catalog of directions, specializations, and grades.", OperationID: "GetSpecializationCatalog", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = *SpecializationCatalog ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GetSpecializationCatalog(ctx) return response, err }, ) } else { response, err = s.h.GetSpecializationCatalog(ctx) } 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 := encodeGetSpecializationCatalogResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleGrantMyConsentRequest handles GrantMyConsent operation. // // Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The // subject comes from the session. The body names the current text version the user read and requires // `accepted: true`; the server verifies that version is still current and stores the hash of the exact // text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant. // // C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate // accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the // same current version returns the existing record; after revocation a grant creates a new record and // never reopens a publication or restores an older grant. // // PUT /api/v1/me/consents/{purpose} func (s *Server) handleGrantMyConsentRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("GrantMyConsent"), semconv.HTTPRequestMethodKey.String("PUT"), semconv.HTTPRouteKey.String("/api/v1/me/consents/{purpose}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), GrantMyConsentOperation, 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: GrantMyConsentOperation, ID: "GrantMyConsent", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, GrantMyConsentOperation, 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, GrantMyConsentOperation, 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 := decodeGrantMyConsentParams(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.decodeGrantMyConsentRequest(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 GrantMyConsentRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: GrantMyConsentOperation, OperationSummary: "Record an explicit consent grant from settings.", OperationID: "GrantMyConsent", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "purpose", In: "path", }: params.Purpose, }, Raw: r, } type ( Request = *ConsentSettingsGrantRequest Params = GrantMyConsentParams Response = GrantMyConsentRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackGrantMyConsentParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.GrantMyConsent(ctx, request, params) return response, err }, ) } else { response, err = s.h.GrantMyConsent(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 := encodeGrantMyConsentResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleHideOrganizationRequest handles HideOrganization operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. The request has no body: the path names the organization and the candidate // comes from the session. The hiding is a record that belongs to the candidate and references the // organization; it changes neither the C2 consent, nor the publication, nor the search status. // // The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization // that is already hidden answers 200 with the existing record and its original `hidden_at`, changes // nothing, and writes no history record. There is one record per candidate and organization. // // 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. // // 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 // other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the // limit. // // Hiding an organization that holds an active contact grant of the candidate revokes that grant with // the reason `visibility_closed` in the same transaction (planned together with the invitation // operations). Lifting the hiding never reopens a grant. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the // path (400), account scenario (403 forbidden for an employer), the organization and its visibility to // the candidate (404 not_found), then the repeat (200), then the limit (409 state_conflict). Like // every visibility change, hiding needs a verified email (a usecase requirement). // // PUT /api/v1/me/privacy/hidden-organizations/{org_id} func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("HideOrganization"), semconv.HTTPRequestMethodKey.String("PUT"), semconv.HTTPRouteKey.String("/api/v1/me/privacy/hidden-organizations/{org_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), HideOrganizationOperation, 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: HideOrganizationOperation, ID: "HideOrganization", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, HideOrganizationOperation, 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, HideOrganizationOperation, 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 := decodeHideOrganizationParams(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 HideOrganizationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: HideOrganizationOperation, OperationSummary: "Hide the candidate profile from one organization.", OperationID: "HideOrganization", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, }, Raw: r, } type ( Request = struct{} Params = HideOrganizationParams Response = HideOrganizationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackHideOrganizationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.HideOrganization(ctx, params) return response, err }, ) } else { response, err = s.h.HideOrganization(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 := encodeHideOrganizationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleListMyCardAccessHistoryRequest handles ListMyCardAccessHistory operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, so the // response holds only accesses to the caller's own card. Returns a page, newest first with the record // identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. // // 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. // // 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. // // 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. // // GET /api/v1/me/privacy/access-history func (s *Server) handleListMyCardAccessHistoryRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ListMyCardAccessHistory"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/privacy/access-history"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyCardAccessHistoryOperation, 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: ListMyCardAccessHistoryOperation, ID: "ListMyCardAccessHistory", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ListMyCardAccessHistoryOperation, 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 := decodeListMyCardAccessHistoryParams(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 ListMyCardAccessHistoryRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ListMyCardAccessHistoryOperation, OperationSummary: "List the accesses of organizations to the card of the current candidate.", OperationID: "ListMyCardAccessHistory", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "limit", In: "query", }: params.Limit, { Name: "cursor", In: "query", }: params.Cursor, }, Raw: r, } type ( Request = struct{} Params = ListMyCardAccessHistoryParams Response = ListMyCardAccessHistoryRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackListMyCardAccessHistoryParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ListMyCardAccessHistory(ctx, params) return response, err }, ) } else { response, err = s.h.ListMyCardAccessHistory(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 := encodeListMyCardAccessHistoryResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleListMyConsentsRequest handles ListMyConsents operation. // // Requires the session cookie of a candidate or an employer account. The subject comes from the // session, never from a request parameter, so the response holds only the caller's own consents: no // request can name another account, and records of other accounts are never listed. Returns a page of // the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with // cursor pagination. // // The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the // source, and the grant time; the server also stores the hash of exactly the text the subject saw. A // newer text version of the same purpose is a new record, and the earlier one becomes `superseded` // without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one // organization, once; a later grant is a new record. Purposes are independent. // // Without `state` the page lists the whole history; `state=active` lists the consents that hold now, // one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the // organization with the name its consent text showed (a snapshot that a later rename does not change), // the selected contact fields, and the invitation with its terms version; it never carries a contact // value. A c2 record proves the consent to the publication text; the published field set and its // changes are evidence of the publication history. // // Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit // acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion // request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed // `limit`, `cursor`, or `state` answers 400 validation_failed. // // GET /api/v1/me/consents func (s *Server) handleListMyConsentsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ListMyConsents"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/consents"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyConsentsOperation, 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: ListMyConsentsOperation, ID: "ListMyConsents", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ListMyConsentsOperation, 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 := decodeListMyConsentsParams(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 ListMyConsentsRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ListMyConsentsOperation, OperationSummary: "List the consents of the current account with their history.", OperationID: "ListMyConsents", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "state", In: "query", }: params.State, { Name: "limit", In: "query", }: params.Limit, { Name: "cursor", In: "query", }: params.Cursor, }, Raw: r, } type ( Request = struct{} Params = ListMyConsentsParams Response = ListMyConsentsRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackListMyConsentsParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ListMyConsents(ctx, params) return response, err }, ) } else { response, err = s.h.ListMyConsents(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 := encodeListMyConsentsResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleListMyHiddenOrganizationsRequest handles ListMyHiddenOrganizations operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, so the // response holds only the caller's own records and no request can name another account. Returns a page // of the hidden organizations, newest first with the organization identifier as the tie-breaker, with // cursor pagination. The response is `Cache-Control: no-store`. // // The records belong to the candidate. An organization never reads them, never learns that it is // hidden, and sees a hidden candidate exactly as it sees one who is not published: no search result, // no card, no contact read. // // 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. // // GET /api/v1/me/privacy/hidden-organizations func (s *Server) handleListMyHiddenOrganizationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ListMyHiddenOrganizations"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/privacy/hidden-organizations"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyHiddenOrganizationsOperation, 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: ListMyHiddenOrganizationsOperation, ID: "ListMyHiddenOrganizations", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ListMyHiddenOrganizationsOperation, 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 := decodeListMyHiddenOrganizationsParams(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 ListMyHiddenOrganizationsRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ListMyHiddenOrganizationsOperation, OperationSummary: "List the organizations that the candidate hides the profile from.", OperationID: "ListMyHiddenOrganizations", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "limit", In: "query", }: params.Limit, { Name: "cursor", In: "query", }: params.Cursor, }, Raw: r, } type ( Request = struct{} Params = ListMyHiddenOrganizationsParams Response = ListMyHiddenOrganizationsRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackListMyHiddenOrganizationsParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ListMyHiddenOrganizations(ctx, params) return response, err }, ) } else { response, err = s.h.ListMyHiddenOrganizations(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 := encodeListMyHiddenOrganizationsResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleListMyInvitationsRequest handles ListMyInvitations operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from // a request parameter. Returns a page of the candidate's inbox, newest first by delivery time with the // identifier as the tie-breaker, with cursor pagination: every invitation that was delivered to this // candidate, in any later state, including withdrawn and expired ones. Drafts and invitations // addressed to other candidates are never listed. // // A summary has the organization, the state, the versions, the role, the salary range, the work // formats, and the deadline. Listing never records a view: the state `delivered` stays until // ViewMyInvitation records that the candidate opened the terms. Responsiveness metrics of the // organization and filters by state are planned and add fields or optional parameters. // // 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. // // GET /api/v1/me/invitations func (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ListMyInvitations"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/invitations"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyInvitationsOperation, 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: ListMyInvitationsOperation, ID: "ListMyInvitations", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ListMyInvitationsOperation, 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 := decodeListMyInvitationsParams(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 ListMyInvitationsRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ListMyInvitationsOperation, OperationSummary: "List the invitations addressed to the current candidate.", OperationID: "ListMyInvitations", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "limit", In: "query", }: params.Limit, { Name: "cursor", In: "query", }: params.Cursor, }, Raw: r, } type ( Request = struct{} Params = ListMyInvitationsParams Response = ListMyInvitationsRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackListMyInvitationsParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ListMyInvitations(ctx, params) return response, err }, ) } else { response, err = s.h.ListMyInvitations(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 := encodeListMyInvitationsResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleListMyOrganizationsRequest handles ListMyOrganizations operation. // // Requires the session cookie of an employer account. The account comes from the session, never from a // request parameter, so the response holds only the caller's own memberships and no request can name // another account. // // Returns a page of the organizations in which the caller has an `active` membership, newest // membership first with the organization identifier as the tie-breaker, with cursor pagination. Each // item names the organization (`OrganizationSummary`) and holds the caller's role and state in it // (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not // list its organization, so an organization the caller cannot enter is never named, and one that the // caller was removed from disappears from the list at once. // // The list is the directory of the active organization context. The context is not stored on the // server: every organization-scoped operation names its organization in the path `org_id`, and the // server checks that identifier against the caller's active membership on every request, so a switch // between organizations is a different `org_id` in the client's routes and cannot outlive a revoked // membership. A client picks the context from this list, may remember the last choice in the browser // as a convenience, and must read the list again after any answer 404 `not_found` from an organization // path. An account with several memberships sees all of them here and works in one at a time; the // rights and the data of the organizations stay separate. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden. An employer account without an organization gets an empty page, which // tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400 // validation_failed. // // GET /api/v1/me/organizations func (s *Server) handleListMyOrganizationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ListMyOrganizations"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/organizations"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyOrganizationsOperation, 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: ListMyOrganizationsOperation, ID: "ListMyOrganizations", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ListMyOrganizationsOperation, 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 := decodeListMyOrganizationsParams(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 ListMyOrganizationsRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ListMyOrganizationsOperation, OperationSummary: "List the organizations available to the current account.", OperationID: "ListMyOrganizations", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "limit", In: "query", }: params.Limit, { Name: "cursor", In: "query", }: params.Cursor, }, Raw: r, } type ( Request = struct{} Params = ListMyOrganizationsParams Response = ListMyOrganizationsRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackListMyOrganizationsParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ListMyOrganizations(ctx, params) return response, err }, ) } else { response, err = s.h.ListMyOrganizations(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 := encodeListMyOrganizationsResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleListMyPrivacyHistoryRequest handles ListMyPrivacyHistory operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, so the // response holds only the caller's own records. Returns a page of the settings history, newest first // with the event identifier as the tie-breaker, with cursor pagination. The response is // `Cache-Control: no-store`. // // The history is append-only evidence of what the candidate published, hid, and announced, and when. A // publication event keeps the published fields and the C2 record behind them, which is what the // consent ledger deliberately does not carry (the C2 record proves the consent to the text, not the // field set). A revocation of C2 and a lapse of the search status are computed and are not events // here; the consent history shows the revocation. The history never contains a profile value. // // 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. // // GET /api/v1/me/privacy/history func (s *Server) handleListMyPrivacyHistoryRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ListMyPrivacyHistory"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/privacy/history"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyPrivacyHistoryOperation, 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: ListMyPrivacyHistoryOperation, ID: "ListMyPrivacyHistory", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ListMyPrivacyHistoryOperation, 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 := decodeListMyPrivacyHistoryParams(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 ListMyPrivacyHistoryRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ListMyPrivacyHistoryOperation, OperationSummary: "List the changes of the visibility settings of the current candidate.", OperationID: "ListMyPrivacyHistory", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "limit", In: "query", }: params.Limit, { Name: "cursor", In: "query", }: params.Cursor, }, Raw: r, } type ( Request = struct{} Params = ListMyPrivacyHistoryParams Response = ListMyPrivacyHistoryRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackListMyPrivacyHistoryParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ListMyPrivacyHistory(ctx, params) return response, err }, ) } else { response, err = s.h.ListMyPrivacyHistory(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 := encodeListMyPrivacyHistoryResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleListMySupportCasesRequest handles ListMySupportCases operation. // // Requires the session cookie of a candidate or an employer account. Returns a page of the cases that // this account created, newest first by creation time with the identifier as the tie-breaker, with // cursor pagination. Each item is a summary with the number, type, status, object reference, category, // response target, and decision outcome; it has no description and no history, which GetMySupportCase // returns with the full case. Cases of other accounts are never listed, including cases of other // members of the same organization. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed // `limit` or `cursor` answers 400 validation_failed. Filters by status and type are planned and add // optional parameters. // // GET /api/v1/me/support-cases func (s *Server) handleListMySupportCasesRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ListMySupportCases"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/me/support-cases"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ListMySupportCasesOperation, 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: ListMySupportCasesOperation, ID: "ListMySupportCases", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ListMySupportCasesOperation, 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 := decodeListMySupportCasesParams(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 ListMySupportCasesRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ListMySupportCasesOperation, OperationSummary: "List the support cases of the current account.", OperationID: "ListMySupportCases", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "limit", In: "query", }: params.Limit, { Name: "cursor", In: "query", }: params.Cursor, }, Raw: r, } type ( Request = struct{} Params = ListMySupportCasesParams Response = ListMySupportCasesRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackListMySupportCasesParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ListMySupportCases(ctx, params) return response, err }, ) } else { response, err = s.h.ListMySupportCases(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 := encodeListMySupportCasesResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleListOrganizationInvitationsRequest handles ListOrganizationInvitations operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. The // organization and the role come from the membership that the server holds for the session account, // never from the request. In the MVP only the owner of the organization works with invitations, as // with needs; the other roles of the PRD FR07 matrix are planned and change no field of this contract. // // Returns a page of invitation summaries in every state, drafts included, newest first by creation // time with the identifier as the tie-breaker, with cursor pagination. A summary names the candidate // only by the opaque `candidate_handle` and has the state, the versions, the role, the salary range, // the deadline, and the contact access without any contact value. A declined invitation shows the // state `declined` without the reason or the comment. Filters by state and need are planned and add // optional parameters. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden; an account without an active membership in the organization and an // unknown organization both answer 404 not_found, so organizations cannot be enumerated; a member // whose role does not allow reading invitations answers 403 forbidden. A malformed `org_id`, `limit`, // or `cursor` answers 400 validation_failed. // // GET /api/v1/organizations/{org_id}/invitations func (s *Server) handleListOrganizationInvitationsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ListOrganizationInvitations"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ListOrganizationInvitationsOperation, 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: ListOrganizationInvitationsOperation, ID: "ListOrganizationInvitations", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ListOrganizationInvitationsOperation, 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 := decodeListOrganizationInvitationsParams(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 ListOrganizationInvitationsRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ListOrganizationInvitationsOperation, OperationSummary: "List the invitations of an organization.", OperationID: "ListOrganizationInvitations", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "limit", In: "query", }: params.Limit, { Name: "cursor", In: "query", }: params.Cursor, }, Raw: r, } type ( Request = struct{} Params = ListOrganizationInvitationsParams Response = ListOrganizationInvitationsRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackListOrganizationInvitationsParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ListOrganizationInvitations(ctx, params) return response, err }, ) } else { response, err = s.h.ListOrganizationInvitations(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 := encodeListOrganizationInvitationsResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleListOrganizationNeedsRequest handles ListOrganizationNeeds operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. The // organization and the role come from the membership that the server holds for the session account, // never from the request. In the MVP only the owner of the organization works with needs; the other // roles of the PRD FR07 matrix (recruiter, hiring manager and technical expert for assigned needs) are // planned and change no field of this contract. The list holds only the needs that the role may read. // // Returns a page of need summaries, newest first by creation time with the identifier as the // tie-breaker, with cursor pagination. A summary has the current version, the target specialization // and grade with their confirmation state, and the readiness; GetOrganizationNeed returns the // requirements and the recommendations. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden; an account without an active membership in the organization and an // unknown organization both answer 404 not_found, so organizations cannot be enumerated; a member // whose role does not allow reading needs answers 403 forbidden. A malformed `org_id`, `limit`, or // `cursor` answers 400 validation_failed. // // GET /api/v1/organizations/{org_id}/needs func (s *Server) handleListOrganizationNeedsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ListOrganizationNeeds"), semconv.HTTPRequestMethodKey.String("GET"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/needs"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ListOrganizationNeedsOperation, 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: ListOrganizationNeedsOperation, ID: "ListOrganizationNeeds", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ListOrganizationNeedsOperation, 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 := decodeListOrganizationNeedsParams(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 ListOrganizationNeedsRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ListOrganizationNeedsOperation, OperationSummary: "List the needs of an organization.", OperationID: "ListOrganizationNeeds", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "limit", In: "query", }: params.Limit, { Name: "cursor", In: "query", }: params.Cursor, }, Raw: r, } type ( Request = struct{} Params = ListOrganizationNeedsParams Response = ListOrganizationNeedsRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackListOrganizationNeedsParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ListOrganizationNeeds(ctx, params) return response, err }, ) } else { response, err = s.h.ListOrganizationNeeds(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 := encodeListOrganizationNeedsResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleLoginRequest handles Login operation. // // Public operation that starts a server session. The server verifies the password with Argon2id; for // an unknown email it verifies against a fixed dummy hash, so the response time does not reveal // whether the account exists. An unknown email and a wrong password both answer 401 // invalid_credentials. // // Correct credentials for an unverified email answer 403 email_not_verified and create no session. // This reveals the verification state only to someone who already knows the password, which proves // more than the state itself; the client offers to resend the link. // // On success the server revokes the session that the request carried, if any, creates a new random // session in PostgreSQL with a new identifier and a new CSRF token, sets the HttpOnly session cookie, // and returns the account and the CSRF token. The new session follows the idle and absolute timeouts // of the sessionCookie scheme. The client keeps the token in memory and sends it in X-CSRF-Token with // every mutating request that requires a session. // // Login is rate-limited per client and per email and answers 429 with Retry-After. Like every unsafe // request, it requires an allowed Origin, which protects against login CSRF, and answers 403 // csrf_check_failed otherwise. // // POST /api/v1/identity/sessions func (s *Server) handleLoginRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("Login"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/identity/sessions"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), LoginOperation, 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: LoginOperation, ID: "Login", } ) var rawBody []byte request, rawBody, close, err := s.decodeLoginRequest(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 LoginRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: LoginOperation, OperationSummary: "Sign in with email and password and start a session.", OperationID: "Login", Body: request, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = *LoginRequest Params = struct{} Response = LoginRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.Login(ctx, request) return response, err }, ) } else { response, err = s.h.Login(ctx, request) } 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 := encodeLoginResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleLogoutRequest handles Logout operation. // // Requires the session cookie and the CSRF token of that session in X-CSRF-Token, and an allowed // Origin. The server revokes the session in PostgreSQL, so the cookie value stops working even if a // copy remains, and clears the cookie. A missing, expired, or revoked session answers 401 // unauthenticated and also clears the cookie, so a stale cookie does not stay in the browser; a // missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed and keeps the // session and the cookie. The client clears its private query cache after the response. // // DELETE /api/v1/identity/sessions/current func (s *Server) handleLogoutRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("Logout"), semconv.HTTPRequestMethodKey.String("DELETE"), semconv.HTTPRouteKey.String("/api/v1/identity/sessions/current"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), LogoutOperation, 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: LogoutOperation, ID: "Logout", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, LogoutOperation, 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, LogoutOperation, 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 } } var rawBody []byte var response LogoutRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: LogoutOperation, OperationSummary: "Sign out and revoke the current session.", OperationID: "Logout", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = LogoutRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.Logout(ctx) return response, err }, ) } else { response, err = s.h.Logout(ctx) } 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 := encodeLogoutResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleRaiseOrganizationInvitationSalaryRequest handles RaiseOrganizationInvitationSalary operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF // token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only // the owner of the organization changes invitations. // // After sending, the salary base is fixed and the lower bound never decreases; the upper bound may be // raised exactly once in the whole history of the invitation (PRD FR13). The body carries only the new // `salary_to`, so the request cannot change the lower bound, the currency, the period, or the tax // basis. The new bound must be above the current one and keep the width of the range from 10% to 40% // of its midpoint, otherwise 400 validation_failed with the pointer `/salary_to`. The raise creates // the next terms version with every other term unchanged and the next invitation version; the // candidate sees the new terms, and an acceptance that names the previous terms version answers 412 // version_conflict. The deadline does not change. The raise follows its own once-only rule and does // not count against the organization-wide daily limit of three range settings, but it counts against // the withheld counter of `salary_fit` (five settings within seven days), because it moves the upper // bound that the indicator compares. // // Allowed in `delivered`, `viewed`, and `accepted`, and in the planned states `counter`, // `interview_scheduled`, `interviewed`, and `no_deal`, where FR13 lets a raise open an early repeated // final. During `negotiation`, after `terms_agreed`, in a terminal state, in a `draft` (change the // draft instead), and after the raise was used, the server answers 409 state_conflict. A raise after // an acceptance changes neither the accepted terms version of the grant nor the grant. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a raise to the same `salary_to` that was already applied answers 200 with the current invitation // even with a new key or an older `expected_version`. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 // forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 // not_found, after any due expiry), the repeat of an applied raise (200), a terminal state (409 // state_conflict, whatever the version), the version (412), any other state that does not allow a // raise and the used raise (409 state_conflict), then the bound and the width (400). The general rate // limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under // the key; 400, 412, and 429 are not. // // POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise func (s *Server) handleRaiseOrganizationInvitationSalaryRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("RaiseOrganizationInvitationSalary"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), RaiseOrganizationInvitationSalaryOperation, 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: RaiseOrganizationInvitationSalaryOperation, ID: "RaiseOrganizationInvitationSalary", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, RaiseOrganizationInvitationSalaryOperation, 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, RaiseOrganizationInvitationSalaryOperation, 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 := decodeRaiseOrganizationInvitationSalaryParams(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.decodeRaiseOrganizationInvitationSalaryRequest(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 RaiseOrganizationInvitationSalaryRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: RaiseOrganizationInvitationSalaryOperation, OperationSummary: "Raise the upper salary bound of a sent invitation once.", OperationID: "RaiseOrganizationInvitationSalary", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "invitation_id", In: "path", }: params.InvitationID, { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *InvitationSalaryRaise Params = RaiseOrganizationInvitationSalaryParams Response = RaiseOrganizationInvitationSalaryRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackRaiseOrganizationInvitationSalaryParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.RaiseOrganizationInvitationSalary(ctx, request, params) return response, err }, ) } else { response, err = s.h.RaiseOrganizationInvitationSalary(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 := encodeRaiseOrganizationInvitationSalaryResponse(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 // sends the email, the password, the chosen scenario, and consent C1 with the version of the text the // user accepted. // // The answer is the same 202 whether the email is new, registered but not verified, or verified, so // registration does not enumerate accounts: // // - New email: the server creates an unverified account with the scenario and the first onboarding // step, records C1 with its text version and text hash, stores only the hash of a one-time // verification token plus the pending registration credentials, and queues the verification // message, all in one transaction. // - Registered but not verified: the server treats the request as a new registration of that address. // In one transaction it advances the registration version, replaces the C1 record, invalidates // every earlier verification token, and queues a message with a new token carrying the pending // password hash, scenario, and onboarding step. The account's saved credentials and scenario change // only when the address owner confirms that token with its registration password, so a // pre-registration with someone else's password cannot take over the account. // - Verified: nothing changes. The server may queue a rate-limited "you already have an account" // notice to the address. // // Every verification token is bound to the registration version it was issued for, so a token issued // before a re-registration can never confirm the newer credentials. An account that stays unverified // is deleted with its consent record and tokens 7 days after its last registration (planned value from // configuration). Verification tokens live 24 hours (planned value from configuration). // // The response does not depend on the branch in content or timing. Before it looks up the email, the // server validates the whole body, including the password bounds after normalization, the password // blocklist, and the C1 version, and it computes the Argon2id hash on every branch; a 400 therefore // never depends on whether the email exists. Mail is delivered asynchronously from the outbox. // // The operation requires Idempotency-Key. For this anonymous operation the key is scoped by the // operation, the key, and an HMAC of the normalized email, and the request fingerprint is an // HMAC-SHA-256 with a server secret over the canonical JSON body. The server never stores the body, // the password, or a plain hash of either; the secret keeps the fingerprint from serving as an offline // password check. A retry with the same key, email, and body replays the stored 202 without a second // message; the same key and email with a different body answers 422 idempotency_key_reused. // // It is rate-limited per client and per email and answers 429 with Retry-After when the limit is // reached. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed // otherwise. // // POST /api/v1/identity/registrations func (s *Server) handleRegisterAccountRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("RegisterAccount"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/identity/registrations"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), RegisterAccountOperation, 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: RegisterAccountOperation, ID: "RegisterAccount", } ) params, err := decodeRegisterAccountParams(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.decodeRegisterAccountRequest(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 RegisterAccountRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: RegisterAccountOperation, OperationSummary: "Register an account by email with a scenario and consent C1.", OperationID: "RegisterAccount", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *RegistrationRequest Params = RegisterAccountParams Response = RegisterAccountRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackRegisterAccountParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.RegisterAccount(ctx, request, params) return response, err }, ) } else { response, err = s.h.RegisterAccount(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 := encodeRegisterAccountResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleRequestMyAccountDeletionRequest handles RequestMyAccountDeletion operation. // // Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The // subject comes from the session. In one transaction, revokes any active C1 record, creates or returns // the subject's active durable deletion request, and writes the outbox intent. The API does not delete // the account synchronously. Repeating the request returns the same active request; a later C1 grant // never cancels it. // // POST /api/v1/me/account-deletion-requests func (s *Server) handleRequestMyAccountDeletionRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("RequestMyAccountDeletion"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/account-deletion-requests"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), RequestMyAccountDeletionOperation, 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: RequestMyAccountDeletionOperation, ID: "RequestMyAccountDeletion", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, RequestMyAccountDeletionOperation, 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, RequestMyAccountDeletionOperation, 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 } } var rawBody []byte var response RequestMyAccountDeletionRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: RequestMyAccountDeletionOperation, OperationSummary: "Revoke C1 and request account deletion.", OperationID: "RequestMyAccountDeletion", Body: nil, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = struct{} Params = struct{} Response = RequestMyAccountDeletionRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.RequestMyAccountDeletion(ctx) return response, err }, ) } else { response, err = s.h.RequestMyAccountDeletion(ctx) } 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 := encodeRequestMyAccountDeletionResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleResendEmailVerificationRequest handles ResendEmailVerification operation. // // Public operation without a session. The answer is the same 202 for an unknown email, a verified // email, and an unverified one, so it does not enumerate accounts. Only for an unverified account does // the server issue a new one-time token bound to the current registration version, invalidate every // earlier token of that account, and queue the message. Resend never changes the password, the // scenario, or the consent record; a user who did not start the pending registration registers again // instead, which replaces it. // // It is rate-limited per client and per email and answers 429 with Retry-After when the limit is // reached. A retry is safe without Idempotency-Key: at worst it replaces the token again within the // rate limit. Like every unsafe request, it requires an allowed Origin and answers 403 // csrf_check_failed otherwise. // // POST /api/v1/identity/email-verification-requests func (s *Server) handleResendEmailVerificationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ResendEmailVerification"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/identity/email-verification-requests"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ResendEmailVerificationOperation, 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: ResendEmailVerificationOperation, ID: "ResendEmailVerification", } ) var rawBody []byte request, rawBody, close, err := s.decodeResendEmailVerificationRequest(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 ResendEmailVerificationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ResendEmailVerificationOperation, OperationSummary: "Request a new email verification link.", OperationID: "ResendEmailVerification", Body: request, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = *EmailVerificationResendRequest Params = struct{} Response = ResendEmailVerificationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ResendEmailVerification(ctx, request) return response, err }, ) } else { response, err = s.h.ResendEmailVerification(ctx, request) } 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 := encodeResendEmailVerificationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleRevokeMyConsentRequest handles RevokeMyConsent operation. // // Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured // Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5, // including superseded records, and never changes another purpose. Repeating a revocation is harmless // and creates no duplicate event. // // Revoking c2 immediately closes the stored publication and records privacy history in the same // transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not // reopen publication or restore old grants. Revoking c3 does not block the manual assessment path. // Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent; // an external FSP deletion adapter is not available yet. // // DELETE /api/v1/me/consents/{purpose} func (s *Server) handleRevokeMyConsentRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("RevokeMyConsent"), semconv.HTTPRequestMethodKey.String("DELETE"), semconv.HTTPRouteKey.String("/api/v1/me/consents/{purpose}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), RevokeMyConsentOperation, 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: RevokeMyConsentOperation, ID: "RevokeMyConsent", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, RevokeMyConsentOperation, 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, RevokeMyConsentOperation, 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 := decodeRevokeMyConsentParams(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 RevokeMyConsentRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: RevokeMyConsentOperation, OperationSummary: "Revoke a non-scoped consent from settings.", OperationID: "RevokeMyConsent", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "purpose", In: "path", }: params.Purpose, }, Raw: r, } type ( Request = struct{} Params = RevokeMyConsentParams Response = RevokeMyConsentRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackRevokeMyConsentParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.RevokeMyConsent(ctx, params) return response, err }, ) } else { response, err = s.h.RevokeMyConsent(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 := encodeRevokeMyConsentResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleRevokeMyOrganizationContactConsentRequest handles RevokeMyOrganizationContactConsent operation. // // Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured // Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The // server revokes every unrevoked C4 record for this subject and organization, using the fields stored // on those records to request downstream grant revocation. It does not affect another organization. // Repeating the request is harmless and creates no duplicate event. // // DELETE /api/v1/me/consents/c4/organizations/{org_id} func (s *Server) handleRevokeMyOrganizationContactConsentRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("RevokeMyOrganizationContactConsent"), semconv.HTTPRequestMethodKey.String("DELETE"), semconv.HTTPRouteKey.String("/api/v1/me/consents/c4/organizations/{org_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), RevokeMyOrganizationContactConsentOperation, 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: RevokeMyOrganizationContactConsentOperation, ID: "RevokeMyOrganizationContactConsent", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, RevokeMyOrganizationContactConsentOperation, 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, RevokeMyOrganizationContactConsentOperation, 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 := decodeRevokeMyOrganizationContactConsentParams(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 RevokeMyOrganizationContactConsentRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: RevokeMyOrganizationContactConsentOperation, OperationSummary: "Revoke C4 for one organization.", OperationID: "RevokeMyOrganizationContactConsent", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, }, Raw: r, } type ( Request = struct{} Params = RevokeMyOrganizationContactConsentParams Response = RevokeMyOrganizationContactConsentRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackRevokeMyOrganizationContactConsentParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.RevokeMyOrganizationContactConsent(ctx, params) return response, err }, ) } else { response, err = s.h.RevokeMyOrganizationContactConsent(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 := encodeRevokeMyOrganizationContactConsentResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleSaveMyProfileRequest handles SaveMyProfile operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. The body is the complete new state of every field and list; see // CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole. // // Every field is optional in substance: a profile can be saved with any subset filled and the rest // null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or // link. A successful save advances an account whose current onboarding step is candidate_profile to // candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update // is atomic with the profile and its history. // // Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion // keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level, // confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed // grade never becomes a confirmed grade or a category. // // Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, // 0 for the first save. If it is not the current version, the server answers 412 version_conflict and // changes nothing, and the client reads the profile again and reapplies its edits, so a concurrent // edit from another tab or device is never lost silently. The version travels in the body rather than // in If-Match because the generated client cannot read the ETag response header yet, as for the // questionnaire; the status and code are the same as for a failed If-Match. // // The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose // values equal the stored ones, with the same decisions, changes nothing, keeps the version, and // answers 200 with the current profile even when `expected_version` is older, so a retry after a lost // response of a successful save succeeds instead of failing with 412. A version above the current one // never existed and always answers 412 version_conflict, even for an unchanged body. // // The save replaces the stored claims as a whole. A suggestion that an import stored and that the // client did not render and send back with the decision `extracted` is dropped by the save; a client // therefore sends every suggestion that it received, and a client that read an older version gets 412 // instead of silently dropping a suggestion it never saw. // // Experience periods use inclusive calendar months. An overlap is allowed only when // `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel // work. Each acknowledgement names two distinct experience indices and repeats their exact normalized // `started_on` and `ended_on` values; both indices and periods must match the submitted array and // `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries // an earlier acknowledgement only when the same two indices still contain the same dates; reordering // or changing either date requires a new acknowledgement. Editing other experience fields does not // invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers // to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping // acknowledgements are invalid. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), a version above the current one (412), domain // rules that depend on the body alone (400), then the rules that depend on the stored claims against // the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when // `expected_version` is stale, because another save may have confirmed that value, and 400 when it is // current; an unchanged body (200); any other change over a stale version (412). The schema rejects an // unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username // without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is // not a positive multiple of 1000, and more items than a list allows. The server also rejects a // repeated tag, skill, or role specialization, a period that ends before it starts or lies in the // future, a changed overlap without explicit confirmation, and a decision `extracted` for a value that // is not a stored suggestion, with 400 validation_failed and pointers to the items, for example // `/roles/1/specialization` or `/stack/1/status`. Error bodies never repeat a submitted value. // // PUT /api/v1/me/profile func (s *Server) handleSaveMyProfileRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("SaveMyProfile"), semconv.HTTPRequestMethodKey.String("PUT"), semconv.HTTPRouteKey.String("/api/v1/me/profile"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), SaveMyProfileOperation, 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: SaveMyProfileOperation, ID: "SaveMyProfile", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, SaveMyProfileOperation, 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, SaveMyProfileOperation, 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 } } var rawBody []byte request, rawBody, close, err := s.decodeSaveMyProfileRequest(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 SaveMyProfileRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: SaveMyProfileOperation, OperationSummary: "Replace the private profile of the current candidate.", OperationID: "SaveMyProfile", Body: request, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = *CandidateProfileUpdate Params = struct{} Response = SaveMyProfileRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.SaveMyProfile(ctx, request) return response, err }, ) } else { response, err = s.h.SaveMyProfile(ctx, request) } 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 := encodeSaveMyProfileResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleSaveMyQuestionnaireRequest handles SaveMyQuestionnaire operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. The body is the complete new state: one or two specializations, each with a // self-assessed grade, task languages, stack tags, and stated experience or null, and the working // context. It replaces the stored questionnaire as a whole. // // Self-assessment is a claim. It influences where the assessment starts and which grade the assessment // step offers first, but it adds no points and never writes a confirmed grade or a category: a // self-assessed `senior`, or the word "Senior" in a stack tag, never assigns the Senior category. A // real profile stays invisible to employers until an assessment confirms a category. Choosing a // specialization whose test is `in_development` is allowed; no assessment starts for it until its bank // is published. Removing a specialization from the questionnaire does not change assessment results. // // Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, // 0 for the first save. If it is not the current version, the server answers 412 version_conflict and // changes nothing; the client reads the questionnaire again. The version travels in the body rather // than in If-Match because the generated client cannot read the ETag response header yet. The status // and code are the same as for a failed If-Match, since the client action is the same. // // The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose // specializations and working context equal the stored ones changes nothing, keeps the version, and // answers 200 with the current questionnaire even when `expected_version` is older, so a retry after a // lost response of a successful save succeeds instead of failing with 412. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), domain rules (400), then the version (412). The // schema rejects more than two specializations, an unknown grade, specialization, or task language, // and unknown fields. The server also rejects a repeated specialization and a task language that the // specialization's published bank does not offer, with 400 validation_failed and pointers to the // items, for example `/specializations/1/specialization` or `/specializations/0/task_languages/0`. // // A successful save on the onboarding step candidate_questionnaire advances the account to // candidate_assessment (planned). // // PUT /api/v1/me/questionnaire func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("SaveMyQuestionnaire"), semconv.HTTPRequestMethodKey.String("PUT"), semconv.HTTPRouteKey.String("/api/v1/me/questionnaire"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), SaveMyQuestionnaireOperation, 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: SaveMyQuestionnaireOperation, ID: "SaveMyQuestionnaire", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, SaveMyQuestionnaireOperation, 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, SaveMyQuestionnaireOperation, 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 } } var rawBody []byte request, rawBody, close, err := s.decodeSaveMyQuestionnaireRequest(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 SaveMyQuestionnaireRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: SaveMyQuestionnaireOperation, OperationSummary: "Replace the questionnaire of the current candidate.", OperationID: "SaveMyQuestionnaire", Body: request, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = *CandidateQuestionnaireUpdate Params = struct{} Response = SaveMyQuestionnaireRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.SaveMyQuestionnaire(ctx, request) return response, err }, ) } else { response, err = s.h.SaveMyQuestionnaire(ctx, request) } 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 := encodeSaveMyQuestionnaireResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleSendOrganizationInvitationRequest handles SendOrganizationInvitation operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF // token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only // the owner of the organization sends invitations. // // Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in // one transaction the server records the delivery, creates the candidate's inbox entry, starts the // deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the // weekly organization quota, and writes the outbox event for the notification, then answers 200 with // the state `delivered`. A successful answer therefore means the candidate can already read the // invitation; an email is a separate notification that never blocks or delays it, and its retries // never move the deadline. No contact of the candidate is disclosed by sending. // // The server checks again that the candidate is still visible to the organization: a revoked // publication C2 or a profile hidden from the organization answers 409 state_conflict without telling // which. It also enforces the limits of the product policy: at most 20 invitations waiting for an // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, // both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and // Retry-After. Enforcement of the pending limit and the organization quota is planned. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current // state even with a new key or an older `expected_version`; the quota is spent once. A stale // `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it // did not read. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 // forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 // not_found), the repeat of a completed send (200), the version (412), the state, the visibility of // the candidate, the pending limit and the pause (409 state_conflict), then the quota (429). 404 and // 409 state_conflict are stored under the key; 400, 412, and 429 are not. // // POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send func (s *Server) handleSendOrganizationInvitationRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("SendOrganizationInvitation"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}/send"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), SendOrganizationInvitationOperation, 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: SendOrganizationInvitationOperation, ID: "SendOrganizationInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, SendOrganizationInvitationOperation, 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, SendOrganizationInvitationOperation, 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 := decodeSendOrganizationInvitationParams(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.decodeSendOrganizationInvitationRequest(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 SendOrganizationInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: SendOrganizationInvitationOperation, OperationSummary: "Send a draft to the candidate's inbox.", OperationID: "SendOrganizationInvitation", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "invitation_id", In: "path", }: params.InvitationID, { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *InvitationCommand Params = SendOrganizationInvitationParams Response = SendOrganizationInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackSendOrganizationInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.SendOrganizationInvitation(ctx, request, params) return response, err }, ) } else { response, err = s.h.SendOrganizationInvitation(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 := encodeSendOrganizationInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleSetMyPublicationRequest handles SetMyPublication operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. The body is the complete new publication setting: `state` `published` with // the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; // the search status and the hidden organizations stay as they were. // // Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger // (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of // the account and binds the publication to that record, so a client sends no consent identifier and // cannot forge one. Without one the server answers 409 state_conflict with the entry // `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every // other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and // then publishes. The server takes the C2 record under a share lock in the transaction that writes the // publication, so a revocation that races with a publication either commits first (the publication is // refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` // is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate // publishes again under the new record. The revocation path itself closes the stored publication and // revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 // was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the // grants as any closing does. Publishing, like every visibility change, needs a verified email (a // usecase requirement; the unverified account cleanup deletes only accounts without such records). // Publishing never adds a field that the body did not name, and a new `CardField` value is never // published for a candidate who did not choose it. // // The field set contains only the groups of `CardField`. The full name, contacts, and the lowest // salary have no value there, so no body can publish them. Only values that the candidate confirmed // ever reach the card. Contacts reach an organization only through the contact grant (C4), and a // profile that is published or closed changes none of the grants that exist; closing the publication, // and hiding an organization that holds a grant, revoke the contact grants concerned with the reason // `visibility_closed` in the same transaction as the change (planned together with the operations, see // the invitation contract). // // Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, // 0 for the first publication. If it is not the current version the server answers 412 // version_conflict and changes nothing. The version travels in the body rather than in If-Match // because the generated client cannot read the ETag header yet. A body that equals the stored setting // changes nothing, keeps the version, and answers 200 even when `expected_version` is older, so a // retry after a lost response succeeds without an Idempotency-Key. A version above the current one // never existed and always answers 412. Every change is recorded in the settings history with its // time, the fields, and the C2 record. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), a version above the current one (412), rules that // depend on the body alone (400), an unchanged body (200), a stale version (412), then the active C2 // for a publication (409 state_conflict). The schema rejects an unknown field, a repeated or unknown // card field, and more fields than there are groups; a published state with no field, and a closed // state with a field, answer 400 validation_failed with the pointer `/fields`. Error bodies never // repeat a submitted value. // // PUT /api/v1/me/privacy/publication func (s *Server) handleSetMyPublicationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("SetMyPublication"), semconv.HTTPRequestMethodKey.String("PUT"), semconv.HTTPRouteKey.String("/api/v1/me/privacy/publication"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), SetMyPublicationOperation, 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: SetMyPublicationOperation, ID: "SetMyPublication", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, SetMyPublicationOperation, 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, SetMyPublicationOperation, 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 } } var rawBody []byte request, rawBody, close, err := s.decodeSetMyPublicationRequest(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 SetMyPublicationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: SetMyPublicationOperation, OperationSummary: "Publish or close the anonymous candidate card.", OperationID: "SetMyPublication", Body: request, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = *PublicationUpdate Params = struct{} Response = SetMyPublicationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.SetMyPublication(ctx, request) return response, err }, ) } else { response, err = s.h.SetMyPublication(ctx, request) } 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 := encodeSetMyPublicationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleSetMySearchStatusRequest handles SetMySearchStatus operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. The body is the complete new status: `looking` ("Ищу") or `not_looking`. // The status is a statement of the candidate and never a consent. It changes neither the C2 consent, // nor the publication, nor the hidden organizations, and it does not close or open any contact grant; // a candidate whose profile is closed who sets `looking` becomes visible to no one. // // `looking` stores the moment of the confirmation and a lapse time. The server takes the interval from // the `search_status` section of the effective product policy (30 days in the demo policy, // `searching_confirmation_interval_days`), stores the policy version it used, and fixes the lapse time // then, so a later policy change moves no stored time. Setting `looking` again is the confirmation: it // replaces the confirmation time with now and advances the version, also after a lapse. The body // carries no time, interval, or policy version. // // After the lapse time the status holds as `not_looking` with `lapsed` true on the next read. The // lapse is computed and written nowhere, so it needs no job, it can never make the candidate more // visible, and it never touches the publication or the hidden organizations. A reminder before the // lapse is a planned notification, not a part of this operation. // // Optimistic concurrency uses `expected_version` in the body, 0 for a candidate who never set the // status; a stale or non-existent version answers 412 version_conflict and changes nothing. // `not_looking` over a stored `not_looking` changes nothing and answers 200 even with a stale version. // `looking` always changes the stored confirmation, so a retry of a confirmation whose response was // lost with the old version answers 412 and the client reads the status again. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), a version above the current one (412), an // unchanged `not_looking` (200), then a stale version (412). // // PUT /api/v1/me/privacy/search-status func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("SetMySearchStatus"), semconv.HTTPRequestMethodKey.String("PUT"), semconv.HTTPRouteKey.String("/api/v1/me/privacy/search-status"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), SetMySearchStatusOperation, 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: SetMySearchStatusOperation, ID: "SetMySearchStatus", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, SetMySearchStatusOperation, 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, SetMySearchStatusOperation, 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 } } var rawBody []byte request, rawBody, close, err := s.decodeSetMySearchStatusRequest(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 SetMySearchStatusRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: SetMySearchStatusOperation, OperationSummary: "Set or confirm the search status of the current candidate.", OperationID: "SetMySearchStatus", Body: request, RawBody: rawBody, Params: middleware.Parameters{}, Raw: r, } type ( Request = *SearchStatusUpdate Params = struct{} Response = SetMySearchStatusRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, nil, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.SetMySearchStatus(ctx, request) return response, err }, ) } else { response, err = s.h.SetMySearchStatus(ctx, request) } 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 := encodeSetMySearchStatusResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleStartMyAssessmentAttemptSessionRequest handles StartMyAssessmentAttemptSession operation. // // Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an // Idempotency-Key. The body carries the attempt version the candidate last read. The server checks // ownership, idempotency, and `expected_version` atomically before starting a session; a stale version // answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the // stored response. // // Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this // command to start the next session. Calling it while a session is already active returns the current // attempt without consuming another session or advancing its version. Starting a session advances the // version once. The command cannot extend `expires_at` or `chain_deadline`. // // If the attempt deadline or session budget has passed, this command commits the due terminal // transition and returns the resulting attempt. A pending practice submitted before the limit is // graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never // start a session or commit a due transition. A background transition may persist a due outcome // independently; after that, this command returns the stored terminal attempt without changing it. // // The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 // not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no // operation gives an employer answers, qualification evidence, or attempt history. // // POST /api/v1/me/assessment-attempts/{attempt_id}/sessions func (s *Server) handleStartMyAssessmentAttemptSessionRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("StartMyAssessmentAttemptSession"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/sessions"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), StartMyAssessmentAttemptSessionOperation, 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: StartMyAssessmentAttemptSessionOperation, ID: "StartMyAssessmentAttemptSession", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, StartMyAssessmentAttemptSessionOperation, 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, StartMyAssessmentAttemptSessionOperation, 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 := decodeStartMyAssessmentAttemptSessionParams(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.decodeStartMyAssessmentAttemptSessionRequest(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 StartMyAssessmentAttemptSessionRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: StartMyAssessmentAttemptSessionOperation, OperationSummary: "Start or resume a work session for the current candidate's attempt.", OperationID: "StartMyAssessmentAttemptSession", 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 = *AssessmentAttemptSessionStart Params = StartMyAssessmentAttemptSessionParams Response = StartMyAssessmentAttemptSessionRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackStartMyAssessmentAttemptSessionParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.StartMyAssessmentAttemptSession(ctx, request, params) return response, err }, ) } else { response, err = s.h.StartMyAssessmentAttemptSession(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 := encodeStartMyAssessmentAttemptSessionResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleSubmitMyAssessmentAnswerRequest handles SubmitMyAssessmentAnswer operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the // format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or // `practice`. It never carries a score, a duration, or a correctness flag; the server records the // times itself and scores the answer with the key of the fixed item instance. Time never enters the // ability estimate or the grade decision. // // The response is the attempt with the next item to answer. It never says whether the answer was // correct. Items are answered in order and each answer is final. // // A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate // calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command // never starts one or consumes session quota. Reading the attempt or result is always read-only. A // command that finds a due deadline transition may commit it before returning; a command that finds an // expired idle session answers 409 until the candidate explicitly starts the next session. // // Practice: an answer with format `practice` submits the solution of the main or the additional // practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the // response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. // Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or // seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or // memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure // could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so // hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the // public examples are unlimited apart from the sandbox rate limit and never show hidden group results; // they are planned as a separate operation. // // Repeats and conflicts, per item: // // - A retry with the same Idempotency-Key and body within 24 hours replays the stored response. // - Sending the answer already stored for the item again, even with a new key or an older // `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. // Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence // for `element_ids`, numeric equality for `number`, identical text without normalization for `text` // and `config`, and the same language with identical source for a practice. // - A different answer for an item that already has one answers 409 state_conflict when // `expected_version` is current; with a stale version the version check comes first and answers // 412. // - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A // submission with the same or a different solution, with the current `expected_version`, queues it // again and advances the version. // // Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the // server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is // the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is // kept for commands that the attempt state does not allow at the current 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), // the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline // transition may be committed, but this request never starts a work session), the repeat of the stored // answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state // (409 state_conflict: the attempt is terminal, the work session ended, the item is not current, the // item has a different answer, or the practice verdict is pending or finished), then the answer // against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following // the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; // 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. // // POST /api/v1/me/assessment-attempts/{attempt_id}/answers func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("SubmitMyAssessmentAnswer"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/answers"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), SubmitMyAssessmentAnswerOperation, 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: SubmitMyAssessmentAnswerOperation, ID: "SubmitMyAssessmentAnswer", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, SubmitMyAssessmentAnswerOperation, 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, SubmitMyAssessmentAnswerOperation, 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 := decodeSubmitMyAssessmentAnswerParams(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.decodeSubmitMyAssessmentAnswerRequest(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 SubmitMyAssessmentAnswerRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: SubmitMyAssessmentAnswerOperation, OperationSummary: "Answer the current item or submit a practice of an assessment attempt.", OperationID: "SubmitMyAssessmentAnswer", 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 = *AssessmentAnswerSubmission Params = SubmitMyAssessmentAnswerParams Response = SubmitMyAssessmentAnswerRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackSubmitMyAssessmentAnswerParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.SubmitMyAssessmentAnswer(ctx, request, params) return response, err }, ) } else { response, err = s.h.SubmitMyAssessmentAnswer(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 := encodeSubmitMyAssessmentAnswerResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleUnhideOrganizationRequest handles UnhideOrganization operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. Deletes the hiding record of the candidate for the organization in the path. // The request is idempotent: it answers 204 whether the organization was hidden, was not hidden, or // does not exist, so the operation reveals nothing about the organization, and a repeat after a lost // response succeeds. The record is deleted, the settings history keeps the event // `organization_unhidden` only when a record was deleted. // // Lifting the hiding makes the candidate readable by that organization again only if the profile is // published and the organization otherwise may read it. It changes neither the C2 consent, nor the // publication, nor the search status, and it never reopens a contact grant that the hiding closed. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the // path (400), account scenario (403 forbidden for an employer), then the deletion (204). // // DELETE /api/v1/me/privacy/hidden-organizations/{org_id} func (s *Server) handleUnhideOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("UnhideOrganization"), semconv.HTTPRequestMethodKey.String("DELETE"), semconv.HTTPRouteKey.String("/api/v1/me/privacy/hidden-organizations/{org_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), UnhideOrganizationOperation, 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: UnhideOrganizationOperation, ID: "UnhideOrganization", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, UnhideOrganizationOperation, 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, UnhideOrganizationOperation, 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 := decodeUnhideOrganizationParams(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 UnhideOrganizationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: UnhideOrganizationOperation, OperationSummary: "Lift the hiding of the candidate profile from one organization.", OperationID: "UnhideOrganization", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, }, Raw: r, } type ( Request = struct{} Params = UnhideOrganizationParams Response = UnhideOrganizationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackUnhideOrganizationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.UnhideOrganization(ctx, params) return response, err }, ) } else { response, err = s.h.UnhideOrganization(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 := encodeUnhideOrganizationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleUpdateOrganizationRequest handles UpdateOrganization operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF // token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the // organization (the FR07 matrix gives this to no other role), so a member with another role answers // 403 forbidden. The role comes from the server-side membership; the body has no organization, // membership, role, owner, or verification field. // // Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. // Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` // and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as // null become unset; `name`, `contacts`, and `representatives` cannot be null. // // The body can change the profile only. The verification level, its basis, the card, the members, and // every role are not fields of it, and unknown fields fail validation, so the owner can neither raise // the trust level of the organization nor the rights of anyone by editing the profile; a longer // description, a verified-looking website, or a new representative leaves the level unchanged. The // level and the roles change only through processes of the server. // // Versions: every committed change creates version `expected_version + 1` and answers 200 with the // organization. `expected_version` is the `version` the client read; when it is not current, the // server answers 412 version_conflict and changes nothing, and the client reads the organization again // and reapplies its edits. The version travels in the body rather than in If-Match because the // generated client cannot read the ETag response header yet, as for needs. A body that changes nothing // when applied to the current profile keeps the version and answers 200 with the current organization // even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a // change that already succeeded is harmless. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403 // forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer // such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can // answer 429 with Retry-After before any check. // // PATCH /api/v1/organizations/{org_id} func (s *Server) handleUpdateOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("UpdateOrganization"), semconv.HTTPRequestMethodKey.String("PATCH"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateOrganizationOperation, 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: UpdateOrganizationOperation, ID: "UpdateOrganization", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, UpdateOrganizationOperation, 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, UpdateOrganizationOperation, 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 := decodeUpdateOrganizationParams(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.decodeUpdateOrganizationRequest(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 UpdateOrganizationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: UpdateOrganizationOperation, OperationSummary: "Change the profile of an organization.", OperationID: "UpdateOrganization", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, }, Raw: r, } type ( Request = *OrganizationUpdate Params = UpdateOrganizationParams Response = UpdateOrganizationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackUpdateOrganizationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.UpdateOrganization(ctx, request, params) return response, err }, ) } else { response, err = s.h.UpdateOrganization(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 := encodeUpdateOrganizationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleUpdateOrganizationInvitationRequest handles UpdateOrganizationInvitation operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF // token of that session in X-CSRF-Token, and an allowed Origin. The body has no organization, // membership, or role field. In the MVP only the owner of the organization changes drafts. // // Only a `draft` can change; any other state answers 409 state_conflict. After sending, the only // change of the terms is the one raise of the upper salary bound through // RaiseOrganizationInvitationSalary. The candidate of a draft cannot change: a draft for another // candidate is a new draft. // // Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. // Each field present replaces that field as a whole and an absent field stays unchanged. `terms` is // always sent complete and replaces the terms as a whole, with the same validation as on creation, so // a package condition is never dropped by omission. `need` sent as null unlinks the need. // // Versions: every committed change creates version `expected_version + 1`; a change of the terms also // creates the next terms version, an immutable snapshot, and a change of anything else keeps the terms // version. `expected_version` is the `version` the client read; when it is not current, the server // answers 412 version_conflict and changes nothing, and the client reads the invitation again. The // version travels in the body because the generated client cannot read the ETag response header yet. // The operation needs no Idempotency-Key: a body that changes nothing when applied to the current // version, such as a retry of a change that already succeeded, keeps the version and answers 200 with // the current invitation even when `expected_version` is older. // // Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of // either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the // candidate's minimum for the offered formats, and switching formats or the basis would otherwise // probe the minimum for free. Such a change counts against the limit shared by the organization with // needs and other drafts, at most three settings a day, and against the withheld counter, which // withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, // enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with // Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not // count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a // body that changes nothing answers 200. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 // forbidden), the invitation (404 not_found), a body that changes nothing (200), the version (412), // the state (409 state_conflict), domain rules (400 with the pointers of // CreateOrganizationInvitation), then the salary limit (429). // // PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id} func (s *Server) handleUpdateOrganizationInvitationRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("UpdateOrganizationInvitation"), semconv.HTTPRequestMethodKey.String("PATCH"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateOrganizationInvitationOperation, 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: UpdateOrganizationInvitationOperation, ID: "UpdateOrganizationInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, UpdateOrganizationInvitationOperation, 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, UpdateOrganizationInvitationOperation, 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 := decodeUpdateOrganizationInvitationParams(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.decodeUpdateOrganizationInvitationRequest(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 UpdateOrganizationInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: UpdateOrganizationInvitationOperation, OperationSummary: "Change the terms, the need link, or the response period of a draft.", OperationID: "UpdateOrganizationInvitation", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "invitation_id", In: "path", }: params.InvitationID, }, Raw: r, } type ( Request = *OrganizationInvitationUpdate Params = UpdateOrganizationInvitationParams Response = UpdateOrganizationInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackUpdateOrganizationInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.UpdateOrganizationInvitation(ctx, request, params) return response, err }, ) } else { response, err = s.h.UpdateOrganizationInvitation(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 := encodeUpdateOrganizationInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleUpdateOrganizationNeedRequest handles UpdateOrganizationNeed operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF // token of that session in X-CSRF-Token, and an allowed Origin. The organization and the role come // from the server-side membership; the body has no organization, membership, or role field. In the MVP // only the owner of the organization changes needs; the technical expert, who may refine the // requirements of assigned needs under PRD FR07, is planned. // // Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. // Each field present replaces that field as a whole and an absent field stays unchanged; a field // decision and each list are replaced entirely and never merged. This keeps every field one optional // value in the generated server and client, without nested partial updates. // // Each requirement field is sent as a decision `{value, status}` and each list item as // `{name or text, status}`, so confirmation is always explicit: // // - Confirm a suggestion: send its stored value with `confirmed`. It keeps its origin and quote. // - Keep a suggestion open: send its stored value with `extracted`, or leave the field out. // `extracted` with any other value, or for a field or item without a stored suggestion, answers 400 // with the pointer of that `status`, for example `/grade/status` or `/required_skills/2/status`. A // client that sends back an unchanged form therefore never confirms a suggestion by accident. // - Change: send another value with `confirmed`. It becomes a confirmed manual value, and its quote // is dropped. // - Delete: send null for a nullable field, which makes it `unknown` (or unlinks `vacancy_id`), or // leave the item out of a skill or task list, which deletes it. An empty skill or task list deletes // every item; a list sent as null answers 400. A deleted requirement really changes the // requirements that search uses, not only an explanation, and a deleted suggestion is not proposed // again by a later extraction. // - Text: a different `source_text` extracts again. New suggestions replace only the `extracted` // values and items of the fields not named in the body; confirmed values are never overwritten, and // a suggested skill whose name is already in either skill list is skipped. Null removes the text // and keeps every value. // // Versions: every committed change creates version `expected_version + 1` as an immutable snapshot and // answers 200 with it. `requirements_version` becomes the new version only when a confirmed // requirement was confirmed, changed, or removed. `expected_version` is the `version` the client read; // when it is not current, the server answers 412 version_conflict and changes nothing, and the client // reads the need again and reapplies its unsaved edits. The version travels in the body rather than in // If-Match because the generated client cannot read the ETag response header yet, as for the // questionnaire. Concurrent changes therefore never overwrite each other silently. // // The operation needs no Idempotency-Key: a body that changes nothing when applied to the current // version, such as a retry of a change that already succeeded, keeps the version and answers 200 with // the current need even when `expected_version` is older. An incomplete need is a valid result; // `readiness.missing_fields` tells what remains. // // Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting // or changing a confirmed salary range counts against a limit shared by the whole organization, every // member and every need, together with ranges set on creation: at most three a day (PRD FR13, // enforcement planned). Over the limit the server answers 429 with Retry-After and changes nothing. // After five settings within seven days the money component is `withheld` for seven days. Repeated // range changes also feed the private organization risk signals. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 // forbidden), the need (404 not_found), a body that changes nothing (200), the version (412), domain // rules (400 with a pointer such as `/salary/value/salary_to` for a range whose lower bound is not // below the upper one or whose width is outside 10-40%, `/desired_skills/0/name` for a skill that is // also in the required list, `/grade/status` or `/required_skills/2/status` for `extracted` with a // value that is not the stored suggestion, or `/vacancy_id`), then the salary change limit (429). The // schema rejects a missing or non-positive `expected_version`, unknown fields such as `rec_score`, // `members`, `candidate_minimum`, or `version`, a field sent as a bare value instead of // `{value, status}`, a list sent as null, a salary bound that is not a positive multiple of 1000, and // an unknown currency, period, or tax basis. // // PATCH /api/v1/organizations/{org_id}/needs/{need_id} func (s *Server) handleUpdateOrganizationNeedRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("UpdateOrganizationNeed"), semconv.HTTPRequestMethodKey.String("PATCH"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/needs/{need_id}"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateOrganizationNeedOperation, 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: UpdateOrganizationNeedOperation, ID: "UpdateOrganizationNeed", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, UpdateOrganizationNeedOperation, 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, UpdateOrganizationNeedOperation, 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 := decodeUpdateOrganizationNeedParams(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.decodeUpdateOrganizationNeedRequest(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 UpdateOrganizationNeedRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: UpdateOrganizationNeedOperation, OperationSummary: "Confirm, change, or delete requirements of a need.", OperationID: "UpdateOrganizationNeed", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "need_id", In: "path", }: params.NeedID, }, Raw: r, } type ( Request = *NeedUpdate Params = UpdateOrganizationNeedParams Response = UpdateOrganizationNeedRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackUpdateOrganizationNeedParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.UpdateOrganizationNeed(ctx, request, params) return response, err }, ) } else { response, err = s.h.UpdateOrganizationNeed(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 := encodeUpdateOrganizationNeedResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleViewMyInvitationRequest handles ViewMyInvitation operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. The candidate comes from the session. The request has no body. // // The view transition of PRD FR12 is an explicit command, so reading the invitation with // GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms // screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances // `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the // terminal states, it changes nothing and answers 200 with the current invitation. A view never // reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and // `viewed_at`. // // The command is idempotent by its effect: the first view wins and every repeat returns the current // invitation. It therefore needs no Idempotency-Key and no `expected_version`: a view must never fail // because the invitation changed after the client read it, for example after a salary raise. A view at // the deadline or later first applies the due expiry and answers 200 with `expired`. // // The general rate limit can answer 429 with Retry-After before any check. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or // wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers // 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown identifier all // answer 404 not_found. An `invitation_id` that is not a UUID answers 400 validation_failed with the // path pointer. // // POST /api/v1/me/invitations/{invitation_id}/view func (s *Server) handleViewMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("ViewMyInvitation"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}/view"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), ViewMyInvitationOperation, 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: ViewMyInvitationOperation, ID: "ViewMyInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, ViewMyInvitationOperation, 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, ViewMyInvitationOperation, 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 := decodeViewMyInvitationParams(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 ViewMyInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: ViewMyInvitationOperation, OperationSummary: "Record that the current candidate opened the terms of an invitation.", OperationID: "ViewMyInvitation", Body: nil, RawBody: rawBody, Params: middleware.Parameters{ { Name: "invitation_id", In: "path", }: params.InvitationID, }, Raw: r, } type ( Request = struct{} Params = ViewMyInvitationParams Response = ViewMyInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackViewMyInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.ViewMyInvitation(ctx, params) return response, err }, ) } else { response, err = s.h.ViewMyInvitation(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 := encodeViewMyInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } } // handleWithdrawOrganizationInvitationRequest handles WithdrawOrganizationInvitation operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF // token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only // the owner of the organization withdraws invitations. // // Moves an unfinished invitation to the terminal state `withdrawn` (PRD FR12): a `draft`, which the // candidate never sees, a `delivered` or `viewed` invitation before the answer, an `accepted` one, and // the planned stages up to `negotiation`. The process closes and no further transition happens in it. // Withdrawing a delivered invitation frees its place in the pending limit of the need but never // returns the weekly quota. Withdrawing never revokes the consent C4 or a grant that already exists: // an accepted invitation keeps its `contact_access`, because only the candidate closes the access, by // revoking C4, cancelling the participation, or closing the visibility. // // `withdrawn` differs from `cancelled_by_candidate`: the organization withdraws, and the grant stays; // the candidate cancels through CancelMyInvitation, and the grant of this invitation is revoked. A // terminal invitation (`declined`, `expired`, `cancelled_by_candidate`) answers 409 state_conflict, // even with a stale `expected_version`, so the organization sees the final state at once. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a withdrawal of an invitation that is already `withdrawn` answers 200 with it even with a new // key or an older `expected_version`. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 // forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 // not_found, after any due expiry), the repeat on a withdrawn invitation (200), a terminal state (409 // state_conflict, whatever the version), then the version (412). The general rate limit can answer 429 // with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, // and 429 are not. // // POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw func (s *Server) handleWithdrawOrganizationInvitationRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ otelogen.OperationID("WithdrawOrganizationInvitation"), semconv.HTTPRequestMethodKey.String("POST"), semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. ctx, span := s.cfg.Tracer.Start(r.Context(), WithdrawOrganizationInvitationOperation, 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: WithdrawOrganizationInvitationOperation, ID: "WithdrawOrganizationInvitation", } ) { type bitset = [1]uint8 var satisfied bitset { sctx, ok, err := s.securitySessionCookie(ctx, WithdrawOrganizationInvitationOperation, 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, WithdrawOrganizationInvitationOperation, 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 := decodeWithdrawOrganizationInvitationParams(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.decodeWithdrawOrganizationInvitationRequest(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 WithdrawOrganizationInvitationRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, OperationName: WithdrawOrganizationInvitationOperation, OperationSummary: "Withdraw an invitation.", OperationID: "WithdrawOrganizationInvitation", Body: request, RawBody: rawBody, Params: middleware.Parameters{ { Name: "org_id", In: "path", }: params.OrgID, { Name: "invitation_id", In: "path", }: params.InvitationID, { Name: "Idempotency-Key", In: "header", }: params.IdempotencyKey, }, Raw: r, } type ( Request = *InvitationCommand Params = WithdrawOrganizationInvitationParams Response = WithdrawOrganizationInvitationRes ) response, err = middleware.HookMiddleware[ Request, Params, Response, ]( m, mreq, unpackWithdrawOrganizationInvitationParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { response, err = s.h.WithdrawOrganizationInvitation(ctx, request, params) return response, err }, ) } else { response, err = s.h.WithdrawOrganizationInvitation(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 := encodeWithdrawOrganizationInvitationResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) } return } }