feat(api): add specialization catalog and candidate questionnaire contract

This commit is contained in:
shira committed 2026-10-06 02:51:23 +03:00
1 parent c338c0c188
commit faeeb5f157
64 files changed
+8339 -47

No files matched your search

@@ -22,6 +22,7 @@ var regexMap = map[string]ogenregex.Regexp{
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
}
var (
@@ -879,6 +879,347 @@ func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w htt
}
}
// 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
}
}
// 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
}
}
// handleLoginRequest handles Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
@@ -1627,3 +1968,252 @@ func (s *Server) handleResendEmailVerificationRequest(args [0]string, argsEscape
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
}
}
@@ -17,6 +17,10 @@ type GetCurrentSessionRes interface {
getCurrentSessionRes()
}
type GetMyQuestionnaireRes interface {
getMyQuestionnaireRes()
}
type LoginRes interface {
loginRes()
}
@@ -32,3 +36,7 @@ type RegisterAccountRes interface {
type ResendEmailVerificationRes interface {
resendEmailVerificationRes()
}
type SaveMyQuestionnaireRes interface {
saveMyQuestionnaireRes()
}
File diff suppressed because it is too large. Load diff
@@ -6,13 +6,16 @@ package api
type OperationName = string
const (
ConfirmEmailOperation OperationName = "ConfirmEmail"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RegisterAccountOperation OperationName = "RegisterAccount"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
ConfirmEmailOperation OperationName = "ConfirmEmail"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RegisterAccountOperation OperationName = "RegisterAccount"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
)
@@ -329,3 +329,82 @@ func (s *Server) decodeResendEmailVerificationRequest(r *http.Request) (
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeSaveMyQuestionnaireRequest(r *http.Request) (
req *CandidateQuestionnaireUpdate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request CandidateQuestionnaireUpdate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
@@ -227,6 +227,78 @@ func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, s
return nil
}
func encodeGetMyQuestionnaireResponse(response GetMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateQuestionnaireHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetMyQuestionnaireUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetMyQuestionnaireForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetSpecializationCatalogResponse(response *SpecializationCatalog, w http.ResponseWriter, span trace.Span) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
}
func encodeLoginResponse(response LoginRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SessionHeaders:
@@ -587,6 +659,89 @@ func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes,
}
}
func encodeSaveMyQuestionnaireResponse(response SaveMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateQuestionnaireHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *SaveMyQuestionnaireBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *SaveMyQuestionnaireUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *SaveMyQuestionnaireForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *SaveMyQuestionnairePreconditionFailed:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(412)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error {
w.Header().Set("Content-Type", "application/problem+json")
code := response.StatusCode
@@ -11,21 +11,24 @@ import (
)
var (
rn12AllowedHeaders = map[string]string{
rn14AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn1AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn10AllowedHeaders = map[string]string{
rn12AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn9AllowedHeaders = map[string]string{
rn11AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn6AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn9AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
)
func (s *Server) cutPrefix(path string) (string, bool) {
@@ -180,7 +183,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn12AllowedHeaders,
allowedHeaders: rn14AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -257,7 +260,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn10AllowedHeaders,
allowedHeaders: rn12AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -281,7 +284,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn9AllowedHeaders,
allowedHeaders: rn11AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -321,6 +324,58 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
case 'm': // Prefix: "me/questionnaire"
if l := len("me/questionnaire"); len(elem) >= l && elem[0:l] == "me/questionnaire" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r)
case "PUT":
s.handleSaveMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn9AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 's': // Prefix: "specializations"
if l := len("specializations"); len(elem) >= l && elem[0:l] == "specializations" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetSpecializationCatalogRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
@@ -668,6 +723,65 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
case 'm': // Prefix: "me/questionnaire"
if l := len("me/questionnaire"); len(elem) >= l && elem[0:l] == "me/questionnaire" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetMyQuestionnaireOperation
r.summary = "Read the questionnaire of the current candidate."
r.operationID = "GetMyQuestionnaire"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/questionnaire"
r.args = args
r.count = 0
return r, true
case "PUT":
r.name = SaveMyQuestionnaireOperation
r.summary = "Replace the questionnaire of the current candidate."
r.operationID = "SaveMyQuestionnaire"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/questionnaire"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 's': // Prefix: "specializations"
if l := len("specializations"); len(elem) >= l && elem[0:l] == "specializations" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetSpecializationCatalogOperation
r.summary = "Read the catalog of directions, specializations, and grades."
r.operationID = "GetSpecializationCatalog"
r.operationGroup = ""
r.pathPattern = "/api/v1/specializations"
r.args = args
r.count = 0
return r, true
default:
return
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -56,9 +56,11 @@ func findAuthorization(h http.Header, prefix string) (string, bool) {
// operationRolesSessionCookie is a private map storing roles per operation.
var operationRolesSessionCookie = map[string][]string{
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
LogoutOperation: []string{},
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
GetMyQuestionnaireOperation: []string{},
LogoutOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
}
// GetRolesForSessionCookie returns the required roles for the given operation.
@@ -84,7 +86,8 @@ func GetRolesForSessionCookie(operation string) []string {
// operationRolesSessionCsrf is a private map storing roles per operation.
var operationRolesSessionCsrf = map[string][]string{
LogoutOperation: []string{},
LogoutOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
}
// GetRolesForSessionCsrf returns the required roles for the given operation.
@@ -71,6 +71,39 @@ type Handler interface {
//
// GET /api/v1/healthz
GetHealthz(ctx context.Context) (*HealthResponse, error)
// GetMyQuestionnaire implements 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
GetMyQuestionnaire(ctx context.Context) (GetMyQuestionnaireRes, error)
// GetSpecializationCatalog implements 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
GetSpecializationCatalog(ctx context.Context) (*SpecializationCatalog, error)
// Login implements Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
@@ -164,6 +197,43 @@ type Handler interface {
//
// POST /api/v1/identity/email-verification-requests
ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (ResendEmailVerificationRes, error)
// SaveMyQuestionnaire implements 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
SaveMyQuestionnaire(ctx context.Context, req *CandidateQuestionnaireUpdate) (SaveMyQuestionnaireRes, error)
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
@@ -91,6 +91,45 @@ func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse,
return r, ht.ErrNotImplemented
}
// GetMyQuestionnaire implements 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 (UnimplementedHandler) GetMyQuestionnaire(ctx context.Context) (r GetMyQuestionnaireRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetSpecializationCatalog implements 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 (UnimplementedHandler) GetSpecializationCatalog(ctx context.Context) (r *SpecializationCatalog, _ error) {
return r, ht.ErrNotImplemented
}
// Login implements Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
@@ -196,6 +235,46 @@ func (UnimplementedHandler) ResendEmailVerification(ctx context.Context, req *Em
return r, ht.ErrNotImplemented
}
// SaveMyQuestionnaire implements 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 (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *CandidateQuestionnaireUpdate) (r SaveMyQuestionnaireRes, _ error) {
return r, ht.ErrNotImplemented
}
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
File diff suppressed because it is too large. Load diff
@@ -411,6 +411,159 @@ func TestGeneratedServerSecurityOrder(t *testing.T) {
}
}
const questionnairePath = "/api/v1/me/questionnaire"
// Questionnaire specialization items shared by the questionnaire tests.
const (
backendWithGo = `{"specialization":"backend","self_assessed_grade":"middle","task_languages":["go"],"stack":["PostgreSQL"],"experience":{"commercial_months":30,"academic_months":12}}`
networkEngineer = `{"specialization":"network_engineer","self_assessed_grade":"junior","task_languages":[],"stack":[],"experience":null}`
frontendInterest = `{"specialization":"frontend","self_assessed_grade":"junior","task_languages":[],"stack":["React"],"experience":null}`
)
// questionnaireBody returns a SaveMyQuestionnaire body with the given
// specialization items.
func questionnaireBody(specializations ...string) string {
return `{"expected_version":0,"specializations":[` + strings.Join(specializations, ",") + `],"work_context":{"work_formats":["remote"]}}`
}
// The schema alone must reject the questionnaire values that FR03 forbids:
// more than two specializations, a grade outside the scale, a task language
// that is not a bank language, and a confirmed grade set by the candidate.
// Security accepts the session here, so the request reaches body validation;
// a valid body then answers 501 until the questionnaire is implemented.
func TestQuestionnaireSchemaValidationPrecedesImplementation(t *testing.T) {
for _, test := range []struct {
name string
body string
statusCode int
pointer string
code string
}{
{
// Go is a task language of the backend specialization, not a
// category of its own.
name: "Backend with Go and Network Engineer",
body: questionnaireBody(backendWithGo, networkEngineer),
statusCode: http.StatusNotImplemented,
},
{
name: "three specializations",
body: questionnaireBody(backendWithGo, networkEngineer, frontendInterest),
statusCode: http.StatusBadRequest,
pointer: "/specializations",
code: "invalid",
},
{
name: "no specialization",
body: questionnaireBody(),
statusCode: http.StatusBadRequest,
pointer: "/specializations",
code: "invalid",
},
{
name: "grade outside the MVP scale",
body: questionnaireBody(strings.Replace(backendWithGo, `"middle"`, `"lead"`, 1)),
statusCode: http.StatusBadRequest,
pointer: "/specializations/0/self_assessed_grade",
code: "invalid",
},
{
// A language is never a specialization code.
name: "language as a specialization",
body: questionnaireBody(strings.Replace(backendWithGo, `"backend"`, `"go"`, 1)),
statusCode: http.StatusBadRequest,
pointer: "/specializations/0/specialization",
code: "invalid",
},
{
name: "task language outside the bank languages",
body: questionnaireBody(strings.Replace(backendWithGo, `["go"]`, `["rust"]`, 1)),
statusCode: http.StatusBadRequest,
pointer: "/specializations/0/task_languages/0",
code: "invalid",
},
{
// The decoder does not record the path of an unknown field in a
// nested object, so the pointer is the whole body.
name: "confirmed grade set by the candidate",
body: questionnaireBody(strings.Replace(backendWithGo, `"stack"`, `"confirmed_grade":"senior","stack"`, 1)),
statusCode: http.StatusBadRequest,
pointer: "",
code: "invalid",
},
{
name: "missing expected version",
body: strings.Replace(questionnaireBody(backendWithGo), `"expected_version":0,`, "", 1),
statusCode: http.StatusBadRequest,
pointer: "/expected_version",
code: "required",
},
} {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := serveIdentityRequest(t, router, identityRequest{
method: http.MethodPut, path: questionnairePath, body: test.body,
headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken},
})
if test.statusCode == http.StatusNotImplemented {
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
return
}
body := requireProblem(t, response, test.statusCode, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: api.ProblemFieldLocationBody, Pointer: test.pointer, Code: test.code}
for _, field := range body.Errors {
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
return
}
}
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
})
}
}
// The catalog is public; the questionnaire stays closed without a session.
func TestCatalogAndQuestionnaireAccessBeforeImplementation(t *testing.T) {
for _, test := range []struct {
name string
request identityRequest
statusCode int
code api.ProblemCode
}{
{
name: "public catalog",
request: identityRequest{method: http.MethodGet, path: "/api/v1/specializations"},
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "questionnaire read without a session",
request: identityRequest{method: http.MethodGet, path: questionnairePath},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
{
name: "questionnaire save with a denied session",
request: identityRequest{
method: http.MethodPut, path: questionnairePath, body: questionnaireBody(backendWithGo),
headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken},
},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
} {
t.Run(test.name, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
requireProblem(t, serveIdentityRequest(t, router, test.request), test.statusCode, test.code)
})
}
}
func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) {
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))