feat: add assessment, privacy and support flows

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

No files matched your search

@@ -2503,9 +2503,10 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
//
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
// a stale version.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
@@ -4057,21 +4058,22 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped
// handleGetMyCardPreviewRequest handles GetMyCardPreview operation.
//
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
// the candidate does not hide the profile from would read it now, built from the current profile, the
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
// `Cache-Control: no-store`.
//
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
// never shown to an organization. While the profile is closed `card` is null. `card` is
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
// or account or profile identifier, and each property is null when it is not published or has no
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
// The self-assessed grade is not a category and never appears; categories come only from assessment
// results.
// The preview creates no view or access record and is never shown to an organization. While the
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
// generalize or suppress the card when an organization reads it.
//
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
// formats appear only through their separate explicit publication choices, and self-assessment never
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
@@ -5713,6 +5715,234 @@ func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool,
}
}
// handleGetOrganizationCandidateCardRequest handles GetOrganizationCandidateCard operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization and membership come from the current server-side session and path, never from cached
// search data.
//
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
// projection. The server resolves it against the current visible cohort, rechecks active membership,
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
// a handle from another organization, a closed or revoked publication, a profile hidden from this
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
//
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
// available, are a separate operation and require the current explicit C4 grant and contact-access
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
// this read immediately. Republishing does not reopen an earlier contact grant.
//
// Every allowed employer card read is recorded in the access history and consumes the organization's
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
// Retry-After. The response is `Cache-Control: no-store`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
// validation_failed.
//
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
func (s *Server) handleGetOrganizationCandidateCardRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetOrganizationCandidateCard"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationCandidateCardOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: GetOrganizationCandidateCardOperation,
ID: "GetOrganizationCandidateCard",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationCandidateCardOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeGetOrganizationCandidateCardParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response GetOrganizationCandidateCardRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetOrganizationCandidateCardOperation,
OperationSummary: "Read one currently visible anonymous candidate card.",
OperationID: "GetOrganizationCandidateCard",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
{
Name: "candidate_handle",
In: "path",
}: params.CandidateHandle,
},
Raw: r,
}
type (
Request = struct{}
Params = GetOrganizationCandidateCardParams
Response = GetOrganizationCandidateCardRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackGetOrganizationCandidateCardParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetOrganizationCandidateCard(ctx, params)
return response, err
},
)
} else {
response, err = s.h.GetOrganizationCandidateCard(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeGetOrganizationCandidateCardResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -6800,11 +7030,12 @@ func (s *Server) handleGrantMyConsentRequest(args [1]string, argsEscaped bool, w
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
// see answer the same 404 not_found, with the same body and without a timing or an error code that
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
// organization. The candidate can see an organization that has sent them an invitation, and the
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
// The response names the organization only after that check, with its current name. The identifiers
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
// the record never reveals to an organization that a candidate hides it.
// organization. The candidate may name an organization in their own card-access history or an existing
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
// candidate lookup remains planned. The response names the organization only after that check, with
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
// it.
//
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
@@ -7042,16 +7273,15 @@ func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool,
//
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
// writes nothing. A view of the card by an organization that has no invitation relation with the
// candidate carries `organization` null, so the candidate sees that the card was viewed without
// learning a company that they cannot otherwise see; a contact read always names the organization,
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
// hidden organization cannot read the card.
// writes nothing. A retained access record permits the candidate to see the organization's identifier
// and current name and to hide their profile from it. The nullable organization field is preserved for
// records whose organization cannot be presented. The entries carry no employee identity, search
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
// not erase earlier permitted accesses from the history.
//
// The storage of accesses is planned with the card and contact operations of the organization side
// (anonymous card reads and contact reads under the invitation contract); until then the operation
// answers 501 not_implemented after the session and request checks.
// Successful organization card reads are recorded transactionally with the visibility and quota
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
// accepted workflow status alone never authorizes contact access.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
@@ -9674,6 +9904,263 @@ func (s *Server) handleRaiseOrganizationInvitationSalaryRequest(args [2]string,
}
}
// handleRecordMyAssessmentAttemptSignalsRequest handles RecordMyAssessmentAttemptSignals operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
// every item_instance_id against that attempt, and commits the receipt and any events in one
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
// remains a separate training mode and receives no signal storage or grade effect.
//
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
// Client timestamps must be within five minutes before attempt creation and five minutes after the
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
// with the assessment attempt or account; this release does not promise an independent expiry
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
//
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
// without storing another batch; using that key with another body answers 422.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
func (s *Server) handleRecordMyAssessmentAttemptSignalsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("RecordMyAssessmentAttemptSignals"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/signals"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), RecordMyAssessmentAttemptSignalsOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: RecordMyAssessmentAttemptSignalsOperation,
ID: "RecordMyAssessmentAttemptSignals",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, RecordMyAssessmentAttemptSignalsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, RecordMyAssessmentAttemptSignalsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeRecordMyAssessmentAttemptSignalsParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
request, rawBody, close, err := s.decodeRecordMyAssessmentAttemptSignalsRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response RecordMyAssessmentAttemptSignalsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: RecordMyAssessmentAttemptSignalsOperation,
OperationSummary: "Store a bounded batch of client-reported assessment signals.",
OperationID: "RecordMyAssessmentAttemptSignals",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "attempt_id",
In: "path",
}: params.AttemptID,
{
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
},
Raw: r,
}
type (
Request = *AssessmentSignalBatch
Params = RecordMyAssessmentAttemptSignalsParams
Response = RecordMyAssessmentAttemptSignalsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackRecordMyAssessmentAttemptSignalsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.RecordMyAssessmentAttemptSignals(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.RecordMyAssessmentAttemptSignals(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeRecordMyAssessmentAttemptSignalsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleRegisterAccountRequest handles RegisterAccount operation.
//
// Public operation without a session. The client reads the current C1 text with GetConsentText and