feat(api): declare identity contract for registration, verification, and sessions

This commit is contained in:
shira committed 2026-10-05 22:57:19 +03:00
1 parent 197661145e
commit 653f3775f8
86 files changed
+11826 -148

No files matched your search

@@ -17,9 +17,12 @@ import (
)
var regexMap = map[string]ogenregex.Regexp{
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[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_]*$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
}
var (
// Allocate option closure once.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,34 @@
// Code generated by ogen, DO NOT EDIT.
package api
type ConfirmEmailRes interface {
confirmEmailRes()
}
type GetConsentTextRes interface {
getConsentTextRes()
}
type GetCurrentAccountRes interface {
getCurrentAccountRes()
}
type GetCurrentSessionRes interface {
getCurrentSessionRes()
}
type LoginRes interface {
loginRes()
}
type LogoutRes interface {
logoutRes()
}
type RegisterAccountRes interface {
registerAccountRes()
}
type ResendEmailVerificationRes interface {
resendEmailVerificationRes()
}
File diff suppressed because it is too large. Load diff
@@ -6,5 +6,13 @@ package api
type OperationName = string
const (
GetHealthzOperation OperationName = "GetHealthz"
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"
)
@@ -0,0 +1,183 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
"net/url"
"github.com/go-faster/errors"
"github.com/ogen-go/ogen/conv"
"github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
)
// GetConsentTextParams is parameters of GetConsentText operation.
type GetConsentTextParams struct {
// Consent whose text is requested.
Purpose ConsentPurpose
}
func unpackGetConsentTextParams(packed middleware.Parameters) (params GetConsentTextParams) {
{
key := middleware.ParameterKey{
Name: "purpose",
In: "path",
}
params.Purpose = packed[key].(ConsentPurpose)
}
return params
}
func decodeGetConsentTextParams(args [1]string, argsEscaped bool, r *http.Request) (params GetConsentTextParams, _ error) {
// Decode path: purpose.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "purpose",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.Purpose = ConsentPurpose(c)
return nil
}(); err != nil {
return err
}
if err := func() error {
if err := params.Purpose.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "purpose",
In: "path",
Err: err,
}
}
return params, nil
}
// RegisterAccountParams is parameters of RegisterAccount operation.
type RegisterAccountParams struct {
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
// request by method, path, and body.
//
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
// not_found or 409 state_conflict. A replay does not repeat the side effect.
//
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
// precondition_required (nothing changed; read the resource again and retry), 422
// idempotency_key_reused, 429, and every 5xx.
//
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
// before any other key check; a running request with the same fingerprint returns 409
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
}
func unpackRegisterAccountParams(packed middleware.Parameters) (params RegisterAccountParams) {
{
key := middleware.ParameterKey{
Name: "Idempotency-Key",
In: "header",
}
params.IdempotencyKey = packed[key].(string)
}
return params
}
func decodeRegisterAccountParams(args [0]string, argsEscaped bool, r *http.Request) (params RegisterAccountParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode header: Idempotency-Key.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "Idempotency-Key",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.IdempotencyKey = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 255,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.IdempotencyKey)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "Idempotency-Key",
In: "header",
Err: err,
}
}
return params, nil
}
@@ -1,3 +1,331 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"bytes"
"io"
"mime"
"net/http"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/validate"
)
func (s *Server) decodeConfirmEmailRequest(r *http.Request) (
req *EmailVerificationRequest,
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 EmailVerificationRequest
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeLoginRequest(r *http.Request) (
req *LoginRequest,
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 LoginRequest
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeRegisterAccountRequest(r *http.Request) (
req *RegistrationRequest,
rawBody []byte,
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 RegistrationRequest
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeResendEmailVerificationRequest(r *http.Request) (
req *EmailVerificationResendRequest,
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 EmailVerificationResendRequest
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)
}
}
@@ -7,11 +7,213 @@ import (
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/uri"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
func encodeConfirmEmailResponse(response ConfirmEmailRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *EmailVerificationResult:
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
case *ConfirmEmailBadRequest:
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 *ConfirmEmailForbidden:
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 *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetConsentTextResponse(response GetConsentTextRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ConsentText:
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
case *Problem:
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
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetCurrentAccountResponse(response GetCurrentAccountRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AccountHeaders:
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 *Problem:
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
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetCurrentSessionResponse(response GetCurrentSessionRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *GetCurrentSessionOKHeaders:
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 *Problem:
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
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, span trace.Span) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
@@ -25,6 +227,366 @@ func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, s
return nil
}
func encodeLoginResponse(response LoginRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SessionHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Set-Cookie")
// 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")
}
}
// Encode "Set-Cookie" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Set-Cookie",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(response.SetCookie))
}); err != nil {
return errors.Wrap(err, "encode Set-Cookie header")
}
}
}
w.WriteHeader(201)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *LoginBadRequest:
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 *LoginUnauthorized:
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 *LoginForbidden:
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 *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeLogoutResponse(response LogoutRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *LogoutNoContent:
w.Header().Set("Access-Control-Expose-Headers", "Set-Cookie")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Set-Cookie" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Set-Cookie",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(response.SetCookie))
}); err != nil {
return errors.Wrap(err, "encode Set-Cookie header")
}
}
}
w.WriteHeader(204)
return nil
case *ProblemHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Set-Cookie")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Set-Cookie" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Set-Cookie",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(response.SetCookie))
}); err != nil {
return errors.Wrap(err, "encode Set-Cookie header")
}
}
}
w.WriteHeader(401)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *Problem:
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 encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *IdentityRequestAccepted:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(202)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *RegisterAccountBadRequest:
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 *RegisterAccountForbidden:
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 *RegisterAccountConflict:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(409)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *RegisterAccountUnprocessableEntity:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(422)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *IdentityRequestAccepted:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(202)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ResendEmailVerificationBadRequest:
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 *ResendEmailVerificationForbidden:
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 *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error {
w.Header().Set("Content-Type", "application/problem+json")
code := response.StatusCode
@@ -10,6 +10,24 @@ import (
"github.com/ogen-go/ogen/uri"
)
var (
rn12AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn1AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn10AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn9AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn6AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
)
func (s *Server) cutPrefix(path string) (string, bool) {
prefix := s.cfg.Prefix
if prefix == "" {
@@ -40,6 +58,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.notFound(w, r)
return
}
args := [1]string{}
// Static code generated router with unwrapped path search.
switch {
@@ -48,29 +67,260 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
break
}
switch elem[0] {
case '/': // Prefix: "/api/v1/healthz"
case '/': // Prefix: "/api/v1/"
if l := len("/api/v1/healthz"); len(elem) >= l && elem[0:l] == "/api/v1/healthz" {
if l := len("/api/v1/"); len(elem) >= l && elem[0:l] == "/api/v1/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetHealthzRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
break
}
switch elem[0] {
case 'h': // Prefix: "healthz"
if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetHealthzRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 'i': // Prefix: "identity/"
if l := len("identity/"); len(elem) >= l && elem[0:l] == "identity/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 'c': // Prefix: "consent-texts/"
if l := len("consent-texts/"); len(elem) >= l && elem[0:l] == "consent-texts/" {
elem = elem[l:]
} else {
break
}
// Param: "purpose"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[0] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetConsentTextRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 'e': // Prefix: "email-verification"
if l := len("email-verification"); len(elem) >= l && elem[0:l] == "email-verification" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case '-': // Prefix: "-requests"
if l := len("-requests"); len(elem) >= l && elem[0:l] == "-requests" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleResendEmailVerificationRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn12AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
case 's': // Prefix: "s"
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleConfirmEmailRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn1AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
}
case 'm': // Prefix: "me"
if l := len("me"); len(elem) >= l && elem[0:l] == "me" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetCurrentAccountRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 'r': // Prefix: "registrations"
if l := len("registrations"); len(elem) >= l && elem[0:l] == "registrations" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleRegisterAccountRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn10AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
case 's': // Prefix: "sessions"
if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "POST":
s.handleLoginRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn9AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/current"
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "DELETE":
s.handleLogoutRequest([0]string{}, elemIsEscaped, w, r)
case "GET":
s.handleGetCurrentSessionRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,GET",
allowedHeaders: rn6AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
return
}
}
@@ -86,7 +336,7 @@ type Route struct {
operationGroup string
pathPattern string
count int
args [0]string
args [1]string
}
// Name returns ogen operation name.
@@ -159,29 +409,265 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
break
}
switch elem[0] {
case '/': // Prefix: "/api/v1/healthz"
case '/': // Prefix: "/api/v1/"
if l := len("/api/v1/healthz"); len(elem) >= l && elem[0:l] == "/api/v1/healthz" {
if l := len("/api/v1/"); len(elem) >= l && elem[0:l] == "/api/v1/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetHealthzOperation
r.summary = "Check whether the API process is responding."
r.operationID = "GetHealthz"
r.operationGroup = ""
r.pathPattern = "/api/v1/healthz"
r.args = args
r.count = 0
return r, true
default:
return
break
}
switch elem[0] {
case 'h': // Prefix: "healthz"
if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetHealthzOperation
r.summary = "Check whether the API process is responding."
r.operationID = "GetHealthz"
r.operationGroup = ""
r.pathPattern = "/api/v1/healthz"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 'i': // Prefix: "identity/"
if l := len("identity/"); len(elem) >= l && elem[0:l] == "identity/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 'c': // Prefix: "consent-texts/"
if l := len("consent-texts/"); len(elem) >= l && elem[0:l] == "consent-texts/" {
elem = elem[l:]
} else {
break
}
// Param: "purpose"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[0] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetConsentTextOperation
r.summary = "Read the currently published text of a registration consent."
r.operationID = "GetConsentText"
r.operationGroup = ""
r.pathPattern = "/api/v1/identity/consent-texts/{purpose}"
r.args = args
r.count = 1
return r, true
default:
return
}
}
case 'e': // Prefix: "email-verification"
if l := len("email-verification"); len(elem) >= l && elem[0:l] == "email-verification" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case '-': // Prefix: "-requests"
if l := len("-requests"); len(elem) >= l && elem[0:l] == "-requests" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = ResendEmailVerificationOperation
r.summary = "Request a new email verification link."
r.operationID = "ResendEmailVerification"
r.operationGroup = ""
r.pathPattern = "/api/v1/identity/email-verification-requests"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 's': // Prefix: "s"
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = ConfirmEmailOperation
r.summary = "Verify an email with the one-time token from the link."
r.operationID = "ConfirmEmail"
r.operationGroup = ""
r.pathPattern = "/api/v1/identity/email-verifications"
r.args = args
r.count = 0
return r, true
default:
return
}
}
}
case 'm': // Prefix: "me"
if l := len("me"); len(elem) >= l && elem[0:l] == "me" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetCurrentAccountOperation
r.summary = "Read the account of the current session."
r.operationID = "GetCurrentAccount"
r.operationGroup = ""
r.pathPattern = "/api/v1/identity/me"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 'r': // Prefix: "registrations"
if l := len("registrations"); len(elem) >= l && elem[0:l] == "registrations" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = RegisterAccountOperation
r.summary = "Register an account by email with a scenario and consent C1."
r.operationID = "RegisterAccount"
r.operationGroup = ""
r.pathPattern = "/api/v1/identity/registrations"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 's': // Prefix: "sessions"
if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "POST":
r.name = LoginOperation
r.summary = "Sign in with email and password and start a session."
r.operationID = "Login"
r.operationGroup = ""
r.pathPattern = "/api/v1/identity/sessions"
r.args = args
r.count = 0
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/current"
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "DELETE":
r.name = LogoutOperation
r.summary = "Sign out and revoke the current session."
r.operationID = "Logout"
r.operationGroup = ""
r.pathPattern = "/api/v1/identity/sessions/current"
r.args = args
r.count = 0
return r, true
case "GET":
r.name = GetCurrentSessionOperation
r.summary = "Read the current session and its CSRF token."
r.operationID = "GetCurrentSession"
r.operationGroup = ""
r.pathPattern = "/api/v1/identity/sessions/current"
r.args = args
r.count = 0
return r, true
default:
return
}
}
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,150 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
"net/http"
"strings"
"github.com/go-faster/errors"
"github.com/ogen-go/ogen/ogenerrors"
)
// SecurityHandler is handler for security parameters.
type SecurityHandler interface {
// HandleSessionCookie handles sessionCookie security.
// Opaque random session identifier issued by Login in an HttpOnly cookie with
// `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps the session in
// PostgreSQL, checks its expiry and revocation on every request, and derives the caller from it;
// operations never take a user identifier from the body. A session ends after an idle timeout of 24
// hours or an absolute lifetime of 7 days, whichever comes first (planned values from configuration);
// activity extends only the idle deadline. A missing, unknown, expired, or revoked session answers 401
// unauthenticated. Scripts cannot read the cookie, and it never appears in a body, log, or problem.
//
// SameSite=Strict costs the single-page application nothing: its HTML is public and every API call is
// a same-origin fetch, which carries the cookie even right after a cross-site navigation, while
// cross-site requests never carry it.
HandleSessionCookie(ctx context.Context, operationName OperationName, t SessionCookie) (context.Context, error)
// HandleSessionCsrf handles sessionCsrf security.
// Synchronizer token bound to the session, returned by Login and GetCurrentSession. Every mutating
// operation that requires a session also requires this header; a missing token or one that does not
// belong to the session answers 403 csrf_check_failed. The token is defense in depth next to
// SameSite=Strict and the Origin check: every unsafe request (POST, PUT, PATCH, DELETE), including
// public ones such as Login, must carry an Origin from the configured allowlist, otherwise it answers
// 403 csrf_check_failed; a missing Origin is rejected too, and the server never derives the allowed
// Origin from the Host header. Request bodies are accepted only as application/json, which a
// cross-site form cannot send. A backend test requires every unsafe operation that requires
// sessionCookie to require this scheme as well.
HandleSessionCsrf(ctx context.Context, operationName OperationName, t SessionCsrf) (context.Context, error)
}
func findAuthorization(h http.Header, prefix string) (string, bool) {
v, ok := h["Authorization"]
if !ok {
return "", false
}
for _, vv := range v {
scheme, value, ok := strings.Cut(vv, " ")
if !ok || !strings.EqualFold(scheme, prefix) {
continue
}
return value, true
}
return "", false
}
// operationRolesSessionCookie is a private map storing roles per operation.
var operationRolesSessionCookie = map[string][]string{
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
LogoutOperation: []string{},
}
// GetRolesForSessionCookie returns the required roles for the given operation.
//
// This is useful for authorization scenarios where you need to know which roles
// are required for an operation.
//
// Example:
//
// requiredRoles := GetRolesForSessionCookie(AddPetOperation)
//
// Returns nil if the operation has no role requirements or if the operation is unknown.
func GetRolesForSessionCookie(operation string) []string {
roles, ok := operationRolesSessionCookie[operation]
if !ok {
return nil
}
// Return a copy to prevent external modification
result := make([]string, len(roles))
copy(result, roles)
return result
}
// operationRolesSessionCsrf is a private map storing roles per operation.
var operationRolesSessionCsrf = map[string][]string{
LogoutOperation: []string{},
}
// GetRolesForSessionCsrf returns the required roles for the given operation.
//
// This is useful for authorization scenarios where you need to know which roles
// are required for an operation.
//
// Example:
//
// requiredRoles := GetRolesForSessionCsrf(AddPetOperation)
//
// Returns nil if the operation has no role requirements or if the operation is unknown.
func GetRolesForSessionCsrf(operation string) []string {
roles, ok := operationRolesSessionCsrf[operation]
if !ok {
return nil
}
// Return a copy to prevent external modification
result := make([]string, len(roles))
copy(result, roles)
return result
}
func (s *Server) securitySessionCookie(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
var t SessionCookie
const parameterName = "__Host-lincodex_session"
var value string
switch cookie, err := req.Cookie(parameterName); {
case err == nil: // if NO error
value = cookie.Value
case errors.Is(err, http.ErrNoCookie):
return ctx, false, nil
default:
return nil, false, errors.Wrap(err, "get cookie value")
}
t.APIKey = value
t.Roles = operationRolesSessionCookie[operationName]
rctx, err := s.sec.HandleSessionCookie(ctx, operationName, t)
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return rctx, true, err
}
func (s *Server) securitySessionCsrf(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
var t SessionCsrf
const parameterName = "X-CSRF-Token"
value := req.Header.Get(parameterName)
if value == "" {
return ctx, false, nil
}
t.APIKey = value
t.Roles = operationRolesSessionCsrf[operationName]
rctx, err := s.sec.HandleSessionCsrf(ctx, operationName, t)
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return rctx, true, err
}
@@ -8,12 +8,162 @@ import (
// Handler handles operations described by OpenAPI v3 specification.
type Handler interface {
// ConfirmEmail implements ConfirmEmail operation.
//
// Public operation without a session. The verification link has the form
// `<frontend origin>/verify-email#token=<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 answers
// verification_token_expired; an unknown, used, replaced, or superseded token answers
// verification_token_invalid; neither changes anything. For both, the client offers a new link and
// sign-in, because the address may already be verified.
//
// 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.
//
// POST /api/v1/identity/email-verifications
ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (ConfirmEmailRes, error)
// GetConsentText implements 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}
GetConsentText(ctx context.Context, params GetConsentTextParams) (GetConsentTextRes, error)
// GetCurrentAccount implements 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
GetCurrentAccount(ctx context.Context) (GetCurrentAccountRes, error)
// GetCurrentSession implements 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
GetCurrentSession(ctx context.Context) (GetCurrentSessionRes, error)
// GetHealthz implements GetHealthz operation.
//
// Check whether the API process is responding.
//
// GET /api/v1/healthz
GetHealthz(ctx context.Context) (*HealthResponse, error)
// Login implements 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
Login(ctx context.Context, req *LoginRequest) (LoginRes, error)
// Logout implements 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
Logout(ctx context.Context) (LogoutRes, error)
// RegisterAccount implements 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, 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 replaces the password hash, the scenario, the onboarding step, and the C1
// record, advances the registration version, invalidates every earlier verification token, and
// queues a message with a new token. A pre-registration with someone else's password therefore
// never survives the address owner's own registration.
// - 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
RegisterAccount(ctx context.Context, req *RegistrationRequest, params RegisterAccountParams) (RegisterAccountRes, error)
// ResendEmailVerification implements 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
ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (ResendEmailVerificationRes, error)
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
@@ -23,18 +173,20 @@ type Handler interface {
// Server implements http server based on OpenAPI v3 specification and
// calls Handler to handle requests.
type Server struct {
h Handler
h Handler
sec SecurityHandler
baseServer
}
// NewServer creates new Server.
func NewServer(h Handler, opts ...ServerOption) (*Server, error) {
func NewServer(h Handler, sec SecurityHandler, opts ...ServerOption) (*Server, error) {
s, err := newServerConfig(opts...).baseServer()
if err != nil {
return nil, err
}
return &Server{
h: h,
sec: sec,
baseServer: s,
}, nil
}
@@ -13,6 +13,75 @@ type UnimplementedHandler struct{}
var _ Handler = UnimplementedHandler{}
// ConfirmEmail implements ConfirmEmail operation.
//
// Public operation without a session. The verification link has the form
// `<frontend origin>/verify-email#token=<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 answers
// verification_token_expired; an unknown, used, replaced, or superseded token answers
// verification_token_invalid; neither changes anything. For both, the client offers a new link and
// sign-in, because the address may already be verified.
//
// 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.
//
// POST /api/v1/identity/email-verifications
func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (r ConfirmEmailRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetConsentText implements 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 (UnimplementedHandler) GetConsentText(ctx context.Context, params GetConsentTextParams) (r GetConsentTextRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetCurrentAccount implements 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 (UnimplementedHandler) GetCurrentAccount(ctx context.Context) (r GetCurrentAccountRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetCurrentSession implements 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 (UnimplementedHandler) GetCurrentSession(ctx context.Context) (r GetCurrentSessionRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetHealthz implements GetHealthz operation.
//
// Check whether the API process is responding.
@@ -22,6 +91,111 @@ func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse,
return r, ht.ErrNotImplemented
}
// Login implements 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 (UnimplementedHandler) Login(ctx context.Context, req *LoginRequest) (r LoginRes, _ error) {
return r, ht.ErrNotImplemented
}
// Logout implements 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 (UnimplementedHandler) Logout(ctx context.Context) (r LogoutRes, _ error) {
return r, ht.ErrNotImplemented
}
// RegisterAccount implements 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, 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 replaces the password hash, the scenario, the onboarding step, and the C1
// record, advances the registration version, invalidates every earlier verification token, and
// queues a message with a new token. A pre-registration with someone else's password therefore
// never survives the address owner's own registration.
// - 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 (UnimplementedHandler) RegisterAccount(ctx context.Context, req *RegistrationRequest, params RegisterAccountParams) (r RegisterAccountRes, _ error) {
return r, ht.ErrNotImplemented
}
// ResendEmailVerification implements 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 (UnimplementedHandler) ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (r ResendEmailVerificationRes, _ error) {
return r, ht.ErrNotImplemented
}
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
@@ -9,6 +9,381 @@ import (
"github.com/ogen-go/ogen/validate"
)
func (s *Account) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Email.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "email",
Error: err,
})
}
if err := func() error {
if err := s.Scenario.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "scenario",
Error: err,
})
}
if err := func() error {
if err := s.OnboardingStep.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "onboarding_step",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *AccountHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s AccountScenario) Validate() error {
switch s {
case "candidate":
return nil
case "employer":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s CacheControlNoStore) Validate() error {
switch s {
case "no-store":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *ConfirmEmailBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ConfirmEmailForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s ConsentPurpose) Validate() error {
switch s {
case "c1":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *ConsentText) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Purpose.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "purpose",
Error: err,
})
}
if err := func() error {
if err := s.TextVersion.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "text_version",
Error: err,
})
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 100000,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Text)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "text",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ConsentTextVersion) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s CsrfToken) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 32,
MinLengthSet: true,
MaxLength: 128,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s EmailAddress) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 3,
MinLengthSet: true,
MaxLength: 254,
MaxLengthSet: true,
Email: true,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s *EmailVerificationRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Token.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "token",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *EmailVerificationResendRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Email.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "email",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *EmailVerificationResult) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.EmailVerified.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "email_verified",
Error: err,
})
}
if err := func() error {
if err := s.Scenario.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "scenario",
Error: err,
})
}
if err := func() error {
if err := s.OnboardingStep.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "onboarding_step",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s EmailVerificationResultEmailVerified) Validate() error {
switch s {
case true:
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *GetCurrentSessionOKHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *HealthResponse) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -41,6 +416,233 @@ func (s HealthResponseStatus) Validate() error {
}
}
func (s *IdentityRequestAccepted) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Status.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "status",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s IdentityRequestAcceptedStatus) Validate() error {
switch s {
case "accepted":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *LoginBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *LoginForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s LoginPassword) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 128,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s *LoginRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Email.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "email",
Error: err,
})
}
if err := func() error {
if err := s.Password.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "password",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *LoginUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *LogoutNoContent) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 4096,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^__Host-lincodex_session="],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.SetCookie)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "SetCookie",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s NewPassword) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 15,
MinLengthSet: true,
MaxLength: 128,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s OnboardingStep) Validate() error {
switch s {
case "candidate_consents":
return nil
case "candidate_profile":
return nil
case "candidate_questionnaire":
return nil
case "candidate_assessment":
return nil
case "employer_company":
return nil
case "completed":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *PersonalDataConsentAcceptance) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.TextVersion.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "text_version",
Error: err,
})
}
if err := func() error {
if err := s.Accepted.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "accepted",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s PersonalDataConsentAcceptanceAccepted) Validate() error {
switch s {
case true:
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *Problem) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -261,10 +863,20 @@ func (s ProblemCode) Validate() error {
switch s {
case "validation_failed":
return nil
case "verification_token_invalid":
return nil
case "verification_token_expired":
return nil
case "unauthenticated":
return nil
case "invalid_credentials":
return nil
case "forbidden":
return nil
case "email_not_verified":
return nil
case "csrf_check_failed":
return nil
case "not_found":
return nil
case "method_not_allowed":
@@ -403,6 +1015,52 @@ func (s ProblemFieldLocation) Validate() error {
}
}
func (s *ProblemHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 4096,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^__Host-lincodex_session="],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.SetCookie)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "SetCookie",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ProblemStatusCode) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -425,3 +1083,269 @@ func (s *ProblemStatusCode) Validate() error {
}
return nil
}
func (s *RegisterAccountBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RegisterAccountConflict) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RegisterAccountForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RegisterAccountUnprocessableEntity) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RegistrationRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Email.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "email",
Error: err,
})
}
if err := func() error {
if err := s.Password.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "password",
Error: err,
})
}
if err := func() error {
if err := s.Scenario.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "scenario",
Error: err,
})
}
if err := func() error {
if err := s.ConsentC1.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "consent_c1",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ResendEmailVerificationBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ResendEmailVerificationForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *Session) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Account.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "account",
Error: err,
})
}
if err := func() error {
if err := s.CsrfToken.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "csrf_token",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *SessionHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 4096,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^__Host-lincodex_session="],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.SetCookie)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "SetCookie",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *TooManyRequestsHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if value, ok := s.RetryAfter.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: true,
Max: 86400,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "RetryAfter",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s VerificationToken) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 32,
MinLengthSet: true,
MaxLength: 128,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
@@ -32,16 +32,41 @@ var definitions = map[api.ProblemCode]definition{
title: "Request validation failed",
detail: "One or more request fields are invalid.",
},
api.ProblemCodeVerificationTokenInvalid: {
status: http.StatusBadRequest,
title: "Verification link is not valid",
detail: "Request a new verification link, or sign in if the address is already verified.",
},
api.ProblemCodeVerificationTokenExpired: {
status: http.StatusBadRequest,
title: "Verification link expired",
detail: "Request a new verification link.",
},
api.ProblemCodeUnauthenticated: {
status: http.StatusUnauthorized,
title: "Authentication required",
detail: "Sign in and repeat the request.",
},
api.ProblemCodeInvalidCredentials: {
status: http.StatusUnauthorized,
title: "Invalid email or password",
detail: "Check the email and password and try again.",
},
api.ProblemCodeForbidden: {
status: http.StatusForbidden,
title: "Access denied",
detail: "You do not have permission to perform this operation.",
},
api.ProblemCodeEmailNotVerified: {
status: http.StatusForbidden,
title: "Email not verified",
detail: "Confirm the email address with the link from the verification message.",
},
api.ProblemCodeCsrfCheckFailed: {
status: http.StatusForbidden,
title: "Cross-site request check failed",
detail: "Read the current session to get a new CSRF token and repeat the request.",
},
api.ProblemCodeNotFound: {
status: http.StatusNotFound,
title: "Resource not found",
@@ -26,16 +26,20 @@ const (
// ht.ErrNotImplemented to 501, request decoding and validation errors to 400,
// unknown routes under /api to 404, unsupported methods to 405, and any other
// server error or panic to 500 without exposing its text. Operation errors go
// through apiHandler.NewError.
// through apiHandler.NewError. security decides every operation that requires
// a session; the generated server answers its rejection, and a request
// without the session cookie, with 401 unauthenticated through NewError.
func NewRouter(
health *v1.HealthHandler,
apiHandler apiadapter.Handler,
security apiadapter.SecurityHandler,
problems *problem.Responder,
collector httpmiddleware.RequestMetrics,
logger *slog.Logger,
) (http.Handler, error) {
apiServer, err := apiadapter.NewServer(
apiHandler,
security,
apiadapter.WithErrorHandler(problems.HandleServerError),
apiadapter.WithNotFound(problems.NotFound),
apiadapter.WithMethodNotAllowed(problems.MethodNotAllowed),
@@ -106,6 +106,311 @@ func TestPublicUnimplementedOperationReturnsNotImplementedProblem(t *testing.T)
}
}
// Identity request fixtures shared by the router tests.
const (
testSessionCookie = "__Host-lincodex_session=opaque-session-value"
testCSRFToken = "Xk4pR9tV2mQ7wL1sN8bC5dF0gH3jZ6yA9eU2iO7rT4c"
testIdempotencyKey = "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11"
registrationPath = "/api/v1/identity/registrations"
currentSessionPath = "/api/v1/identity/sessions/current"
)
// registrationBody returns a valid RegisterAccount body with replaced parts.
func registrationBody(password, consent string) string {
return `{"email":"candidate@example.com","password":"` + password + `","scenario":"candidate","consent_c1":` + consent + `}`
}
const (
validPassword = "correct horse battery staple"
validConsent = `{"text_version":"c1-2026-10-01","accepted":true}`
)
type identityRequest struct {
method string
path string
body string
headers map[string]string
}
func serveIdentityRequest(t *testing.T, router http.Handler, request identityRequest) *httptest.ResponseRecorder {
t.Helper()
httpRequest := httptest.NewRequest(request.method, request.path, strings.NewReader(request.body))
if request.body != "" {
httpRequest.Header.Set("Content-Type", "application/json")
}
for name, value := range request.headers {
httpRequest.Header.Set(name, value)
}
response := httptest.NewRecorder()
router.ServeHTTP(response, httpRequest)
return response
}
// Identity operations are in the contract before their business logic. Public
// ones must answer 501 only after request validation, and session-protected
// ones must stay closed: DenyAllSecurity grants no session, with or without a
// cookie and a CSRF token.
func TestIdentityOperationsBeforeImplementation(t *testing.T) {
for _, test := range []struct {
name string
request identityRequest
statusCode int
code api.ProblemCode
}{
{
name: "public registration",
request: identityRequest{
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
},
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "public email verification resend",
request: identityRequest{
method: http.MethodPost, path: "/api/v1/identity/email-verification-requests",
body: `{"email":"candidate@example.com"}`,
},
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "public email confirmation",
request: identityRequest{
method: http.MethodPost, path: "/api/v1/identity/email-verifications",
body: `{"token":"q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE"}`,
},
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "public login",
request: identityRequest{
method: http.MethodPost, path: "/api/v1/identity/sessions",
body: `{"email":"candidate@example.com","password":"correct horse battery staple"}`,
},
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "public consent text",
request: identityRequest{method: http.MethodGet, path: "/api/v1/identity/consent-texts/c1"},
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "current account without a session cookie",
request: identityRequest{method: http.MethodGet, path: "/api/v1/identity/me"},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
{
name: "current account with a session cookie",
request: identityRequest{
method: http.MethodGet, path: "/api/v1/identity/me",
headers: map[string]string{"Cookie": testSessionCookie},
},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
{
name: "current session without a session cookie",
request: identityRequest{method: http.MethodGet, path: currentSessionPath},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
{
name: "logout with a session cookie and a CSRF token",
request: identityRequest{
method: http.MethodDelete, path: currentSessionPath,
headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken},
},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
{
name: "logout with only a CSRF token",
request: identityRequest{
method: http.MethodDelete, path: currentSessionPath,
headers: map[string]string{"X-CSRF-Token": testCSRFToken},
},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
{
name: "logout with only a session cookie",
request: identityRequest{
method: http.MethodDelete, path: currentSessionPath,
headers: map[string]string{"Cookie": testSessionCookie},
},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
} {
t.Run(test.name, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
response := serveIdentityRequest(t, router, test.request)
requireProblem(t, response, test.statusCode, test.code)
if cookie := response.Header().Get("Set-Cookie"); test.statusCode == http.StatusNotImplemented && cookie != "" {
t.Fatalf("Set-Cookie = %q, want none from an unimplemented operation", cookie)
}
})
}
// The security handler does not affect operations without security.
router := newTestRouter(t, func(context.Context) error { return nil })
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
if response.Code != http.StatusOK {
t.Fatalf("healthz status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String())
}
}
// Registration rejects invalid requests with 400 before the 501 of the
// missing business logic, with pointers to the failing fields.
func TestRegistrationValidationPrecedesImplementation(t *testing.T) {
const fourteenCharacters = "fourteen-chars"
withKey := map[string]string{"Idempotency-Key": testIdempotencyKey}
for _, test := range []struct {
name string
body string
headers map[string]string
location api.ProblemFieldLocation
pointer string
code string
}{
{
// Unknown fields are rejected, so no other consent, such as C4,
// can be given at registration.
name: "consent C4 at registration",
body: `{"email":"candidate@example.com","password":"` + validPassword + `","scenario":"candidate","consent_c1":` + validConsent + `,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true}}`,
headers: withKey,
location: api.ProblemFieldLocationBody,
pointer: "",
code: "invalid",
},
{
name: "consent C1 not accepted",
body: registrationBody(validPassword, `{"text_version":"c1-2026-10-01","accepted":false}`),
headers: withKey,
location: api.ProblemFieldLocationBody,
pointer: "/consent_c1/accepted",
code: "invalid",
},
{
name: "password shorter than 15 characters",
body: registrationBody(fourteenCharacters, validConsent),
headers: withKey,
location: api.ProblemFieldLocationBody,
pointer: "/password",
code: "invalid",
},
{
name: "missing Idempotency-Key",
body: registrationBody(validPassword, validConsent),
location: api.ProblemFieldLocationHeader,
pointer: "/Idempotency-Key",
code: "required",
},
} {
t.Run(test.name, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
response := serveIdentityRequest(t, router, identityRequest{
method: http.MethodPost, path: registrationPath, body: test.body, headers: test.headers,
})
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: test.location, 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)
})
}
}
// sessionPrincipalKey marks the context returned by HandleSessionCookie.
type sessionPrincipalKey struct{}
// recordingSecurity accepts every scheme value and records the order of the
// calls and whether HandleSessionCsrf saw the context of HandleSessionCookie.
type recordingSecurity struct {
calls []string
csrfSawPrincipal bool
}
func (security *recordingSecurity) HandleSessionCookie(ctx context.Context, _ api.OperationName, _ api.SessionCookie) (context.Context, error) {
security.calls = append(security.calls, "SessionCookie")
return context.WithValue(ctx, sessionPrincipalKey{}, "principal"), nil
}
func (security *recordingSecurity) HandleSessionCsrf(ctx context.Context, _ api.OperationName, _ api.SessionCsrf) (context.Context, error) {
security.calls = append(security.calls, "SessionCsrf")
security.csrfSawPrincipal = ctx.Value(sessionPrincipalKey{}) != nil
return ctx, nil
}
// The session-bound CSRF check of TASK-056 relies on the generated server
// calling HandleSessionCookie before HandleSessionCsrf and passing the
// returned context on. ogen orders the calls by scheme name, so renaming a
// scheme or upgrading ogen must keep this test green.
func TestGeneratedServerSecurityOrder(t *testing.T) {
for _, test := range []struct {
name string
headers map[string]string
calls []string
csrfSawPrincipal bool
statusCode int
}{
{
name: "cookie and CSRF token",
headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken},
calls: []string{"SessionCookie", "SessionCsrf"},
csrfSawPrincipal: true,
statusCode: http.StatusNotImplemented,
},
{
// Without a cookie HandleSessionCsrf still runs, with the
// original context, and the unsatisfied requirement answers 401.
name: "CSRF token without a cookie",
headers: map[string]string{"X-CSRF-Token": testCSRFToken},
calls: []string{"SessionCsrf"},
statusCode: http.StatusUnauthorized,
},
{
name: "cookie without a CSRF token",
headers: map[string]string{"Cookie": testSessionCookie},
calls: []string{"SessionCookie"},
statusCode: http.StatusUnauthorized,
},
} {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
security := &recordingSecurity{}
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := serveIdentityRequest(t, router, identityRequest{method: http.MethodDelete, path: currentSessionPath, headers: test.headers})
if response.Code != test.statusCode {
t.Fatalf("status code = %d, want %d: %s", response.Code, test.statusCode, response.Body.String())
}
if fmt.Sprint(security.calls) != fmt.Sprint(test.calls) {
t.Fatalf("security calls = %v, want %v", security.calls, test.calls)
}
if security.csrfSawPrincipal != test.csrfSawPrincipal {
t.Fatalf("HandleSessionCsrf saw the session context = %t, want %t", security.csrfSawPrincipal, test.csrfSawPrincipal)
}
})
}
}
func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) {
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
@@ -154,7 +459,7 @@ func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) {
getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) },
}
recorder := &requestRecorder{}
router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), recorder, logger)
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -331,7 +636,7 @@ func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler {
func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler {
t.Helper()
router, err := NewRouter(healthHandler, apiHandler, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -343,7 +648,7 @@ func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getH
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz}
router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), collector, logger)
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -0,0 +1,80 @@
package httpadapter
import (
"net/http"
"os"
"slices"
"testing"
"github.com/ogen-go/ogen"
)
// publicContractBundle is the bundled public contract that the generated
// server is built from, relative to this package.
const publicContractBundle = "../../../../../api/core/openapi.bundle.yml"
const (
sessionCookieScheme = "sessionCookie"
sessionCSRFScheme = "sessionCsrf"
)
// A browser sends the session cookie with every same-site request, so an
// unsafe operation that accepts the session must also demand the
// session-bound CSRF token. A new operation that forgets sessionCsrf would
// otherwise compile and pass every other check.
func TestUnsafeSessionOperationsRequireCSRFToken(t *testing.T) {
data, err := os.ReadFile(publicContractBundle)
if err != nil {
t.Fatalf("read the public contract bundle: %v", err)
}
spec, err := ogen.Parse(data)
if err != nil {
t.Fatalf("parse the public contract bundle: %v", err)
}
checked := 0
for path, item := range spec.Paths {
for method, operation := range unsafeOperations(item) {
// An operation without its own security list inherits the root
// one; an explicit empty list makes it public.
requirements := operation.Security
if requirements == nil {
requirements = spec.Security
}
for _, requirement := range requirements {
if _, usesSession := requirement[sessionCookieScheme]; !usesSession {
continue
}
checked++
if _, usesCSRF := requirement[sessionCSRFScheme]; !usesCSRF {
t.Errorf("%s %s (%s) accepts %s without %s", method, path, operation.OperationID, sessionCookieScheme, sessionCSRFScheme)
}
}
}
}
// Logout is an unsafe session operation, so an empty result means the
// bundle was not read as expected.
if checked == 0 {
t.Fatal("found no unsafe operation that requires a session; the check would pass vacuously")
}
}
func unsafeOperations(item *ogen.PathItem) map[string]*ogen.Operation {
operations := map[string]*ogen.Operation{
http.MethodPost: item.Post,
http.MethodPut: item.Put,
http.MethodPatch: item.Patch,
http.MethodDelete: item.Delete,
}
for method, operation := range item.AdditionalOperations {
if !slices.Contains([]string{http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace}, method) {
operations[method] = operation
}
}
for method, operation := range operations {
if operation == nil {
delete(operations, method)
}
}
return operations
}
@@ -0,0 +1,70 @@
package v1
import (
"context"
"errors"
"lincodex/backend/internal/adapter/primary/http/api"
)
// errSessionsNotImplemented rejects every session-protected request until the
// session boundary exists. Its text stays in the server: the generated server
// wraps it in *ogenerrors.SecurityError, which the problem responder answers
// with a fixed 401 unauthenticated problem.
var errSessionsNotImplemented = errors.New("v1.DenyAllSecurity - sessions are not implemented")
// DenyAllSecurity implements api.SecurityHandler by rejecting every session
// cookie and CSRF token, so no operation that requires a session is reachable
// before server sessions exist. Operations that declare `security: []` do not
// call it and keep their own behavior, which is 501 not_implemented until
// their business logic exists.
//
// TASK-056 replaces it. The generated server (ogen v1.24.0) evaluates the
// schemes of an operation as follows; TestGeneratedServerSecurityOrder pins
// the order and the context propagation:
//
// - It evaluates sessionCookie before sessionCsrf, in the order of the
// generated type names, and each step receives the context returned by
// the previous successful step.
// - A scheme whose value is absent (no cookie, or an empty X-CSRF-Token
// header) does not call its Handle method and counts as unsatisfied.
// - A Handle method that returns ogenerrors.ErrSkipServerSecurity also counts
// as unsatisfied, and evaluation continues with the next scheme.
// - A Handle method that returns any other error stops evaluation: the
// server passes &ogenerrors.SecurityError{Security: "SessionCookie" or
// "SessionCsrf", Err: err} to Handler.NewError with the context that the
// failing step received. HandleSessionCsrf is therefore called after a
// missing cookie or a skipped session, with the original context, but
// never after HandleSessionCookie returned another error.
// - When every scheme was evaluated and a requirement is still unsatisfied,
// the server passes &ogenerrors.SecurityError{Err:
// ogenerrors.ErrSecurityRequirementIsNotSatisfied}, without a Security
// field, to Handler.NewError with the context of the last successful step.
//
// The intended mapping on top of that behavior:
//
// - HandleSessionCookie returns a context with the principal for a valid
// session and ogenerrors.ErrSkipServerSecurity for a missing, unknown,
// expired, or revoked one.
// - HandleSessionCsrf returns ogenerrors.ErrSkipServerSecurity when the
// context has no principal, so the result is 401 unauthenticated, and a
// typed error when the token does not belong to the session.
// - NewError answers a SecurityError with Security "SessionCsrf" with 403
// csrf_check_failed, an unsatisfied requirement whose context carries a
// principal (an empty X-CSRF-Token) with 403 csrf_check_failed, and every
// other security failure with 401 unauthenticated.
type DenyAllSecurity struct{}
var _ api.SecurityHandler = (*DenyAllSecurity)(nil)
func NewDenyAllSecurity() *DenyAllSecurity {
return &DenyAllSecurity{}
}
func (*DenyAllSecurity) HandleSessionCookie(ctx context.Context, _ api.OperationName, _ api.SessionCookie) (context.Context, error) {
return ctx, errSessionsNotImplemented
}
func (*DenyAllSecurity) HandleSessionCsrf(ctx context.Context, _ api.OperationName, _ api.SessionCsrf) (context.Context, error) {
return ctx, errSessionsNotImplemented
}