feat(identity): add server sessions and audited mail recovery

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:03:46 +03:00
1 parent 20c03288d6
commit 4ee53d9a74
58 files changed
+5359 -567

No files matched your search

@@ -0,0 +1,196 @@
// Package mailretry implements the local operator command for inspecting and
// authorizing a retry of an unknown mail delivery.
package mailretry
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strings"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
)
const usage = "usage: mail-retry inspect --delivery <uuid> | mail-retry retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk"
type action uint8
const (
inspectAction action = iota + 1
retryAction
)
// Command is a parsed, validated local mail retry command.
type Command struct {
Action action
DeliveryID uuid.UUID
Actor string
AcknowledgeDuplicateRisk bool
}
// Operator is the metadata-only and audit-backed retry usecase.
type Operator interface {
Inspect(ctx context.Context, deliveryID uuid.UUID) (notification.DeliveryRetryInspection, error)
RetryUnknown(ctx context.Context, deliveryID uuid.UUID, actor string, acknowledgeDuplicateRisk bool) (string, error)
}
// Parse validates every argument before Run reads configuration or connects
// to PostgreSQL.
func Parse(args []string) (Command, error) {
if len(args) == 0 {
return Command{}, errors.New(usage)
}
var command Command
var actor *string
var acknowledge *bool
switch args[0] {
case "inspect":
command.Action = inspectAction
case "retry":
command.Action = retryAction
default:
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("mail-retry "+args[0], flag.ContinueOnError)
flags.SetOutput(io.Discard)
deliveryID := flags.String("delivery", "", "delivery UUID")
if command.Action == retryAction {
actor = flags.String("actor", "", "operator handle")
acknowledge = flags.Bool("acknowledge-duplicate-risk", false, "acknowledge that a duplicate may be sent")
}
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
return Command{}, errors.New(usage)
}
parsedID, err := uuid.Parse(strings.TrimSpace(*deliveryID))
if err != nil || parsedID == uuid.Nil {
return Command{}, errors.New("delivery must be a non-zero UUID")
}
command.DeliveryID = parsedID
if command.Action == retryAction {
if _, err := domain.ParseMailRetryActor(strings.TrimSpace(*actor)); err != nil {
return Command{}, errors.New("actor must be operator:<handle>")
}
if !*acknowledge {
return Command{}, errors.New("--acknowledge-duplicate-risk is required")
}
command.Actor = strings.TrimSpace(*actor)
command.AcknowledgeDuplicateRisk = true
}
return command, nil
}
// Run parses the command, loads only its database and mail-account settings
// from the supplied environment, then executes the operator usecase. It does
// not load dotenv files or read transport credentials.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil {
return errors.New("mail retry command dependencies are required")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return errors.New("DATABASE_URL is not set")
}
provider := strings.ToLower(strings.TrimSpace(envValue(lookup, "EMAIL_PROVIDER", "")))
if provider != string(config.EmailProviderResend) {
return errors.New("mail retry is available only with EMAIL_PROVIDER=resend in this build")
}
accountLabel := strings.TrimSpace(envValue(lookup, "EMAIL_ACCOUNT", "default"))
account, err := domain.NewMailProviderAccount(provider, accountLabel)
if err != nil {
return errors.New("mail provider account configuration is invalid")
}
pool, err := postgres.NewPool(ctx, databaseURL)
if err != nil {
return errors.New("database configuration is invalid")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("database is unavailable")
}
deliveries := postgres.NewDeliveryStore(pool).Deliveries()
operator, err := notification.NewDeliveryRetryOperator(
postgres.NewTransactor(pool),
deliveries,
account,
resend.IdempotencyWindow,
time.Now,
)
if err != nil {
return errors.New("mail retry is unavailable")
}
return Execute(ctx, command, operator, output)
}
// Execute prints the duplicate-risk warning before retry authorization can
// mutate the delivery or append an audit decision.
func Execute(ctx context.Context, command Command, operator Operator, output io.Writer) error {
if operator == nil || output == nil {
return errors.New("mail retry command dependencies are required")
}
snapshot, err := operator.Inspect(ctx, command.DeliveryID)
if err != nil {
return safeOperationError(err)
}
if command.Action == inspectAction {
if _, err := fmt.Fprintf(output,
"delivery: %s\nprovider: %s\nstatus: %s\nattempts: %d\n%s\n",
snapshot.DeliveryID, snapshot.Provider, snapshot.Status, snapshot.AttemptCount, notification.DuplicateRiskWarning,
); err != nil {
return errors.New("could not write mail retry inspection")
}
return nil
}
if command.Action != retryAction || !command.AcknowledgeDuplicateRisk {
return errors.New(usage)
}
if _, err := fmt.Fprintln(output, notification.DuplicateRiskWarning); err != nil {
return errors.New("could not write duplicate-risk warning")
}
if _, err := operator.RetryUnknown(ctx, command.DeliveryID, command.Actor, command.AcknowledgeDuplicateRisk); err != nil {
return safeOperationError(err)
}
if _, err := fmt.Fprintln(output, "retry scheduled; audit decision recorded"); err != nil {
return errors.New("retry was scheduled, but the result could not be written")
}
return nil
}
func envValue(lookup config.LookupEnv, name, fallback string) string {
value, ok := lookup(name)
if !ok || strings.TrimSpace(value) == "" {
return fallback
}
return value
}
func safeOperationError(err error) error {
switch {
case errors.Is(err, outbound.ErrDeliveryNotFound):
return errors.New("delivery not found")
case errors.Is(err, outbound.ErrDeliveryRetryNotAllowed):
return errors.New("delivery is not eligible for manual retry")
case errors.Is(err, notification.ErrDuplicateRiskAcknowledgementRequired):
return errors.New("duplicate-risk acknowledgement is required")
case errors.Is(err, domain.ErrInvalidDelivery):
return errors.New("delivery or actor is invalid")
default:
return errors.New("mail retry operation failed")
}
}
@@ -0,0 +1,142 @@
package mailretry
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
)
const testDeliveryID = "2e203b62-3fb5-4ef7-b118-360bbff7f2aa"
func TestParseRequiresExplicitCommandFields(t *testing.T) {
tests := []struct {
name string
args []string
want string
}{
{name: "command", args: nil, want: "usage:"},
{name: "unknown command", args: []string{"send"}, want: "usage:"},
{name: "inspect delivery", args: []string{"inspect"}, want: "non-zero UUID"},
{name: "invalid delivery", args: []string{"inspect", "--delivery", "not-a-uuid"}, want: "non-zero UUID"},
{name: "retry delivery", args: []string{"retry", "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk"}, want: "non-zero UUID"},
{name: "retry actor", args: []string{"retry", "--delivery", testDeliveryID, "--acknowledge-duplicate-risk"}, want: "actor must be"},
{name: "retry acknowledgement", args: []string{"retry", "--delivery", testDeliveryID, "--actor", "operator:mail-ops"}, want: "--acknowledge-duplicate-risk is required"},
{name: "invalid actor", args: []string{"retry", "--delivery", testDeliveryID, "--actor", "mail-ops", "--acknowledge-duplicate-risk"}, want: "actor must be"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := Parse(test.args)
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("Parse(%q) error = %v, want text %q", test.args, err, test.want)
}
})
}
}
func TestRunValidatesArgumentsBeforeReadingEnvironment(t *testing.T) {
var reads int
err := Run(context.Background(), []string{"retry", "--delivery", testDeliveryID, "--actor", "operator:mail-ops"}, func(string) (string, bool) {
reads++
return "", false
}, &bytes.Buffer{})
if err == nil || reads != 0 {
t.Fatalf("Run() error = %v, environment reads = %d; want argument error before config access", err, reads)
}
}
func TestRunDoesNotPrintDatabaseURL(t *testing.T) {
const secretURL = "postgres://operator:secret-password@127.0.0.1:1/mail"
lookup := func(key string) (string, bool) {
switch key {
case "DATABASE_URL":
return secretURL, true
case "EMAIL_PROVIDER":
return "resend", true
default:
return "", false
}
}
var output bytes.Buffer
err := Run(context.Background(), []string{"inspect", "--delivery", testDeliveryID}, lookup, &output)
if err == nil || strings.Contains(err.Error(), "secret-password") || strings.Contains(output.String(), "secret-password") {
t.Fatalf("Run() error/output leaked connection details: error %v, output %q", err, output.String())
}
}
func TestExecuteWarnsBeforeSchedulingAndRedactsMetadata(t *testing.T) {
deliveryID := uuid.MustParse(testDeliveryID)
var output bytes.Buffer
operator := &testOperator{
inspection: notification.DeliveryRetryInspection{
DeliveryID: deliveryID,
Provider: "resend",
ProviderAccount: "sensitive-account-label",
Status: domain.DeliveryStatusUnknown,
AttemptCount: 2,
},
output: &output,
}
command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true}
if err := Execute(context.Background(), command, operator, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if !operator.retryCalled || !strings.Contains(output.String(), notification.DuplicateRiskWarning) ||
strings.Contains(output.String(), "sensitive-account-label") {
t.Fatalf("Execute() output/calls = %q, %t; want warning before retry and redacted account", output.String(), operator.retryCalled)
}
}
func TestExecuteDoesNotScheduleWhenWarningCannotBeWritten(t *testing.T) {
deliveryID := uuid.MustParse(testDeliveryID)
operator := &testOperator{inspection: notification.DeliveryRetryInspection{DeliveryID: deliveryID, Status: domain.DeliveryStatusUnknown}}
command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true}
if err := Execute(context.Background(), command, operator, errorWriter{}); err == nil || operator.retryCalled {
t.Fatalf("Execute() error = %v, retry called = %t; want output error before mutation", err, operator.retryCalled)
}
}
func TestExecuteReturnsSafeStateError(t *testing.T) {
deliveryID := uuid.MustParse(testDeliveryID)
operator := &testOperator{
inspection: notification.DeliveryRetryInspection{DeliveryID: deliveryID, Status: domain.DeliveryStatusUnknown},
retryErr: errors.Join(outbound.ErrDeliveryRetryNotAllowed, errors.New("recipient private@example.invalid")),
}
var output bytes.Buffer
command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true}
err := Execute(context.Background(), command, operator, &output)
if err == nil || err.Error() != "delivery is not eligible for manual retry" || strings.Contains(err.Error(), "private@example.invalid") {
t.Fatalf("Execute() error = %v; want a safe state error", err)
}
}
type testOperator struct {
inspection notification.DeliveryRetryInspection
inspectErr error
retryErr error
output *bytes.Buffer
retryCalled bool
}
func (operator *testOperator) Inspect(context.Context, uuid.UUID) (notification.DeliveryRetryInspection, error) {
return operator.inspection, operator.inspectErr
}
func (operator *testOperator) RetryUnknown(context.Context, uuid.UUID, string, bool) (string, error) {
operator.retryCalled = true
if operator.output != nil && !strings.Contains(operator.output.String(), notification.DuplicateRiskWarning) {
return "", errors.New("retry called before warning")
}
return "", operator.retryErr
}
type errorWriter struct{}
func (errorWriter) Write([]byte) (int, error) { return 0, errors.New("output unavailable") }
@@ -0,0 +1,81 @@
package middleware
import (
"context"
"crypto/subtle"
"net/http"
"lincodex/backend/internal/domain"
)
const SessionCookieName = "__Host-lincodex_session"
type sessionRequestMetadataKey struct{}
type sessionRequestMetadata struct {
origin string
originValid bool
incomingToken domain.SecretToken
}
// SessionRequestMetadata records the browser Origin and an optional incoming
// session token for the handwritten identity operations. It never trusts
// forwarded headers and rejects duplicate or malformed cookie values.
func SessionRequestMetadata() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
metadata := sessionRequestMetadata{}
origins := r.Header.Values("Origin")
if len(origins) == 1 {
metadata.origin = origins[0]
metadata.originValid = true
}
cookieCount := 0
for _, cookie := range r.Cookies() {
if cookie.Name != SessionCookieName {
continue
}
cookieCount++
if token, err := domain.ParseSecretToken(cookie.Value); err == nil {
metadata.incomingToken = token
}
}
if cookieCount != 1 {
metadata.incomingToken = domain.SecretToken{}
}
ctx := context.WithValue(r.Context(), sessionRequestMetadataKey{}, metadata)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// RequestOrigin returns the sole Origin header value when one was provided.
func RequestOrigin(ctx context.Context) (string, bool) {
metadata, ok := ctx.Value(sessionRequestMetadataKey{}).(sessionRequestMetadata)
return metadata.origin, ok && metadata.originValid
}
// IncomingSessionToken returns a parsed token from exactly one session cookie.
// The zero value means missing, malformed, or duplicated input.
func IncomingSessionToken(ctx context.Context) domain.SecretToken {
metadata, ok := ctx.Value(sessionRequestMetadataKey{}).(sessionRequestMetadata)
if !ok {
return domain.SecretToken{}
}
return metadata.incomingToken
}
// SessionCookieMatches reports whether the generated API parser's value is
// the sole valid session cookie recorded at the HTTP boundary.
func SessionCookieMatches(ctx context.Context, rawToken string) bool {
stored := IncomingSessionToken(ctx)
if stored.IsZero() {
return false
}
provided, err := domain.ParseSecretToken(rawToken)
if err != nil {
return false
}
storedHash, providedHash := stored.Hash(), provided.Hash()
return subtle.ConstantTimeCompare(storedHash[:], providedHash[:]) == 1
}
@@ -0,0 +1,96 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"lincodex/backend/internal/domain"
)
func TestSessionRequestMetadataAcceptsOneOriginAndSessionCookie(t *testing.T) {
token, err := domain.NewSecretToken()
if err != nil {
t.Fatal(err)
}
var origin string
var originOK, cookieMatches bool
var incoming domain.SecretToken
handler := SessionRequestMetadata()(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
origin, originOK = RequestOrigin(request.Context())
incoming = IncomingSessionToken(request.Context())
cookieMatches = SessionCookieMatches(request.Context(), token.Reveal())
}))
request := httptest.NewRequest(http.MethodPost, "/api/v1/identity/sessions", nil)
request.Header.Set("Origin", "https://app.example.com")
request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: token.Reveal()})
handler.ServeHTTP(httptest.NewRecorder(), request)
if !originOK || origin != "https://app.example.com" || incoming.Hash() != token.Hash() || !cookieMatches {
t.Fatal("metadata did not preserve the sole Origin and parsed session cookie")
}
}
func TestSessionRequestMetadataRejectsAmbiguousOrMalformedBrowserHeaders(t *testing.T) {
token, err := domain.NewSecretToken()
if err != nil {
t.Fatal(err)
}
tests := map[string]func(*http.Request){
"duplicate cookie": func(request *http.Request) {
request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: token.Reveal()})
request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: token.Reveal()})
},
"malformed cookie": func(request *http.Request) {
request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: "short"})
},
"duplicate origin": func(request *http.Request) {
request.Header.Add("Origin", "https://app.example.com")
request.Header.Add("Origin", "https://attacker.example")
},
"forwarded origin only": func(request *http.Request) {
request.Header.Set("X-Forwarded-Host", "app.example.com")
},
}
for name, prepare := range tests {
t.Run(name, func(t *testing.T) {
var origin string
var originOK bool
var incoming domain.SecretToken
handler := SessionRequestMetadata()(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
origin, originOK = RequestOrigin(request.Context())
incoming = IncomingSessionToken(request.Context())
}))
request := httptest.NewRequest(http.MethodPost, "/api/v1/identity/sessions", nil)
prepare(request)
handler.ServeHTTP(httptest.NewRecorder(), request)
if originOK || origin != "" || !incoming.IsZero() {
t.Fatalf("ambiguous input was accepted: origin present=%v token present=%v", originOK, !incoming.IsZero())
}
})
}
}
func TestSessionCookieMatchesOnlyTheBoundaryToken(t *testing.T) {
first, err := domain.NewSecretToken()
if err != nil {
t.Fatal(err)
}
second, err := domain.NewSecretToken()
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodGet, "/api/v1/identity/me", nil)
request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: first.Reveal()})
var matches []bool
handler := SessionRequestMetadata()(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
matches = []bool{
SessionCookieMatches(request.Context(), first.Reveal()),
SessionCookieMatches(request.Context(), second.Reveal()),
SessionCookieMatches(request.Context(), "short"),
}
}))
handler.ServeHTTP(httptest.NewRecorder(), request)
if len(matches) != 3 || !matches[0] || matches[1] || matches[2] {
t.Fatalf("SessionCookieMatches() = %v", matches)
}
}
@@ -61,6 +61,9 @@ func NewRouter(
// The client address is resolved once, through the trusted proxies only,
// for the per-client rate limits of the handlers.
router.Use(httpmiddleware.ClientIP(trustedProxies))
// Login and logout compare one Origin header value exactly with the
// configured public origin. Session metadata never trusts forwarded headers.
router.Use(httpmiddleware.SessionRequestMetadata())
router.Use(httpmiddleware.RequestLog(logger, resolveRoute, healthPath, readinessPath))
router.Use(httpmiddleware.CollectMetrics(collector, resolveRoute))
router.Group(func(operational chi.Router) {
@@ -73,7 +76,7 @@ func NewRouter(
// server aborts the response; the kit Recoverer would swallow that panic.
router.Group(func(public chi.Router) {
public.Use(problems.Recover)
public.Handle(apiWildcard, apiServer)
public.Handle(apiWildcard, clearUnauthorizedLogoutCookie(apiServer))
// Unknown /api paths outside the versioned prefix are also problems,
// so every error under /api has the contract's format.
public.Handle(apiRoot, http.HandlerFunc(problems.NotFound))
@@ -82,6 +85,30 @@ func NewRouter(
return router, nil
}
func clearUnauthorizedLogoutCookie(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clearCookie := r.Method == http.MethodDelete && r.URL.Path == publicPrefix+"/identity/sessions/current"
next.ServeHTTP(&logoutCookieWriter{ResponseWriter: w, clearCookie: clearCookie}, r)
})
}
type logoutCookieWriter struct {
http.ResponseWriter
clearCookie bool
}
func (writer *logoutCookieWriter) WriteHeader(status int) {
if writer.clearCookie && status == http.StatusUnauthorized {
writer.Header().Add("Set-Cookie", v1.ExpiredSessionCookie())
}
writer.ResponseWriter.WriteHeader(status)
}
func (writer *logoutCookieWriter) Unwrap() http.ResponseWriter {
return writer.ResponseWriter
}
// apiWildcard is the chi pattern that mounts the generated server.
const apiWildcard = publicPrefix + "/*"
@@ -0,0 +1,65 @@
package v1
import (
"context"
"errors"
"github.com/ogen-go/ogen/ogenerrors"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/usecase/identity"
)
// Handler is the composite implementation of the generated api.Handler.
// Unimplemented operations stay on ogen's embedded fallback until a business
// handler is added for them.
type Handler struct {
api.UnimplementedHandler
health *HealthHandler
identity *IdentityHandler
problems *problem.Responder
}
var _ api.Handler = (*Handler)(nil)
// HandlerOption adds a business-area handler to Handler.
type HandlerOption func(*Handler)
// WithIdentity serves the configured identity operations.
func WithIdentity(identity *IdentityHandler) HandlerOption {
return func(handler *Handler) { handler.identity = identity }
}
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
handler := &Handler{health: health, problems: problems}
for _, option := range options {
option(handler)
}
return handler
}
// NewError maps security failures to fixed public problems. Other errors are
// passed to the responder, which logs them and does not expose their text.
func (handler *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
var securityError *ogenerrors.SecurityError
if errors.As(err, &securityError) {
switch {
case errors.Is(securityError.Err, errCsrfCheckFailed):
return problem.New(ctx, api.ProblemCodeCsrfCheckFailed)
case errors.Is(securityError.Err, ogenerrors.ErrSecurityRequirementIsNotSatisfied):
if _, ok := PrincipalFromContext(ctx); ok {
return problem.New(ctx, api.ProblemCodeCsrfCheckFailed)
}
return problem.New(ctx, api.ProblemCodeUnauthenticated)
case errors.Is(securityError.Err, ogenerrors.ErrSkipServerSecurity),
errors.Is(securityError.Err, identity.ErrUnauthenticated),
errors.Is(securityError.Err, errSessionsNotImplemented):
return problem.New(ctx, api.ProblemCodeUnauthenticated)
default:
return handler.problems.HandlerError(ctx, securityError.Err)
}
}
return handler.problems.HandlerError(ctx, err)
}
@@ -0,0 +1,292 @@
package v1
import (
"context"
"errors"
"math"
"net/http"
"strings"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/identity"
)
func (handler *Handler) RegisterAccount(
ctx context.Context,
request *api.RegistrationRequest,
params api.RegisterAccountParams,
) (api.RegisterAccountRes, error) {
if handler.identity == nil {
return handler.UnimplementedHandler.RegisterAccount(ctx, request, params)
}
return handler.identity.RegisterAccount(ctx, request, params)
}
func (handler *Handler) ResendEmailVerification(
ctx context.Context,
request *api.EmailVerificationResendRequest,
) (api.ResendEmailVerificationRes, error) {
if handler.identity == nil {
return handler.UnimplementedHandler.ResendEmailVerification(ctx, request)
}
return handler.identity.ResendEmailVerification(ctx, request)
}
func (handler *Handler) ConfirmEmail(
ctx context.Context,
request *api.EmailVerificationRequest,
params api.ConfirmEmailParams,
) (api.ConfirmEmailRes, error) {
if handler.identity == nil || handler.identity.confirmation == nil {
return handler.UnimplementedHandler.ConfirmEmail(ctx, request, params)
}
return handler.identity.ConfirmEmail(ctx, request, params)
}
func (handler *Handler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) {
if handler.identity == nil || handler.identity.sessions == nil {
return handler.UnimplementedHandler.Login(ctx, request)
}
return handler.identity.Login(ctx, request)
}
func (handler *Handler) GetCurrentSession(ctx context.Context) (api.GetCurrentSessionRes, error) {
if handler.identity == nil || handler.identity.sessions == nil {
return handler.UnimplementedHandler.GetCurrentSession(ctx)
}
return handler.identity.GetCurrentSession(ctx)
}
func (handler *Handler) Logout(ctx context.Context) (api.LogoutRes, error) {
if handler.identity == nil || handler.identity.sessions == nil {
return handler.UnimplementedHandler.Logout(ctx)
}
return handler.identity.Logout(ctx)
}
func (handler *IdentityHandler) RegisterAccount(
ctx context.Context,
request *api.RegistrationRequest,
params api.RegisterAccountParams,
) (api.RegisterAccountRes, error) {
err := handler.registration.Register(ctx, identity.RegisterCommand{
IdempotencyKey: params.IdempotencyKey,
Email: string(request.Email),
Password: string(request.Password),
Scenario: string(request.Scenario),
ConsentTextVersion: string(request.ConsentC1.TextVersion),
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return accepted(), nil
case errors.Is(err, identity.ErrInvalidField):
return (*api.RegisterAccountBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
case errors.Is(err, identity.ErrIdempotencyKeyReused):
return (*api.RegisterAccountUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func (handler *IdentityHandler) ResendEmailVerification(
ctx context.Context,
request *api.EmailVerificationResendRequest,
) (api.ResendEmailVerificationRes, error) {
if handler.registration == nil {
return nil, errors.New("IdentityHandler.ResendEmailVerification - registration is not configured")
}
err := handler.registration.ResendVerification(ctx, identity.ResendCommand{
Email: string(request.Email),
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return accepted(), nil
case errors.Is(err, identity.ErrInvalidField):
return (*api.ResendEmailVerificationBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func (handler *IdentityHandler) ConfirmEmail(
ctx context.Context,
request *api.EmailVerificationRequest,
params api.ConfirmEmailParams,
) (api.ConfirmEmailRes, error) {
if handler.confirmation == nil {
return nil, errors.New("IdentityHandler.ConfirmEmail - confirmation is not configured")
}
origin, ok := params.Origin.Get()
if !ok || strings.TrimSpace(origin) == "" || origin != handler.confirmationOrigin {
return (*api.ConfirmEmailForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
result, err := handler.confirmation.Confirm(ctx, identity.ConfirmCommand{
Token: string(request.Token),
Password: request.Password,
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return &api.EmailVerificationResult{
EmailVerified: api.EmailVerificationResultEmailVerifiedTrue,
Scenario: api.AccountScenario(result.Scenario),
OnboardingStep: api.OnboardingStep(result.OnboardingStep),
}, nil
case errors.Is(err, identity.ErrVerificationTokenInvalid):
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenInvalid).Response), nil
case errors.Is(err, identity.ErrVerificationTokenExpired):
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenExpired).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func (handler *IdentityHandler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) {
if !originAllowed(ctx, handler.sessionOrigin) {
return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
result, err := handler.sessions.Login(ctx, identity.LoginCommand{
Email: string(request.Email),
Password: string(request.Password),
ClientKey: clientKey(ctx),
Incoming: httpmiddleware.IncomingSessionToken(ctx),
})
switch {
case err == nil:
return &api.SessionHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
SetCookie: sessionCookie(result.Token, result.Session),
Response: api.Session{
Account: accountFromUser(result.User),
CsrfToken: api.CsrfToken(result.CSRFToken),
},
}, nil
case errors.Is(err, identity.ErrInvalidField):
return (*api.LoginBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
case errors.Is(err, identity.ErrInvalidCredentials):
return (*api.LoginUnauthorized)(&problem.New(ctx, api.ProblemCodeInvalidCredentials).Response), nil
case errors.Is(err, identity.ErrEmailNotVerified):
return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func (handler *IdentityHandler) GetCurrentSession(ctx context.Context) (api.GetCurrentSessionRes, error) {
session, ok := sessionFromContext(ctx)
if !ok || !session.EmailVerified {
return unauthenticatedProblemResponse(ctx), nil
}
return &api.GetCurrentSessionOKHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.Session{
Account: accountFromUser(session.User),
CsrfToken: api.CsrfToken(session.CSRFToken),
},
}, nil
}
func (handler *IdentityHandler) Logout(ctx context.Context) (api.LogoutRes, error) {
session, ok := sessionFromContext(ctx)
if !ok || !session.EmailVerified {
return unauthenticatedProblemResponse(ctx), nil
}
if err := handler.sessions.Logout(ctx, session.SessionID); err != nil {
if errors.Is(err, identity.ErrUnauthenticated) {
return unauthenticatedProblemResponse(ctx), nil
}
return nil, err
}
return &api.LogoutNoContent{SetCookie: ExpiredSessionCookie()}, nil
}
func accepted() *api.IdentityRequestAccepted {
return &api.IdentityRequestAccepted{Status: api.IdentityRequestAcceptedStatusAccepted}
}
// clientKey is the limiter key of the client address resolved through trusted
// proxies. Without the middleware only per-address limits apply.
func clientKey(ctx context.Context) string {
address, ok := httpmiddleware.ClientAddr(ctx)
if !ok {
return ""
}
return httpmiddleware.LimiterKey(address)
}
func invalidFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode {
field, ok := errors.AsType[*identity.InvalidFieldError](err)
if !ok {
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
}
location := api.ProblemFieldLocationBody
if field.Pointer == "/Idempotency-Key" {
location = api.ProblemFieldLocationHeader
}
return problem.InvalidField(ctx, location, field.Pointer)
}
func rateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) {
limited, ok := errors.AsType[*identity.RateLimitedError](err)
if !ok {
return nil, false
}
return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), true
}
func wholeSeconds(wait time.Duration) int32 {
return int32(min(math.Ceil(wait.Seconds()), math.MaxInt32))
}
func originAllowed(ctx context.Context, expected string) bool {
origin, ok := httpmiddleware.RequestOrigin(ctx)
return ok && origin == expected
}
func unauthenticatedProblemResponse(ctx context.Context) *api.Problem {
response := problem.New(ctx, api.ProblemCodeUnauthenticated).Response
return &response
}
func sessionCookie(token domain.SecretToken, session domain.Session) string {
maxAge := int(math.Ceil(session.ExpiresAt.Sub(session.CreatedAt).Seconds()))
cookie := &http.Cookie{
Name: httpmiddleware.SessionCookieName,
Value: token.Reveal(),
Path: "/",
MaxAge: maxAge,
Expires: session.ExpiresAt.UTC(),
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
}
return cookie.String()
}
func ExpiredSessionCookie() string {
return (&http.Cookie{
Name: httpmiddleware.SessionCookieName,
Value: "",
Path: "/",
MaxAge: -1,
Expires: time.Unix(1, 0).UTC(),
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
}).String()
}
@@ -1,98 +0,0 @@
package v1
import (
"context"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
)
// Handler is the composite implementation of the generated api.Handler.
//
// The embedded api.UnimplementedHandler keeps the backend compiling after the
// contract gains an operation that has no business implementation yet. Such an
// operation returns ht.ErrNotImplemented without side effects. The generated
// server passes that error to the ErrorHandler configured in the router, which
// answers 501 with code not_implemented, before it would call NewError.
//
// The contract's common default response makes ogen add NewError to
// api.Handler. The embedded api.UnimplementedHandler.NewError returns a zero
// status code that the generated encoder sends as HTTP 200, so Handler defines
// NewError explicitly: *ogenerrors.SecurityError, which the generated server
// passes to it directly, becomes 401, and every other error becomes 500 with a
// fixed body and is logged here, never exposing err.Error(). Errors of the
// generated *api.ProblemStatusCode type are encoded before NewError is called,
// so operations return them for expected failures such as 403 or 404.
//
// Each implemented operation gets an explicit method here that delegates to
// the handler owning it. Each implemented operation also gets a router test
// through v1.NewHandler that asserts a non-501 response, because renaming an
// operationId would otherwise silently fall back to the embedded 501 method.
type Handler struct {
api.UnimplementedHandler
health *HealthHandler
identity *IdentityHandler
problems *problem.Responder
}
var _ api.Handler = (*Handler)(nil)
// HandlerOption adds the handler of a business area to Handler.
type HandlerOption func(*Handler)
// WithIdentity serves the registration operations. A nil handler leaves them
// to the embedded api.UnimplementedHandler, as when no database is
// configured.
func WithIdentity(identity *IdentityHandler) HandlerOption {
return func(handler *Handler) { handler.identity = identity }
}
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
handler := &Handler{health: health, problems: problems}
for _, option := range options {
option(handler)
}
return handler
}
func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) {
return handler.health.GetHealthz(ctx)
}
func (handler *Handler) RegisterAccount(
ctx context.Context,
request *api.RegistrationRequest,
params api.RegisterAccountParams,
) (api.RegisterAccountRes, error) {
if handler.identity == nil {
return handler.UnimplementedHandler.RegisterAccount(ctx, request, params)
}
return handler.identity.RegisterAccount(ctx, request, params)
}
func (handler *Handler) ResendEmailVerification(
ctx context.Context,
request *api.EmailVerificationResendRequest,
) (api.ResendEmailVerificationRes, error) {
if handler.identity == nil {
return handler.UnimplementedHandler.ResendEmailVerification(ctx, request)
}
return handler.identity.ResendEmailVerification(ctx, request)
}
func (handler *Handler) ConfirmEmail(
ctx context.Context,
request *api.EmailVerificationRequest,
params api.ConfirmEmailParams,
) (api.ConfirmEmailRes, error) {
if handler.identity == nil || handler.identity.confirmation == nil {
return handler.UnimplementedHandler.ConfirmEmail(ctx, request, params)
}
return handler.identity.ConfirmEmail(ctx, request, params)
}
// NewError implements api.Handler for errors returned by operations.
func (handler *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
return handler.problems.HandlerError(ctx, err)
}
@@ -23,6 +23,10 @@ func (handler *HealthHandler) GetHealthz(context.Context) (*api.HealthResponse,
return &api.HealthResponse{Status: api.HealthResponseStatusOk}, nil
}
func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) {
return handler.health.GetHealthz(ctx)
}
func (handler *HealthHandler) Healthz(w http.ResponseWriter, _ *http.Request) {
writeStatus(w, http.StatusOK, "ok")
}
@@ -2,14 +2,7 @@ package v1
import (
"context"
"errors"
"math"
"strings"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/usecase/identity"
)
@@ -28,12 +21,13 @@ type EmailConfirmation interface {
// IdentityHandlerOption configures an optional identity operation.
type IdentityHandlerOption func(*IdentityHandler)
// IdentityHandler serves anonymous registration, resend, and confirmation
// operations.
// IdentityHandler serves authentication and account identity operations.
type IdentityHandler struct {
registration AccountRegistration
confirmation EmailConfirmation
confirmationOrigin string
sessions *identity.SessionService
sessionOrigin string
}
func NewIdentityHandler(registration AccountRegistration, options ...IdentityHandlerOption) *IdentityHandler {
@@ -53,130 +47,12 @@ func WithEmailConfirmation(confirmation EmailConfirmation, publicOrigin string)
}
}
func (handler *IdentityHandler) RegisterAccount(
ctx context.Context,
request *api.RegistrationRequest,
params api.RegisterAccountParams,
) (api.RegisterAccountRes, error) {
err := handler.registration.Register(ctx, identity.RegisterCommand{
IdempotencyKey: params.IdempotencyKey,
Email: string(request.Email),
Password: string(request.Password),
Scenario: string(request.Scenario),
ConsentTextVersion: string(request.ConsentC1.TextVersion),
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return accepted(), nil
case errors.Is(err, identity.ErrInvalidField):
return (*api.RegisterAccountBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
case errors.Is(err, identity.ErrIdempotencyKeyReused):
return (*api.RegisterAccountUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
// WithSessionService serves login, current account, current session, and
// logout against PostgreSQL-backed sessions. Unsafe browser operations compare
// Origin exactly with the configured public origin.
func WithSessionService(sessions *identity.SessionService, publicOrigin string) IdentityHandlerOption {
return func(handler *IdentityHandler) {
handler.sessions = sessions
handler.sessionOrigin = publicOrigin
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func (handler *IdentityHandler) ResendEmailVerification(
ctx context.Context,
request *api.EmailVerificationResendRequest,
) (api.ResendEmailVerificationRes, error) {
if handler.registration == nil {
return nil, errors.New("IdentityHandler.ResendEmailVerification - registration is not configured")
}
err := handler.registration.ResendVerification(ctx, identity.ResendCommand{
Email: string(request.Email),
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return accepted(), nil
case errors.Is(err, identity.ErrInvalidField):
return (*api.ResendEmailVerificationBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func (handler *IdentityHandler) ConfirmEmail(
ctx context.Context,
request *api.EmailVerificationRequest,
params api.ConfirmEmailParams,
) (api.ConfirmEmailRes, error) {
if handler.confirmation == nil {
return nil, errors.New("IdentityHandler.ConfirmEmail - confirmation is not configured")
}
origin, ok := params.Origin.Get()
if !ok || strings.TrimSpace(origin) == "" || origin != handler.confirmationOrigin {
return (*api.ConfirmEmailForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
result, err := handler.confirmation.Confirm(ctx, identity.ConfirmCommand{
Token: string(request.Token),
Password: request.Password,
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return &api.EmailVerificationResult{
EmailVerified: api.EmailVerificationResultEmailVerifiedTrue,
Scenario: api.AccountScenario(result.Scenario),
OnboardingStep: api.OnboardingStep(result.OnboardingStep),
}, nil
case errors.Is(err, identity.ErrVerificationTokenInvalid):
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenInvalid).Response), nil
case errors.Is(err, identity.ErrVerificationTokenExpired):
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenExpired).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func accepted() *api.IdentityRequestAccepted {
return &api.IdentityRequestAccepted{Status: api.IdentityRequestAcceptedStatusAccepted}
}
// clientKey is the limiter key of the client network address that the
// ClientIP middleware resolved. Without it, for example when the middleware
// is not mounted, the per-client limit is skipped and only the per-address
// limits apply: a shared bucket would let one client lock everyone out.
func clientKey(ctx context.Context) string {
address, ok := httpmiddleware.ClientAddr(ctx)
if !ok {
return ""
}
return httpmiddleware.LimiterKey(address)
}
func invalidFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode {
field, ok := errors.AsType[*identity.InvalidFieldError](err)
if !ok {
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
}
location := api.ProblemFieldLocationBody
if field.Pointer == "/Idempotency-Key" {
location = api.ProblemFieldLocationHeader
}
return problem.InvalidField(ctx, location, field.Pointer)
}
func rateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) {
limited, ok := errors.AsType[*identity.RateLimitedError](err)
if !ok {
return nil, false
}
return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), true
}
// wholeSeconds rounds a wait up, so a client that waits the stated time is
// not refused again for the remainder.
func wholeSeconds(wait time.Duration) int32 {
return int32(min(math.Ceil(wait.Seconds()), math.MaxInt32))
}
@@ -0,0 +1,59 @@
package v1
import (
"context"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/identity"
)
type principalContextKey struct{}
type sessionContextKey struct{}
// Principal is the authenticated account identity available to handwritten
// HTTP handlers. The ID comes from PostgreSQL session state, never a request
// body or path parameter.
type Principal struct {
UserID uuid.UUID
EmailVerified bool
}
type authenticatedSession struct {
Principal
User domain.User
SessionID uuid.UUID
CSRFToken string
}
// PrincipalFromContext returns the account identity installed by session
// security middleware, if the request has an authenticated session.
func PrincipalFromContext(ctx context.Context) (Principal, bool) {
if ctx == nil {
return Principal{}, false
}
principal, ok := ctx.Value(principalContextKey{}).(Principal)
return principal, ok && principal.UserID != uuid.Nil
}
func withAuthenticatedSession(ctx context.Context, session identity.AuthenticatedSession) context.Context {
principal := Principal{UserID: session.User.ID, EmailVerified: session.User.EmailVerified()}
ctx = context.WithValue(ctx, principalContextKey{}, principal)
return context.WithValue(ctx, sessionContextKey{}, authenticatedSession{
Principal: principal,
User: session.User,
SessionID: session.SessionID,
CSRFToken: session.CSRFToken,
})
}
func sessionFromContext(ctx context.Context) (authenticatedSession, bool) {
if ctx == nil {
return authenticatedSession{}, false
}
session, ok := ctx.Value(sessionContextKey{}).(authenticatedSession)
return session, ok && session.UserID != uuid.Nil && session.SessionID != uuid.Nil
}
@@ -0,0 +1,89 @@
package v1
import (
"context"
"crypto/hmac"
"errors"
"fmt"
"github.com/ogen-go/ogen/ogenerrors"
"lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/usecase/identity"
)
var errCsrfCheckFailed = errors.New("CSRF check failed")
type SessionAuthenticator interface {
Authenticate(ctx context.Context, rawToken string) (identity.AuthenticatedSession, error)
}
// SessionSecurity authenticates only the three session operations enabled in
// this implementation. All other protected operations remain unavailable until their
// handlers are implemented.
type SessionSecurity struct {
authenticator SessionAuthenticator
publicOrigin string
}
var _ api.SecurityHandler = (*SessionSecurity)(nil)
func NewSessionSecurity(authenticator SessionAuthenticator, publicOrigin string) *SessionSecurity {
return &SessionSecurity{authenticator: authenticator, publicOrigin: publicOrigin}
}
func (handler *IdentityHandler) SessionSecurity() *SessionSecurity {
if handler == nil || handler.sessions == nil {
return NewSessionSecurity(nil, "")
}
return NewSessionSecurity(handler.sessions, handler.sessionOrigin)
}
func (security *SessionSecurity) HandleSessionCookie(
ctx context.Context,
operation api.OperationName,
cookie api.SessionCookie,
) (context.Context, error) {
if !sessionOperationAllowed(operation) || security == nil || security.authenticator == nil ||
!httpmiddleware.SessionCookieMatches(ctx, cookie.APIKey) {
return ctx, ogenerrors.ErrSkipServerSecurity
}
authenticated, err := security.authenticator.Authenticate(ctx, cookie.APIKey)
if errors.Is(err, identity.ErrUnauthenticated) {
return ctx, ogenerrors.ErrSkipServerSecurity
}
if err != nil {
return ctx, fmt.Errorf("SessionSecurity.HandleSessionCookie - authenticate session: %w", err)
}
return withAuthenticatedSession(ctx, authenticated), nil
}
func (security *SessionSecurity) HandleSessionCsrf(
ctx context.Context,
operation api.OperationName,
csrf api.SessionCsrf,
) (context.Context, error) {
if operation != api.LogoutOperation {
return ctx, ogenerrors.ErrSkipServerSecurity
}
authenticated, ok := sessionFromContext(ctx)
if !ok {
return ctx, ogenerrors.ErrSkipServerSecurity
}
origin, hasOrigin := httpmiddleware.RequestOrigin(ctx)
if security == nil || !hasOrigin || origin != security.publicOrigin || authenticated.CSRFToken == "" ||
!hmac.Equal([]byte(authenticated.CSRFToken), []byte(csrf.APIKey)) {
return ctx, errCsrfCheckFailed
}
return ctx, nil
}
func sessionOperationAllowed(operation api.OperationName) bool {
switch operation {
case api.GetCurrentSessionOperation, api.GetCurrentAccountOperation, api.LogoutOperation:
return true
default:
return false
}
}
@@ -0,0 +1,200 @@
package v1
import (
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/ogen-go/ogen/ogenerrors"
"lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/identity"
)
type sessionAuthenticatorStub struct {
result identity.AuthenticatedSession
err error
calls int
}
func (authenticator *sessionAuthenticatorStub) Authenticate(_ context.Context, _ string) (identity.AuthenticatedSession, error) {
authenticator.calls++
return authenticator.result, authenticator.err
}
func TestSessionSecurityAddsPrincipalOnlyForTheThreeEnabledOperations(t *testing.T) {
token, err := domain.NewSecretToken()
if err != nil {
t.Fatal(err)
}
userID := uuid.New()
verifiedAt := time.Now()
authenticator := &sessionAuthenticatorStub{result: identity.AuthenticatedSession{
User: domain.User{ID: userID, EmailVerifiedAt: &verifiedAt},
SessionID: uuid.New(),
CSRFToken: "bound-csrf-token",
}}
security := NewSessionSecurity(authenticator, "https://app.example.com")
for _, operation := range []api.OperationName{
api.GetCurrentAccountOperation,
api.GetCurrentSessionOperation,
api.LogoutOperation,
} {
ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com")
authenticated, err := security.HandleSessionCookie(ctx, operation, api.SessionCookie{APIKey: token.Reveal()})
if err != nil {
t.Fatalf("HandleSessionCookie(%s) error = %v", operation, err)
}
principal, ok := PrincipalFromContext(authenticated)
if !ok || principal.UserID != userID || !principal.EmailVerified {
t.Fatalf("PrincipalFromContext(%s) = %+v, %v", operation, principal, ok)
}
}
if authenticator.calls != 3 {
t.Fatalf("authentication calls = %d, want one for each allowed operation", authenticator.calls)
}
ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com")
_, err = security.HandleSessionCookie(ctx, api.GetMyProfileOperation, api.SessionCookie{APIKey: token.Reveal()})
if !errors.Is(err, ogenerrors.ErrSkipServerSecurity) || authenticator.calls != 3 {
t.Fatalf("disallowed operation error=%v authentication calls=%d", err, authenticator.calls)
}
}
func TestLogoutRequiresExactOriginAndSessionBoundCSRF(t *testing.T) {
token, err := domain.NewSecretToken()
if err != nil {
t.Fatal(err)
}
verifiedAt := time.Now()
authenticator := &sessionAuthenticatorStub{result: identity.AuthenticatedSession{
User: domain.User{ID: uuid.New(), EmailVerifiedAt: &verifiedAt},
SessionID: uuid.New(),
CSRFToken: "csrf-for-this-session",
}}
security := NewSessionSecurity(authenticator, "https://app.example.com")
for _, test := range []struct {
name string
origin string
csrf string
wantErr error
}{
{name: "valid pair", origin: "https://app.example.com", csrf: "csrf-for-this-session"},
{name: "wrong token", origin: "https://app.example.com", csrf: "csrf-from-another-session", wantErr: errCsrfCheckFailed},
{name: "wrong origin", origin: "https://attacker.example", csrf: "csrf-for-this-session", wantErr: errCsrfCheckFailed},
{name: "missing origin", csrf: "csrf-for-this-session", wantErr: errCsrfCheckFailed},
} {
t.Run(test.name, func(t *testing.T) {
ctx := sessionRequestContext(t, token.Reveal(), test.origin)
ctx, err := security.HandleSessionCookie(ctx, api.LogoutOperation, api.SessionCookie{APIKey: token.Reveal()})
if err != nil {
t.Fatalf("HandleSessionCookie() error = %v", err)
}
_, err = security.HandleSessionCsrf(ctx, api.LogoutOperation, api.SessionCsrf{APIKey: test.csrf})
if !errors.Is(err, test.wantErr) {
t.Fatalf("HandleSessionCsrf() error = %v, want %v", err, test.wantErr)
}
})
}
}
func TestSecurityErrorsMapToUnauthenticatedOrCSRFProblem(t *testing.T) {
logger := slog.New(slog.NewTextHandler(&strings.Builder{}, nil))
handler := NewHandler(nil, problem.NewResponder(logger))
tests := []struct {
name string
ctx context.Context
err error
want api.ProblemCode
wantStatus int
}{
{name: "missing cookie", ctx: context.Background(), err: &ogenerrors.SecurityError{Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied}, want: api.ProblemCodeUnauthenticated, wantStatus: http.StatusUnauthorized},
{name: "missing csrf with principal", ctx: principalTestContext(), err: &ogenerrors.SecurityError{Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied}, want: api.ProblemCodeCsrfCheckFailed, wantStatus: http.StatusForbidden},
{name: "bad csrf", err: &ogenerrors.SecurityError{Security: "SessionCsrf", Err: errCsrfCheckFailed}, want: api.ProblemCodeCsrfCheckFailed, wantStatus: http.StatusForbidden},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctx := test.ctx
if ctx == nil {
ctx = context.Background()
}
response := handler.NewError(ctx, test.err)
if response.StatusCode != test.wantStatus || response.Response.Code != test.want {
t.Fatalf("NewError() = %d %s, want %d %s", response.StatusCode, response.Response.Code, test.wantStatus, test.want)
}
})
}
}
func TestSessionCookiesUseRequiredAttributesAndClearStaleValues(t *testing.T) {
token, err := domain.NewSecretToken()
if err != nil {
t.Fatal(err)
}
start := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
session, err := domain.NewSession(domain.NewSessionInput{
UserID: uuid.New(), TokenHash: token.Hash(), StartedAt: start, AbsoluteLifetime: 168 * time.Hour,
})
if err != nil {
t.Fatal(err)
}
response := &http.Response{Header: http.Header{"Set-Cookie": {sessionCookie(token, session)}}}
cookies := response.Cookies()
if len(cookies) != 1 {
t.Fatalf("login cookie count = %d", len(cookies))
}
cookie := cookies[0]
if cookie.Name != httpmiddleware.SessionCookieName || cookie.Value != token.Reveal() || cookie.Path != "/" ||
cookie.Domain != "" || !cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode ||
cookie.MaxAge != int((168*time.Hour).Seconds()) || !cookie.Expires.Equal(session.ExpiresAt) {
t.Fatalf("login cookie attributes = %+v", cookie)
}
clearResponse := &http.Response{Header: http.Header{"Set-Cookie": {ExpiredSessionCookie()}}}
cleared := clearResponse.Cookies()
if len(cleared) != 1 || cleared[0].Name != httpmiddleware.SessionCookieName || cleared[0].Value != "" ||
cleared[0].Path != "/" || cleared[0].MaxAge >= 0 || !cleared[0].Secure || !cleared[0].HttpOnly ||
cleared[0].SameSite != http.SameSiteStrictMode {
t.Fatalf("logout clearing cookie = %+v", cleared)
}
}
func sessionRequestContext(t *testing.T, rawToken, origin string) context.Context {
t.Helper()
request := httptest.NewRequest(http.MethodGet, "/api/v1/identity/me", nil)
if origin != "" {
request.Header.Set("Origin", origin)
}
if rawToken != "" {
request.AddCookie(&http.Cookie{Name: httpmiddleware.SessionCookieName, Value: rawToken})
}
capture := &sessionContextCapture{}
httpmiddleware.SessionRequestMetadata()(capture).ServeHTTP(httptest.NewRecorder(), request)
if capture.ctx == nil {
t.Fatal("session request middleware did not pass a context")
}
return capture.ctx
}
type sessionContextCapture struct {
ctx context.Context
}
func (capture *sessionContextCapture) ServeHTTP(_ http.ResponseWriter, request *http.Request) {
capture.ctx = request.Context()
}
func principalTestContext() context.Context {
return context.WithValue(context.Background(), principalContextKey{}, Principal{UserID: uuid.New(), EmailVerified: true})
}
@@ -0,0 +1,37 @@
package v1
import (
"context"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
)
func (handler *Handler) GetCurrentAccount(ctx context.Context) (api.GetCurrentAccountRes, error) {
if handler.identity == nil || handler.identity.sessions == nil {
return handler.UnimplementedHandler.GetCurrentAccount(ctx)
}
return handler.identity.GetCurrentAccount(ctx)
}
func (handler *IdentityHandler) GetCurrentAccount(ctx context.Context) (api.GetCurrentAccountRes, error) {
session, ok := sessionFromContext(ctx)
if !ok || !session.EmailVerified {
return unauthenticatedProblemResponse(ctx), nil
}
return &api.AccountHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: accountFromUser(session.User),
}, nil
}
func accountFromUser(user domain.User) api.Account {
return api.Account{
ID: user.ID,
Email: api.EmailAddress(user.Email.Address()),
EmailVerified: user.EmailVerified(),
Scenario: api.AccountScenario(user.Scenario),
OnboardingStep: api.OnboardingStep(user.OnboardingStep),
CreatedAt: api.Timestamp(user.CreatedAt),
}
}