1630 lines
49 KiB
Go
1630 lines
49 KiB
Go
// Code generated by ogen, DO NOT EDIT.
|
|
|
|
package api
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/go-faster/errors"
|
|
ht "github.com/ogen-go/ogen/http"
|
|
"github.com/ogen-go/ogen/middleware"
|
|
"github.com/ogen-go/ogen/ogenerrors"
|
|
"github.com/ogen-go/ogen/otelogen"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/metric"
|
|
semconv "go.opentelemetry.io/otel/semconv/v1.39.0"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
type codeRecorder struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
|
|
func (c *codeRecorder) WriteHeader(status int) {
|
|
c.status = status
|
|
c.ResponseWriter.WriteHeader(status)
|
|
}
|
|
|
|
func (c *codeRecorder) Unwrap() http.ResponseWriter {
|
|
return c.ResponseWriter
|
|
}
|
|
|
|
// handleConfirmEmailRequest handles 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 (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
|
statusWriter := &codeRecorder{ResponseWriter: w}
|
|
w = statusWriter
|
|
otelAttrs := []attribute.KeyValue{
|
|
otelogen.OperationID("ConfirmEmail"),
|
|
semconv.HTTPRequestMethodKey.String("POST"),
|
|
semconv.HTTPRouteKey.String("/api/v1/identity/email-verifications"),
|
|
}
|
|
// Add attributes from config.
|
|
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
|
|
|
// Start a span for this request.
|
|
ctx, span := s.cfg.Tracer.Start(r.Context(), ConfirmEmailOperation,
|
|
trace.WithAttributes(otelAttrs...),
|
|
serverSpanKind,
|
|
)
|
|
defer span.End()
|
|
|
|
// Add Labeler to context.
|
|
labeler := &Labeler{attrs: otelAttrs}
|
|
ctx = contextWithLabeler(ctx, labeler)
|
|
|
|
// Run stopwatch.
|
|
startTime := time.Now()
|
|
defer func() {
|
|
elapsedDuration := time.Since(startTime)
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
code := statusWriter.status
|
|
if code != 0 {
|
|
codeAttr := semconv.HTTPResponseStatusCode(code)
|
|
attrs = append(attrs, codeAttr)
|
|
span.SetAttributes(attrs...)
|
|
}
|
|
attrOpt := metric.WithAttributes(attrs...)
|
|
|
|
// Increment request counter.
|
|
s.requests.Add(ctx, 1, attrOpt)
|
|
|
|
// Use floating point division here for higher precision (instead of Millisecond method).
|
|
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
|
}()
|
|
|
|
var (
|
|
recordError = func(stage string, err error) {
|
|
span.RecordError(err)
|
|
|
|
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
|
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
|
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
|
// max redirects exceeded), in which case status MUST be set to Error.
|
|
code := statusWriter.status
|
|
if code < 100 || code >= 500 {
|
|
span.SetStatus(codes.Error, stage)
|
|
}
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
if code != 0 {
|
|
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
|
}
|
|
|
|
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
}
|
|
err error
|
|
opErrContext = ogenerrors.OperationContext{
|
|
Name: ConfirmEmailOperation,
|
|
ID: "ConfirmEmail",
|
|
}
|
|
)
|
|
|
|
var rawBody []byte
|
|
request, rawBody, close, err := s.decodeConfirmEmailRequest(r)
|
|
if err != nil {
|
|
err = &ogenerrors.DecodeRequestError{
|
|
OperationContext: opErrContext,
|
|
Err: err,
|
|
}
|
|
defer recordError("DecodeRequest", err)
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
defer func() {
|
|
if err := close(); err != nil {
|
|
recordError("CloseRequest", err)
|
|
}
|
|
}()
|
|
|
|
var response ConfirmEmailRes
|
|
if m := s.cfg.Middleware; m != nil {
|
|
mreq := middleware.Request{
|
|
Context: ctx,
|
|
OperationName: ConfirmEmailOperation,
|
|
OperationSummary: "Verify an email with the one-time token from the link.",
|
|
OperationID: "ConfirmEmail",
|
|
Body: request,
|
|
RawBody: rawBody,
|
|
Params: middleware.Parameters{},
|
|
Raw: r,
|
|
}
|
|
|
|
type (
|
|
Request = *EmailVerificationRequest
|
|
Params = struct{}
|
|
Response = ConfirmEmailRes
|
|
)
|
|
response, err = middleware.HookMiddleware[
|
|
Request,
|
|
Params,
|
|
Response,
|
|
](
|
|
m,
|
|
mreq,
|
|
nil,
|
|
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
|
response, err = s.h.ConfirmEmail(ctx, request)
|
|
return response, err
|
|
},
|
|
)
|
|
} else {
|
|
response, err = s.h.ConfirmEmail(ctx, request)
|
|
}
|
|
if err != nil {
|
|
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
|
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
if errors.Is(err, ht.ErrNotImplemented) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := encodeConfirmEmailResponse(response, w, span); err != nil {
|
|
defer recordError("EncodeResponse", err)
|
|
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// handleGetConsentTextRequest handles GetConsentText operation.
|
|
//
|
|
// Public operation without a session. Returns the current text of a consent that is given before an
|
|
// account exists; only `c1` is available. The registration page shows this text and sends its
|
|
// `text_version` with RegisterAccount, and the server hashes the same stored text when it records the
|
|
// acceptance. If the text changes while the page is open, RegisterAccount answers 400
|
|
// validation_failed with the pointer `/consent_c1/text_version`, and the page reads the text again. An
|
|
// unknown purpose fails parameter validation with 400.
|
|
//
|
|
// GET /api/v1/identity/consent-texts/{purpose}
|
|
func (s *Server) handleGetConsentTextRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
|
statusWriter := &codeRecorder{ResponseWriter: w}
|
|
w = statusWriter
|
|
otelAttrs := []attribute.KeyValue{
|
|
otelogen.OperationID("GetConsentText"),
|
|
semconv.HTTPRequestMethodKey.String("GET"),
|
|
semconv.HTTPRouteKey.String("/api/v1/identity/consent-texts/{purpose}"),
|
|
}
|
|
// Add attributes from config.
|
|
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
|
|
|
// Start a span for this request.
|
|
ctx, span := s.cfg.Tracer.Start(r.Context(), GetConsentTextOperation,
|
|
trace.WithAttributes(otelAttrs...),
|
|
serverSpanKind,
|
|
)
|
|
defer span.End()
|
|
|
|
// Add Labeler to context.
|
|
labeler := &Labeler{attrs: otelAttrs}
|
|
ctx = contextWithLabeler(ctx, labeler)
|
|
|
|
// Run stopwatch.
|
|
startTime := time.Now()
|
|
defer func() {
|
|
elapsedDuration := time.Since(startTime)
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
code := statusWriter.status
|
|
if code != 0 {
|
|
codeAttr := semconv.HTTPResponseStatusCode(code)
|
|
attrs = append(attrs, codeAttr)
|
|
span.SetAttributes(attrs...)
|
|
}
|
|
attrOpt := metric.WithAttributes(attrs...)
|
|
|
|
// Increment request counter.
|
|
s.requests.Add(ctx, 1, attrOpt)
|
|
|
|
// Use floating point division here for higher precision (instead of Millisecond method).
|
|
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
|
}()
|
|
|
|
var (
|
|
recordError = func(stage string, err error) {
|
|
span.RecordError(err)
|
|
|
|
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
|
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
|
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
|
// max redirects exceeded), in which case status MUST be set to Error.
|
|
code := statusWriter.status
|
|
if code < 100 || code >= 500 {
|
|
span.SetStatus(codes.Error, stage)
|
|
}
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
if code != 0 {
|
|
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
|
}
|
|
|
|
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
}
|
|
err error
|
|
opErrContext = ogenerrors.OperationContext{
|
|
Name: GetConsentTextOperation,
|
|
ID: "GetConsentText",
|
|
}
|
|
)
|
|
params, err := decodeGetConsentTextParams(args, argsEscaped, r)
|
|
if err != nil {
|
|
err = &ogenerrors.DecodeParamsError{
|
|
OperationContext: opErrContext,
|
|
Err: err,
|
|
}
|
|
defer recordError("DecodeParams", err)
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
|
|
var rawBody []byte
|
|
|
|
var response GetConsentTextRes
|
|
if m := s.cfg.Middleware; m != nil {
|
|
mreq := middleware.Request{
|
|
Context: ctx,
|
|
OperationName: GetConsentTextOperation,
|
|
OperationSummary: "Read the currently published text of a registration consent.",
|
|
OperationID: "GetConsentText",
|
|
Body: nil,
|
|
RawBody: rawBody,
|
|
Params: middleware.Parameters{
|
|
{
|
|
Name: "purpose",
|
|
In: "path",
|
|
}: params.Purpose,
|
|
},
|
|
Raw: r,
|
|
}
|
|
|
|
type (
|
|
Request = struct{}
|
|
Params = GetConsentTextParams
|
|
Response = GetConsentTextRes
|
|
)
|
|
response, err = middleware.HookMiddleware[
|
|
Request,
|
|
Params,
|
|
Response,
|
|
](
|
|
m,
|
|
mreq,
|
|
unpackGetConsentTextParams,
|
|
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
|
response, err = s.h.GetConsentText(ctx, params)
|
|
return response, err
|
|
},
|
|
)
|
|
} else {
|
|
response, err = s.h.GetConsentText(ctx, params)
|
|
}
|
|
if err != nil {
|
|
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
|
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
if errors.Is(err, ht.ErrNotImplemented) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := encodeGetConsentTextResponse(response, w, span); err != nil {
|
|
defer recordError("EncodeResponse", err)
|
|
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// handleGetCurrentAccountRequest handles GetCurrentAccount operation.
|
|
//
|
|
// Requires the session cookie. The account comes from the session, never from a request parameter. The
|
|
// client uses `scenario` and `onboarding_step` to return the user to the unfinished onboarding step. A
|
|
// missing, unknown, expired, or revoked session answers 401 unauthenticated. An unverified account
|
|
// never has a session, because login answers 403 email_not_verified for it, so this operation also
|
|
// answers 401 for such an account.
|
|
//
|
|
// GET /api/v1/identity/me
|
|
func (s *Server) handleGetCurrentAccountRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
|
statusWriter := &codeRecorder{ResponseWriter: w}
|
|
w = statusWriter
|
|
otelAttrs := []attribute.KeyValue{
|
|
otelogen.OperationID("GetCurrentAccount"),
|
|
semconv.HTTPRequestMethodKey.String("GET"),
|
|
semconv.HTTPRouteKey.String("/api/v1/identity/me"),
|
|
}
|
|
// Add attributes from config.
|
|
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
|
|
|
// Start a span for this request.
|
|
ctx, span := s.cfg.Tracer.Start(r.Context(), GetCurrentAccountOperation,
|
|
trace.WithAttributes(otelAttrs...),
|
|
serverSpanKind,
|
|
)
|
|
defer span.End()
|
|
|
|
// Add Labeler to context.
|
|
labeler := &Labeler{attrs: otelAttrs}
|
|
ctx = contextWithLabeler(ctx, labeler)
|
|
|
|
// Run stopwatch.
|
|
startTime := time.Now()
|
|
defer func() {
|
|
elapsedDuration := time.Since(startTime)
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
code := statusWriter.status
|
|
if code != 0 {
|
|
codeAttr := semconv.HTTPResponseStatusCode(code)
|
|
attrs = append(attrs, codeAttr)
|
|
span.SetAttributes(attrs...)
|
|
}
|
|
attrOpt := metric.WithAttributes(attrs...)
|
|
|
|
// Increment request counter.
|
|
s.requests.Add(ctx, 1, attrOpt)
|
|
|
|
// Use floating point division here for higher precision (instead of Millisecond method).
|
|
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
|
}()
|
|
|
|
var (
|
|
recordError = func(stage string, err error) {
|
|
span.RecordError(err)
|
|
|
|
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
|
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
|
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
|
// max redirects exceeded), in which case status MUST be set to Error.
|
|
code := statusWriter.status
|
|
if code < 100 || code >= 500 {
|
|
span.SetStatus(codes.Error, stage)
|
|
}
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
if code != 0 {
|
|
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
|
}
|
|
|
|
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
}
|
|
err error
|
|
opErrContext = ogenerrors.OperationContext{
|
|
Name: GetCurrentAccountOperation,
|
|
ID: "GetCurrentAccount",
|
|
}
|
|
)
|
|
{
|
|
type bitset = [1]uint8
|
|
var satisfied bitset
|
|
{
|
|
sctx, ok, err := s.securitySessionCookie(ctx, GetCurrentAccountOperation, r)
|
|
if err != nil {
|
|
err = &ogenerrors.SecurityError{
|
|
OperationContext: opErrContext,
|
|
Security: "SessionCookie",
|
|
Err: err,
|
|
}
|
|
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
|
defer recordError("Security:SessionCookie", err)
|
|
}
|
|
return
|
|
}
|
|
if ok {
|
|
satisfied[0] |= 1 << 0
|
|
ctx = sctx
|
|
}
|
|
}
|
|
|
|
if ok := func() bool {
|
|
nextRequirement:
|
|
for _, requirement := range []bitset{
|
|
{0b00000001},
|
|
} {
|
|
for i, mask := range requirement {
|
|
if satisfied[i]&mask != mask {
|
|
continue nextRequirement
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
return false
|
|
}(); !ok {
|
|
err = &ogenerrors.SecurityError{
|
|
OperationContext: opErrContext,
|
|
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
|
}
|
|
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
|
defer recordError("Security", err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
var rawBody []byte
|
|
|
|
var response GetCurrentAccountRes
|
|
if m := s.cfg.Middleware; m != nil {
|
|
mreq := middleware.Request{
|
|
Context: ctx,
|
|
OperationName: GetCurrentAccountOperation,
|
|
OperationSummary: "Read the account of the current session.",
|
|
OperationID: "GetCurrentAccount",
|
|
Body: nil,
|
|
RawBody: rawBody,
|
|
Params: middleware.Parameters{},
|
|
Raw: r,
|
|
}
|
|
|
|
type (
|
|
Request = struct{}
|
|
Params = struct{}
|
|
Response = GetCurrentAccountRes
|
|
)
|
|
response, err = middleware.HookMiddleware[
|
|
Request,
|
|
Params,
|
|
Response,
|
|
](
|
|
m,
|
|
mreq,
|
|
nil,
|
|
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
|
response, err = s.h.GetCurrentAccount(ctx)
|
|
return response, err
|
|
},
|
|
)
|
|
} else {
|
|
response, err = s.h.GetCurrentAccount(ctx)
|
|
}
|
|
if err != nil {
|
|
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
|
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
if errors.Is(err, ht.ErrNotImplemented) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := encodeGetCurrentAccountResponse(response, w, span); err != nil {
|
|
defer recordError("EncodeResponse", err)
|
|
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// handleGetCurrentSessionRequest handles GetCurrentSession operation.
|
|
//
|
|
// Requires the session cookie. Returns the account and the CSRF token of the current session, so the
|
|
// client can restore the token after a page reload or after 403 csrf_check_failed. A missing, unknown,
|
|
// expired, or revoked session answers 401 unauthenticated. Cross-origin pages cannot read the token,
|
|
// because the API sends no Access-Control-Allow-Origin header.
|
|
//
|
|
// GET /api/v1/identity/sessions/current
|
|
func (s *Server) handleGetCurrentSessionRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
|
statusWriter := &codeRecorder{ResponseWriter: w}
|
|
w = statusWriter
|
|
otelAttrs := []attribute.KeyValue{
|
|
otelogen.OperationID("GetCurrentSession"),
|
|
semconv.HTTPRequestMethodKey.String("GET"),
|
|
semconv.HTTPRouteKey.String("/api/v1/identity/sessions/current"),
|
|
}
|
|
// Add attributes from config.
|
|
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
|
|
|
// Start a span for this request.
|
|
ctx, span := s.cfg.Tracer.Start(r.Context(), GetCurrentSessionOperation,
|
|
trace.WithAttributes(otelAttrs...),
|
|
serverSpanKind,
|
|
)
|
|
defer span.End()
|
|
|
|
// Add Labeler to context.
|
|
labeler := &Labeler{attrs: otelAttrs}
|
|
ctx = contextWithLabeler(ctx, labeler)
|
|
|
|
// Run stopwatch.
|
|
startTime := time.Now()
|
|
defer func() {
|
|
elapsedDuration := time.Since(startTime)
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
code := statusWriter.status
|
|
if code != 0 {
|
|
codeAttr := semconv.HTTPResponseStatusCode(code)
|
|
attrs = append(attrs, codeAttr)
|
|
span.SetAttributes(attrs...)
|
|
}
|
|
attrOpt := metric.WithAttributes(attrs...)
|
|
|
|
// Increment request counter.
|
|
s.requests.Add(ctx, 1, attrOpt)
|
|
|
|
// Use floating point division here for higher precision (instead of Millisecond method).
|
|
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
|
}()
|
|
|
|
var (
|
|
recordError = func(stage string, err error) {
|
|
span.RecordError(err)
|
|
|
|
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
|
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
|
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
|
// max redirects exceeded), in which case status MUST be set to Error.
|
|
code := statusWriter.status
|
|
if code < 100 || code >= 500 {
|
|
span.SetStatus(codes.Error, stage)
|
|
}
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
if code != 0 {
|
|
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
|
}
|
|
|
|
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
}
|
|
err error
|
|
opErrContext = ogenerrors.OperationContext{
|
|
Name: GetCurrentSessionOperation,
|
|
ID: "GetCurrentSession",
|
|
}
|
|
)
|
|
{
|
|
type bitset = [1]uint8
|
|
var satisfied bitset
|
|
{
|
|
sctx, ok, err := s.securitySessionCookie(ctx, GetCurrentSessionOperation, r)
|
|
if err != nil {
|
|
err = &ogenerrors.SecurityError{
|
|
OperationContext: opErrContext,
|
|
Security: "SessionCookie",
|
|
Err: err,
|
|
}
|
|
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
|
defer recordError("Security:SessionCookie", err)
|
|
}
|
|
return
|
|
}
|
|
if ok {
|
|
satisfied[0] |= 1 << 0
|
|
ctx = sctx
|
|
}
|
|
}
|
|
|
|
if ok := func() bool {
|
|
nextRequirement:
|
|
for _, requirement := range []bitset{
|
|
{0b00000001},
|
|
} {
|
|
for i, mask := range requirement {
|
|
if satisfied[i]&mask != mask {
|
|
continue nextRequirement
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
return false
|
|
}(); !ok {
|
|
err = &ogenerrors.SecurityError{
|
|
OperationContext: opErrContext,
|
|
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
|
}
|
|
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
|
defer recordError("Security", err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
var rawBody []byte
|
|
|
|
var response GetCurrentSessionRes
|
|
if m := s.cfg.Middleware; m != nil {
|
|
mreq := middleware.Request{
|
|
Context: ctx,
|
|
OperationName: GetCurrentSessionOperation,
|
|
OperationSummary: "Read the current session and its CSRF token.",
|
|
OperationID: "GetCurrentSession",
|
|
Body: nil,
|
|
RawBody: rawBody,
|
|
Params: middleware.Parameters{},
|
|
Raw: r,
|
|
}
|
|
|
|
type (
|
|
Request = struct{}
|
|
Params = struct{}
|
|
Response = GetCurrentSessionRes
|
|
)
|
|
response, err = middleware.HookMiddleware[
|
|
Request,
|
|
Params,
|
|
Response,
|
|
](
|
|
m,
|
|
mreq,
|
|
nil,
|
|
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
|
response, err = s.h.GetCurrentSession(ctx)
|
|
return response, err
|
|
},
|
|
)
|
|
} else {
|
|
response, err = s.h.GetCurrentSession(ctx)
|
|
}
|
|
if err != nil {
|
|
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
|
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
if errors.Is(err, ht.ErrNotImplemented) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := encodeGetCurrentSessionResponse(response, w, span); err != nil {
|
|
defer recordError("EncodeResponse", err)
|
|
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// handleGetHealthzRequest handles GetHealthz operation.
|
|
//
|
|
// Check whether the API process is responding.
|
|
//
|
|
// GET /api/v1/healthz
|
|
func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
|
statusWriter := &codeRecorder{ResponseWriter: w}
|
|
w = statusWriter
|
|
otelAttrs := []attribute.KeyValue{
|
|
otelogen.OperationID("GetHealthz"),
|
|
semconv.HTTPRequestMethodKey.String("GET"),
|
|
semconv.HTTPRouteKey.String("/api/v1/healthz"),
|
|
}
|
|
// Add attributes from config.
|
|
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
|
|
|
// Start a span for this request.
|
|
ctx, span := s.cfg.Tracer.Start(r.Context(), GetHealthzOperation,
|
|
trace.WithAttributes(otelAttrs...),
|
|
serverSpanKind,
|
|
)
|
|
defer span.End()
|
|
|
|
// Add Labeler to context.
|
|
labeler := &Labeler{attrs: otelAttrs}
|
|
ctx = contextWithLabeler(ctx, labeler)
|
|
|
|
// Run stopwatch.
|
|
startTime := time.Now()
|
|
defer func() {
|
|
elapsedDuration := time.Since(startTime)
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
code := statusWriter.status
|
|
if code != 0 {
|
|
codeAttr := semconv.HTTPResponseStatusCode(code)
|
|
attrs = append(attrs, codeAttr)
|
|
span.SetAttributes(attrs...)
|
|
}
|
|
attrOpt := metric.WithAttributes(attrs...)
|
|
|
|
// Increment request counter.
|
|
s.requests.Add(ctx, 1, attrOpt)
|
|
|
|
// Use floating point division here for higher precision (instead of Millisecond method).
|
|
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
|
}()
|
|
|
|
var (
|
|
recordError = func(stage string, err error) {
|
|
span.RecordError(err)
|
|
|
|
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
|
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
|
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
|
// max redirects exceeded), in which case status MUST be set to Error.
|
|
code := statusWriter.status
|
|
if code < 100 || code >= 500 {
|
|
span.SetStatus(codes.Error, stage)
|
|
}
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
if code != 0 {
|
|
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
|
}
|
|
|
|
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
}
|
|
err error
|
|
)
|
|
|
|
var rawBody []byte
|
|
|
|
var response *HealthResponse
|
|
if m := s.cfg.Middleware; m != nil {
|
|
mreq := middleware.Request{
|
|
Context: ctx,
|
|
OperationName: GetHealthzOperation,
|
|
OperationSummary: "Check whether the API process is responding.",
|
|
OperationID: "GetHealthz",
|
|
Body: nil,
|
|
RawBody: rawBody,
|
|
Params: middleware.Parameters{},
|
|
Raw: r,
|
|
}
|
|
|
|
type (
|
|
Request = struct{}
|
|
Params = struct{}
|
|
Response = *HealthResponse
|
|
)
|
|
response, err = middleware.HookMiddleware[
|
|
Request,
|
|
Params,
|
|
Response,
|
|
](
|
|
m,
|
|
mreq,
|
|
nil,
|
|
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
|
response, err = s.h.GetHealthz(ctx)
|
|
return response, err
|
|
},
|
|
)
|
|
} else {
|
|
response, err = s.h.GetHealthz(ctx)
|
|
}
|
|
if err != nil {
|
|
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
|
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
if errors.Is(err, ht.ErrNotImplemented) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := encodeGetHealthzResponse(response, w, span); err != nil {
|
|
defer recordError("EncodeResponse", err)
|
|
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// handleLoginRequest handles Login operation.
|
|
//
|
|
// Public operation that starts a server session. The server verifies the password with Argon2id; for
|
|
// an unknown email it verifies against a fixed dummy hash, so the response time does not reveal
|
|
// whether the account exists. An unknown email and a wrong password both answer 401
|
|
// invalid_credentials.
|
|
//
|
|
// Correct credentials for an unverified email answer 403 email_not_verified and create no session.
|
|
// This reveals the verification state only to someone who already knows the password, which proves
|
|
// more than the state itself; the client offers to resend the link.
|
|
//
|
|
// On success the server revokes the session that the request carried, if any, creates a new random
|
|
// session in PostgreSQL with a new identifier and a new CSRF token, sets the HttpOnly session cookie,
|
|
// and returns the account and the CSRF token. The new session follows the idle and absolute timeouts
|
|
// of the sessionCookie scheme. The client keeps the token in memory and sends it in X-CSRF-Token with
|
|
// every mutating request that requires a session.
|
|
//
|
|
// Login is rate-limited per client and per email and answers 429 with Retry-After. Like every unsafe
|
|
// request, it requires an allowed Origin, which protects against login CSRF, and answers 403
|
|
// csrf_check_failed otherwise.
|
|
//
|
|
// POST /api/v1/identity/sessions
|
|
func (s *Server) handleLoginRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
|
statusWriter := &codeRecorder{ResponseWriter: w}
|
|
w = statusWriter
|
|
otelAttrs := []attribute.KeyValue{
|
|
otelogen.OperationID("Login"),
|
|
semconv.HTTPRequestMethodKey.String("POST"),
|
|
semconv.HTTPRouteKey.String("/api/v1/identity/sessions"),
|
|
}
|
|
// Add attributes from config.
|
|
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
|
|
|
// Start a span for this request.
|
|
ctx, span := s.cfg.Tracer.Start(r.Context(), LoginOperation,
|
|
trace.WithAttributes(otelAttrs...),
|
|
serverSpanKind,
|
|
)
|
|
defer span.End()
|
|
|
|
// Add Labeler to context.
|
|
labeler := &Labeler{attrs: otelAttrs}
|
|
ctx = contextWithLabeler(ctx, labeler)
|
|
|
|
// Run stopwatch.
|
|
startTime := time.Now()
|
|
defer func() {
|
|
elapsedDuration := time.Since(startTime)
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
code := statusWriter.status
|
|
if code != 0 {
|
|
codeAttr := semconv.HTTPResponseStatusCode(code)
|
|
attrs = append(attrs, codeAttr)
|
|
span.SetAttributes(attrs...)
|
|
}
|
|
attrOpt := metric.WithAttributes(attrs...)
|
|
|
|
// Increment request counter.
|
|
s.requests.Add(ctx, 1, attrOpt)
|
|
|
|
// Use floating point division here for higher precision (instead of Millisecond method).
|
|
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
|
}()
|
|
|
|
var (
|
|
recordError = func(stage string, err error) {
|
|
span.RecordError(err)
|
|
|
|
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
|
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
|
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
|
// max redirects exceeded), in which case status MUST be set to Error.
|
|
code := statusWriter.status
|
|
if code < 100 || code >= 500 {
|
|
span.SetStatus(codes.Error, stage)
|
|
}
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
if code != 0 {
|
|
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
|
}
|
|
|
|
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
}
|
|
err error
|
|
opErrContext = ogenerrors.OperationContext{
|
|
Name: LoginOperation,
|
|
ID: "Login",
|
|
}
|
|
)
|
|
|
|
var rawBody []byte
|
|
request, rawBody, close, err := s.decodeLoginRequest(r)
|
|
if err != nil {
|
|
err = &ogenerrors.DecodeRequestError{
|
|
OperationContext: opErrContext,
|
|
Err: err,
|
|
}
|
|
defer recordError("DecodeRequest", err)
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
defer func() {
|
|
if err := close(); err != nil {
|
|
recordError("CloseRequest", err)
|
|
}
|
|
}()
|
|
|
|
var response LoginRes
|
|
if m := s.cfg.Middleware; m != nil {
|
|
mreq := middleware.Request{
|
|
Context: ctx,
|
|
OperationName: LoginOperation,
|
|
OperationSummary: "Sign in with email and password and start a session.",
|
|
OperationID: "Login",
|
|
Body: request,
|
|
RawBody: rawBody,
|
|
Params: middleware.Parameters{},
|
|
Raw: r,
|
|
}
|
|
|
|
type (
|
|
Request = *LoginRequest
|
|
Params = struct{}
|
|
Response = LoginRes
|
|
)
|
|
response, err = middleware.HookMiddleware[
|
|
Request,
|
|
Params,
|
|
Response,
|
|
](
|
|
m,
|
|
mreq,
|
|
nil,
|
|
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
|
response, err = s.h.Login(ctx, request)
|
|
return response, err
|
|
},
|
|
)
|
|
} else {
|
|
response, err = s.h.Login(ctx, request)
|
|
}
|
|
if err != nil {
|
|
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
|
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
if errors.Is(err, ht.ErrNotImplemented) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := encodeLoginResponse(response, w, span); err != nil {
|
|
defer recordError("EncodeResponse", err)
|
|
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// handleLogoutRequest handles Logout operation.
|
|
//
|
|
// Requires the session cookie and the CSRF token of that session in X-CSRF-Token, and an allowed
|
|
// Origin. The server revokes the session in PostgreSQL, so the cookie value stops working even if a
|
|
// copy remains, and clears the cookie. A missing, expired, or revoked session answers 401
|
|
// unauthenticated and also clears the cookie, so a stale cookie does not stay in the browser; a
|
|
// missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed and keeps the
|
|
// session and the cookie. The client clears its private query cache after the response.
|
|
//
|
|
// DELETE /api/v1/identity/sessions/current
|
|
func (s *Server) handleLogoutRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
|
statusWriter := &codeRecorder{ResponseWriter: w}
|
|
w = statusWriter
|
|
otelAttrs := []attribute.KeyValue{
|
|
otelogen.OperationID("Logout"),
|
|
semconv.HTTPRequestMethodKey.String("DELETE"),
|
|
semconv.HTTPRouteKey.String("/api/v1/identity/sessions/current"),
|
|
}
|
|
// Add attributes from config.
|
|
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
|
|
|
// Start a span for this request.
|
|
ctx, span := s.cfg.Tracer.Start(r.Context(), LogoutOperation,
|
|
trace.WithAttributes(otelAttrs...),
|
|
serverSpanKind,
|
|
)
|
|
defer span.End()
|
|
|
|
// Add Labeler to context.
|
|
labeler := &Labeler{attrs: otelAttrs}
|
|
ctx = contextWithLabeler(ctx, labeler)
|
|
|
|
// Run stopwatch.
|
|
startTime := time.Now()
|
|
defer func() {
|
|
elapsedDuration := time.Since(startTime)
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
code := statusWriter.status
|
|
if code != 0 {
|
|
codeAttr := semconv.HTTPResponseStatusCode(code)
|
|
attrs = append(attrs, codeAttr)
|
|
span.SetAttributes(attrs...)
|
|
}
|
|
attrOpt := metric.WithAttributes(attrs...)
|
|
|
|
// Increment request counter.
|
|
s.requests.Add(ctx, 1, attrOpt)
|
|
|
|
// Use floating point division here for higher precision (instead of Millisecond method).
|
|
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
|
}()
|
|
|
|
var (
|
|
recordError = func(stage string, err error) {
|
|
span.RecordError(err)
|
|
|
|
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
|
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
|
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
|
// max redirects exceeded), in which case status MUST be set to Error.
|
|
code := statusWriter.status
|
|
if code < 100 || code >= 500 {
|
|
span.SetStatus(codes.Error, stage)
|
|
}
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
if code != 0 {
|
|
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
|
}
|
|
|
|
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
}
|
|
err error
|
|
opErrContext = ogenerrors.OperationContext{
|
|
Name: LogoutOperation,
|
|
ID: "Logout",
|
|
}
|
|
)
|
|
{
|
|
type bitset = [1]uint8
|
|
var satisfied bitset
|
|
{
|
|
sctx, ok, err := s.securitySessionCookie(ctx, LogoutOperation, r)
|
|
if err != nil {
|
|
err = &ogenerrors.SecurityError{
|
|
OperationContext: opErrContext,
|
|
Security: "SessionCookie",
|
|
Err: err,
|
|
}
|
|
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
|
defer recordError("Security:SessionCookie", err)
|
|
}
|
|
return
|
|
}
|
|
if ok {
|
|
satisfied[0] |= 1 << 0
|
|
ctx = sctx
|
|
}
|
|
}
|
|
{
|
|
sctx, ok, err := s.securitySessionCsrf(ctx, LogoutOperation, r)
|
|
if err != nil {
|
|
err = &ogenerrors.SecurityError{
|
|
OperationContext: opErrContext,
|
|
Security: "SessionCsrf",
|
|
Err: err,
|
|
}
|
|
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
|
defer recordError("Security:SessionCsrf", err)
|
|
}
|
|
return
|
|
}
|
|
if ok {
|
|
satisfied[0] |= 1 << 1
|
|
ctx = sctx
|
|
}
|
|
}
|
|
|
|
if ok := func() bool {
|
|
nextRequirement:
|
|
for _, requirement := range []bitset{
|
|
{0b00000011},
|
|
} {
|
|
for i, mask := range requirement {
|
|
if satisfied[i]&mask != mask {
|
|
continue nextRequirement
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
return false
|
|
}(); !ok {
|
|
err = &ogenerrors.SecurityError{
|
|
OperationContext: opErrContext,
|
|
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
|
}
|
|
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
|
defer recordError("Security", err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
var rawBody []byte
|
|
|
|
var response LogoutRes
|
|
if m := s.cfg.Middleware; m != nil {
|
|
mreq := middleware.Request{
|
|
Context: ctx,
|
|
OperationName: LogoutOperation,
|
|
OperationSummary: "Sign out and revoke the current session.",
|
|
OperationID: "Logout",
|
|
Body: nil,
|
|
RawBody: rawBody,
|
|
Params: middleware.Parameters{},
|
|
Raw: r,
|
|
}
|
|
|
|
type (
|
|
Request = struct{}
|
|
Params = struct{}
|
|
Response = LogoutRes
|
|
)
|
|
response, err = middleware.HookMiddleware[
|
|
Request,
|
|
Params,
|
|
Response,
|
|
](
|
|
m,
|
|
mreq,
|
|
nil,
|
|
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
|
response, err = s.h.Logout(ctx)
|
|
return response, err
|
|
},
|
|
)
|
|
} else {
|
|
response, err = s.h.Logout(ctx)
|
|
}
|
|
if err != nil {
|
|
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
|
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
if errors.Is(err, ht.ErrNotImplemented) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := encodeLogoutResponse(response, w, span); err != nil {
|
|
defer recordError("EncodeResponse", err)
|
|
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// handleRegisterAccountRequest handles RegisterAccount operation.
|
|
//
|
|
// Public operation without a session. The client reads the current C1 text with GetConsentText and
|
|
// sends the email, the password, the chosen scenario, and consent C1 with the version of the text the
|
|
// user accepted.
|
|
//
|
|
// The answer is the same 202 whether the email is new, registered but not verified, or verified, so
|
|
// registration does not enumerate accounts:
|
|
//
|
|
// - New email: the server creates an unverified account with the scenario and the first onboarding
|
|
// step, records C1 with its text version and text hash, stores only the hash of a one-time
|
|
// verification token, 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 (s *Server) handleRegisterAccountRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
|
statusWriter := &codeRecorder{ResponseWriter: w}
|
|
w = statusWriter
|
|
otelAttrs := []attribute.KeyValue{
|
|
otelogen.OperationID("RegisterAccount"),
|
|
semconv.HTTPRequestMethodKey.String("POST"),
|
|
semconv.HTTPRouteKey.String("/api/v1/identity/registrations"),
|
|
}
|
|
// Add attributes from config.
|
|
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
|
|
|
// Start a span for this request.
|
|
ctx, span := s.cfg.Tracer.Start(r.Context(), RegisterAccountOperation,
|
|
trace.WithAttributes(otelAttrs...),
|
|
serverSpanKind,
|
|
)
|
|
defer span.End()
|
|
|
|
// Add Labeler to context.
|
|
labeler := &Labeler{attrs: otelAttrs}
|
|
ctx = contextWithLabeler(ctx, labeler)
|
|
|
|
// Run stopwatch.
|
|
startTime := time.Now()
|
|
defer func() {
|
|
elapsedDuration := time.Since(startTime)
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
code := statusWriter.status
|
|
if code != 0 {
|
|
codeAttr := semconv.HTTPResponseStatusCode(code)
|
|
attrs = append(attrs, codeAttr)
|
|
span.SetAttributes(attrs...)
|
|
}
|
|
attrOpt := metric.WithAttributes(attrs...)
|
|
|
|
// Increment request counter.
|
|
s.requests.Add(ctx, 1, attrOpt)
|
|
|
|
// Use floating point division here for higher precision (instead of Millisecond method).
|
|
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
|
}()
|
|
|
|
var (
|
|
recordError = func(stage string, err error) {
|
|
span.RecordError(err)
|
|
|
|
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
|
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
|
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
|
// max redirects exceeded), in which case status MUST be set to Error.
|
|
code := statusWriter.status
|
|
if code < 100 || code >= 500 {
|
|
span.SetStatus(codes.Error, stage)
|
|
}
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
if code != 0 {
|
|
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
|
}
|
|
|
|
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
}
|
|
err error
|
|
opErrContext = ogenerrors.OperationContext{
|
|
Name: RegisterAccountOperation,
|
|
ID: "RegisterAccount",
|
|
}
|
|
)
|
|
params, err := decodeRegisterAccountParams(args, argsEscaped, r)
|
|
if err != nil {
|
|
err = &ogenerrors.DecodeParamsError{
|
|
OperationContext: opErrContext,
|
|
Err: err,
|
|
}
|
|
defer recordError("DecodeParams", err)
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
|
|
var rawBody []byte
|
|
request, rawBody, close, err := s.decodeRegisterAccountRequest(r)
|
|
if err != nil {
|
|
err = &ogenerrors.DecodeRequestError{
|
|
OperationContext: opErrContext,
|
|
Err: err,
|
|
}
|
|
defer recordError("DecodeRequest", err)
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
defer func() {
|
|
if err := close(); err != nil {
|
|
recordError("CloseRequest", err)
|
|
}
|
|
}()
|
|
|
|
var response RegisterAccountRes
|
|
if m := s.cfg.Middleware; m != nil {
|
|
mreq := middleware.Request{
|
|
Context: ctx,
|
|
OperationName: RegisterAccountOperation,
|
|
OperationSummary: "Register an account by email with a scenario and consent C1.",
|
|
OperationID: "RegisterAccount",
|
|
Body: request,
|
|
RawBody: rawBody,
|
|
Params: middleware.Parameters{
|
|
{
|
|
Name: "Idempotency-Key",
|
|
In: "header",
|
|
}: params.IdempotencyKey,
|
|
},
|
|
Raw: r,
|
|
}
|
|
|
|
type (
|
|
Request = *RegistrationRequest
|
|
Params = RegisterAccountParams
|
|
Response = RegisterAccountRes
|
|
)
|
|
response, err = middleware.HookMiddleware[
|
|
Request,
|
|
Params,
|
|
Response,
|
|
](
|
|
m,
|
|
mreq,
|
|
unpackRegisterAccountParams,
|
|
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
|
response, err = s.h.RegisterAccount(ctx, request, params)
|
|
return response, err
|
|
},
|
|
)
|
|
} else {
|
|
response, err = s.h.RegisterAccount(ctx, request, params)
|
|
}
|
|
if err != nil {
|
|
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
|
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
if errors.Is(err, ht.ErrNotImplemented) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := encodeRegisterAccountResponse(response, w, span); err != nil {
|
|
defer recordError("EncodeResponse", err)
|
|
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// handleResendEmailVerificationRequest handles ResendEmailVerification operation.
|
|
//
|
|
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
|
|
// email, and an unverified one, so it does not enumerate accounts. Only for an unverified account does
|
|
// the server issue a new one-time token bound to the current registration version, invalidate every
|
|
// earlier token of that account, and queue the message. Resend never changes the password, the
|
|
// scenario, or the consent record; a user who did not start the pending registration registers again
|
|
// instead, which replaces it.
|
|
//
|
|
// It is rate-limited per client and per email and answers 429 with Retry-After when the limit is
|
|
// reached. A retry is safe without Idempotency-Key: at worst it replaces the token again within the
|
|
// rate limit. Like every unsafe request, it requires an allowed Origin and answers 403
|
|
// csrf_check_failed otherwise.
|
|
//
|
|
// POST /api/v1/identity/email-verification-requests
|
|
func (s *Server) handleResendEmailVerificationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
|
statusWriter := &codeRecorder{ResponseWriter: w}
|
|
w = statusWriter
|
|
otelAttrs := []attribute.KeyValue{
|
|
otelogen.OperationID("ResendEmailVerification"),
|
|
semconv.HTTPRequestMethodKey.String("POST"),
|
|
semconv.HTTPRouteKey.String("/api/v1/identity/email-verification-requests"),
|
|
}
|
|
// Add attributes from config.
|
|
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
|
|
|
// Start a span for this request.
|
|
ctx, span := s.cfg.Tracer.Start(r.Context(), ResendEmailVerificationOperation,
|
|
trace.WithAttributes(otelAttrs...),
|
|
serverSpanKind,
|
|
)
|
|
defer span.End()
|
|
|
|
// Add Labeler to context.
|
|
labeler := &Labeler{attrs: otelAttrs}
|
|
ctx = contextWithLabeler(ctx, labeler)
|
|
|
|
// Run stopwatch.
|
|
startTime := time.Now()
|
|
defer func() {
|
|
elapsedDuration := time.Since(startTime)
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
code := statusWriter.status
|
|
if code != 0 {
|
|
codeAttr := semconv.HTTPResponseStatusCode(code)
|
|
attrs = append(attrs, codeAttr)
|
|
span.SetAttributes(attrs...)
|
|
}
|
|
attrOpt := metric.WithAttributes(attrs...)
|
|
|
|
// Increment request counter.
|
|
s.requests.Add(ctx, 1, attrOpt)
|
|
|
|
// Use floating point division here for higher precision (instead of Millisecond method).
|
|
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
|
}()
|
|
|
|
var (
|
|
recordError = func(stage string, err error) {
|
|
span.RecordError(err)
|
|
|
|
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
|
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
|
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
|
// max redirects exceeded), in which case status MUST be set to Error.
|
|
code := statusWriter.status
|
|
if code < 100 || code >= 500 {
|
|
span.SetStatus(codes.Error, stage)
|
|
}
|
|
|
|
attrSet := labeler.AttributeSet()
|
|
attrs := attrSet.ToSlice()
|
|
if code != 0 {
|
|
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
|
}
|
|
|
|
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
}
|
|
err error
|
|
opErrContext = ogenerrors.OperationContext{
|
|
Name: ResendEmailVerificationOperation,
|
|
ID: "ResendEmailVerification",
|
|
}
|
|
)
|
|
|
|
var rawBody []byte
|
|
request, rawBody, close, err := s.decodeResendEmailVerificationRequest(r)
|
|
if err != nil {
|
|
err = &ogenerrors.DecodeRequestError{
|
|
OperationContext: opErrContext,
|
|
Err: err,
|
|
}
|
|
defer recordError("DecodeRequest", err)
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
defer func() {
|
|
if err := close(); err != nil {
|
|
recordError("CloseRequest", err)
|
|
}
|
|
}()
|
|
|
|
var response ResendEmailVerificationRes
|
|
if m := s.cfg.Middleware; m != nil {
|
|
mreq := middleware.Request{
|
|
Context: ctx,
|
|
OperationName: ResendEmailVerificationOperation,
|
|
OperationSummary: "Request a new email verification link.",
|
|
OperationID: "ResendEmailVerification",
|
|
Body: request,
|
|
RawBody: rawBody,
|
|
Params: middleware.Parameters{},
|
|
Raw: r,
|
|
}
|
|
|
|
type (
|
|
Request = *EmailVerificationResendRequest
|
|
Params = struct{}
|
|
Response = ResendEmailVerificationRes
|
|
)
|
|
response, err = middleware.HookMiddleware[
|
|
Request,
|
|
Params,
|
|
Response,
|
|
](
|
|
m,
|
|
mreq,
|
|
nil,
|
|
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
|
response, err = s.h.ResendEmailVerification(ctx, request)
|
|
return response, err
|
|
},
|
|
)
|
|
} else {
|
|
response, err = s.h.ResendEmailVerification(ctx, request)
|
|
}
|
|
if err != nil {
|
|
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
|
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
if errors.Is(err, ht.ErrNotImplemented) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
return
|
|
}
|
|
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
|
defer recordError("Internal", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if err := encodeResendEmailVerificationResponse(response, w, span); err != nil {
|
|
defer recordError("EncodeResponse", err)
|
|
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
|
s.cfg.ErrorHandler(ctx, w, r, err)
|
|
}
|
|
return
|
|
}
|
|
}
|