feat(identity): add server sessions and audited mail recovery
This commit is contained in:
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),
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,12 @@ type Reply struct {
|
||||
// Name is the Resend error name for a non-2xx answer, for example
|
||||
// "daily_quota_exceeded".
|
||||
Name string
|
||||
// RetryAfter is copied to the response header for a rate-limit fixture.
|
||||
RetryAfter string
|
||||
// DropAfterAccept stores the message and closes the connection without an
|
||||
// HTTP answer, like a provider accepting the request before the response
|
||||
// is lost.
|
||||
DropAfterAccept bool
|
||||
}
|
||||
|
||||
// Server is the fixture. Create it with New.
|
||||
@@ -61,17 +67,22 @@ type Server struct {
|
||||
mu sync.Mutex
|
||||
requests []Request
|
||||
messages map[string]message // by idempotency key
|
||||
accepted int
|
||||
scripted []Reply
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
type message struct {
|
||||
id string
|
||||
body string
|
||||
id string
|
||||
body string
|
||||
acceptedAt time.Time
|
||||
}
|
||||
|
||||
const providerIdempotencyWindow = 24 * time.Hour
|
||||
|
||||
// New starts the fixture on a loopback address.
|
||||
func New() *Server {
|
||||
server := &Server{messages: make(map[string]message)}
|
||||
server := &Server{messages: make(map[string]message), clock: time.Now}
|
||||
server.http = httptest.NewServer(http.HandlerFunc(server.serve))
|
||||
return server
|
||||
}
|
||||
@@ -94,6 +105,18 @@ func (server *Server) Script(replies ...Reply) {
|
||||
// test can act while a send is in flight.
|
||||
func (server *Server) SetDelay(delay time.Duration) { server.delay.Store(int64(delay)) }
|
||||
|
||||
// SetClock replaces the provider clock so tests can expire idempotency keys
|
||||
// without waiting in real time.
|
||||
func (server *Server) SetClock(clock func() time.Time) {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
if clock == nil {
|
||||
server.clock = time.Now
|
||||
return
|
||||
}
|
||||
server.clock = clock
|
||||
}
|
||||
|
||||
// Arrivals returns how many calls the fixture has received, answered or
|
||||
// not yet.
|
||||
func (server *Server) Arrivals() int { return int(server.arrivals.Load()) }
|
||||
@@ -110,7 +133,7 @@ func (server *Server) Requests() []Request {
|
||||
func (server *Server) Messages() int {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
return len(server.messages)
|
||||
return server.accepted
|
||||
}
|
||||
|
||||
func (server *Server) serve(response http.ResponseWriter, request *http.Request) {
|
||||
@@ -118,18 +141,26 @@ func (server *Server) serve(response http.ResponseWriter, request *http.Request)
|
||||
if delay := time.Duration(server.delay.Load()); delay > 0 {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
payload, record, ok := readRequest(response, request)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
server.handleEmail(response, payload, record)
|
||||
}
|
||||
|
||||
func readRequest(response http.ResponseWriter, request *http.Request) ([]byte, Request, bool) {
|
||||
if request.Method != http.MethodPost || request.URL.Path != "/emails" {
|
||||
writeError(response, http.StatusNotFound, "not_found")
|
||||
return
|
||||
return nil, Request{}, false
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 {
|
||||
writeError(response, http.StatusUnauthorized, "invalid_api_key")
|
||||
return
|
||||
return nil, Request{}, false
|
||||
}
|
||||
payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes))
|
||||
if err != nil {
|
||||
writeError(response, http.StatusBadRequest, "invalid_parameter")
|
||||
return
|
||||
return nil, Request{}, false
|
||||
}
|
||||
var body struct {
|
||||
To []string `json:"to"`
|
||||
@@ -139,41 +170,78 @@ func (server *Server) serve(response http.ResponseWriter, request *http.Request)
|
||||
}
|
||||
if err := json.Unmarshal(payload, &body); err != nil {
|
||||
writeError(response, http.StatusBadRequest, "invalid_parameter")
|
||||
return
|
||||
return nil, Request{}, false
|
||||
}
|
||||
key := request.Header.Get("Idempotency-Key")
|
||||
record := Request{IdempotencyKey: key, To: body.To, Subject: body.Subject, Text: body.Text, HTML: body.HTML}
|
||||
return payload, Request{
|
||||
IdempotencyKey: request.Header.Get("Idempotency-Key"),
|
||||
To: body.To,
|
||||
Subject: body.Subject,
|
||||
Text: body.Text,
|
||||
HTML: body.HTML,
|
||||
}, true
|
||||
}
|
||||
|
||||
func (server *Server) handleEmail(response http.ResponseWriter, payload []byte, record Request) {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
reply := Reply{}
|
||||
if len(server.scripted) > 0 {
|
||||
reply := server.scripted[0]
|
||||
reply = server.scripted[0]
|
||||
server.scripted = server.scripted[1:]
|
||||
}
|
||||
now := server.clock()
|
||||
known, seen := server.messages[record.IdempotencyKey]
|
||||
if seen && now.Sub(known.acceptedAt) >= providerIdempotencyWindow {
|
||||
delete(server.messages, record.IdempotencyKey)
|
||||
seen = false
|
||||
}
|
||||
if reply.Status != 0 {
|
||||
server.requests = append(server.requests, record)
|
||||
server.mu.Unlock()
|
||||
if reply.RetryAfter != "" {
|
||||
response.Header().Set("Retry-After", reply.RetryAfter)
|
||||
}
|
||||
writeError(response, reply.Status, reply.Name)
|
||||
return
|
||||
}
|
||||
known, seen := server.messages[key]
|
||||
switch {
|
||||
case seen && known.body != string(payload):
|
||||
// The key was used with another body: Resend refuses it.
|
||||
server.requests = append(server.requests, record)
|
||||
messageID, replayed, conflict := server.recordAcceptanceLocked(record.IdempotencyKey, string(payload), now, known, seen)
|
||||
record.Replayed = replayed
|
||||
server.requests = append(server.requests, record)
|
||||
server.mu.Unlock()
|
||||
if conflict {
|
||||
writeError(response, http.StatusConflict, "invalid_idempotent_request")
|
||||
return
|
||||
case seen:
|
||||
record.Replayed = true
|
||||
server.requests = append(server.requests, record)
|
||||
writeAccepted(response, known.id)
|
||||
}
|
||||
if reply.DropAfterAccept {
|
||||
dropConnection(response)
|
||||
return
|
||||
}
|
||||
accepted := message{id: uuid.NewString(), body: string(payload)}
|
||||
writeAccepted(response, messageID)
|
||||
}
|
||||
|
||||
func (server *Server) recordAcceptanceLocked(key, body string, now time.Time, known message, seen bool) (string, bool, bool) {
|
||||
if seen {
|
||||
if known.body != body {
|
||||
return "", false, true
|
||||
}
|
||||
return known.id, true, false
|
||||
}
|
||||
accepted := message{id: uuid.NewString(), body: body, acceptedAt: now}
|
||||
if key != "" {
|
||||
server.messages[key] = accepted
|
||||
} else {
|
||||
server.messages[accepted.id] = accepted
|
||||
}
|
||||
server.requests = append(server.requests, record)
|
||||
writeAccepted(response, accepted.id)
|
||||
server.accepted++
|
||||
return accepted.id, false, false
|
||||
}
|
||||
|
||||
func dropConnection(response http.ResponseWriter) {
|
||||
if hijacker, ok := response.(http.Hijacker); ok {
|
||||
connection, _, err := hijacker.Hijack()
|
||||
if err == nil {
|
||||
_ = connection.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeAccepted(response http.ResponseWriter, id string) {
|
||||
|
||||
@@ -141,7 +141,95 @@ func (repository deliveryRepository) Get(ctx context.Context, id uuid.UUID) (dom
|
||||
if err != nil {
|
||||
return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", mapDeliveryError(err))
|
||||
}
|
||||
return deliveryFromRow(row)
|
||||
return deliveryFromRow(sqlc.Delivery{
|
||||
ID: row.ID,
|
||||
SourceEventID: row.SourceEventID,
|
||||
RecipientUserID: row.RecipientUserID,
|
||||
RecipientEmail: row.RecipientEmail,
|
||||
Kind: row.Kind,
|
||||
TemplateVersion: row.TemplateVersion,
|
||||
Subject: row.Subject,
|
||||
TextBody: row.TextBody,
|
||||
HtmlBody: row.HtmlBody,
|
||||
ContentSha256: row.ContentSha256,
|
||||
Provider: row.Provider,
|
||||
ProviderAccount: row.ProviderAccount,
|
||||
IdempotencyKey: row.IdempotencyKey,
|
||||
Status: row.Status,
|
||||
AttemptCount: row.AttemptCount,
|
||||
NextAttemptAt: row.NextAttemptAt,
|
||||
LastAttemptAt: row.LastAttemptAt,
|
||||
ProviderMessageID: row.ProviderMessageID,
|
||||
Version: row.Version,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
EmailTokenID: row.EmailTokenID,
|
||||
CancelReason: row.CancelReason,
|
||||
ClaimOwner: row.ClaimOwner,
|
||||
ClaimedUntil: row.ClaimedUntil,
|
||||
FirstSendStartedAt: row.FirstSendStartedAt,
|
||||
FailureCount: row.FailureCount,
|
||||
BodyRedactedAt: row.BodyRedactedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) GetRetrySnapshot(ctx context.Context, id uuid.UUID) (outbound.DeliveryRetrySnapshot, error) {
|
||||
const location = "deliveryRepository.GetRetrySnapshot"
|
||||
row, err := repository.queries.GetDeliveryRetrySnapshot(ctx, pgUUID(id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - select delivery: %w", location, outbound.ErrDeliveryNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - select delivery: %w", location, mapDeliveryError(err))
|
||||
}
|
||||
if _, err := domain.NewMailProviderAccount(row.Provider, row.ProviderAccount); err != nil {
|
||||
return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - decode provider account: %w", location, err)
|
||||
}
|
||||
status, err := domain.ParseDeliveryStatus(row.Status)
|
||||
if err != nil {
|
||||
return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - decode status: %w", location, err)
|
||||
}
|
||||
return outbound.DeliveryRetrySnapshot{
|
||||
ID: uuid.UUID(row.ID.Bytes),
|
||||
Provider: row.Provider,
|
||||
ProviderAccount: row.ProviderAccount,
|
||||
Status: status,
|
||||
AttemptCount: row.AttemptCount,
|
||||
NextAttemptAt: zeroableTime(row.NextAttemptAt),
|
||||
FirstSendStartedAt: zeroableTime(row.FirstSendStartedAt),
|
||||
ManualRetryStartedAt: zeroableTime(row.ManualRetryStartedAt),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) AuthorizeUnknownRetry(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
account domain.MailProviderAccount,
|
||||
actor domain.MailRetryActor,
|
||||
acknowledgeDuplicateRisk bool,
|
||||
at time.Time,
|
||||
minimumAge time.Duration,
|
||||
) error {
|
||||
const location = "deliveryRepository.AuthorizeUnknownRetry"
|
||||
if id == uuid.Nil || account.IsZero() || actor == "" || !acknowledgeDuplicateRisk || at.IsZero() || minimumAge < 0 {
|
||||
return fmt.Errorf("%s - invalid authorization request: %w", location, outbound.ErrDeliveryRetryNotAllowed)
|
||||
}
|
||||
updated, err := repository.queries.AuthorizeUnknownDeliveryRetry(ctx, sqlc.AuthorizeUnknownDeliveryRetryParams{
|
||||
Actor: string(actor),
|
||||
DuplicateRiskAcknowledged: acknowledgeDuplicateRisk,
|
||||
DeliveryID: pgUUID(id),
|
||||
Provider: account.Provider(),
|
||||
ProviderAccount: account.Account(),
|
||||
MinimumAgeSeconds: minimumAge.Seconds(),
|
||||
Now: pgTime(at),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - authorize retry: %w", location, mapDeliveryError(err))
|
||||
}
|
||||
if updated == 0 {
|
||||
return fmt.Errorf("%s - current delivery state is not eligible: %w", location, outbound.ErrDeliveryRetryNotAllowed)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error) {
|
||||
@@ -265,6 +353,33 @@ func (repository deliveryRepository) Cancel(ctx context.Context, next domain.Del
|
||||
return repository.updateState(ctx, "deliveryRepository.Cancel", next, true)
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) StopUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error {
|
||||
const location = "deliveryRepository.StopUnknownRetry"
|
||||
if next.IsZero() || next.Status() != domain.DeliveryStatusUnknown || !next.NextAttemptAt().IsZero() || owner == uuid.Nil || next.Version() <= 1 {
|
||||
return fmt.Errorf("%s - state was not built by domain.Delivery.StopAutomaticRetry: %w", location, domain.ErrInvalidDelivery)
|
||||
}
|
||||
updated, err := repository.queries.StopUnknownDeliveryRetry(ctx, sqlc.StopUnknownDeliveryRetryParams{
|
||||
Now: pgTime(next.UpdatedAt()),
|
||||
ID: pgUUID(next.ID()),
|
||||
LeaseOwner: pgUUID(owner),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - stop retry: %w", location, mapDeliveryError(err))
|
||||
}
|
||||
if updated == 0 {
|
||||
return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) ScheduleUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error {
|
||||
const location = "deliveryRepository.ScheduleUnknownRetry"
|
||||
if owner == uuid.Nil || next.IsZero() || next.Status() != domain.DeliveryStatusUnknown || next.NextAttemptAt().IsZero() || next.Version() <= 1 {
|
||||
return fmt.Errorf("%s - state was not built by domain.Delivery.ScheduleUnknownRetry: %w", location, domain.ErrInvalidDelivery)
|
||||
}
|
||||
return repository.updateState(ctx, location, next, true)
|
||||
}
|
||||
|
||||
// updateState stores a state change without an attempt over the version
|
||||
// before it. releaseClaim ends the sending worker's lease with the change.
|
||||
func (repository deliveryRepository) updateState(ctx context.Context, location string, next domain.Delivery, releaseClaim bool) error {
|
||||
@@ -363,9 +478,13 @@ func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outboun
|
||||
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - decode claimed delivery: %w", location, unreadable)
|
||||
}
|
||||
claimed := outbound.ClaimedDelivery{
|
||||
Delivery: delivery,
|
||||
PreviousClaimedUntil: zeroableTime(row.PreviousClaimedUntil),
|
||||
FailureCount: row.FailureCount,
|
||||
Delivery: delivery,
|
||||
PreviousClaimedUntil: zeroableTime(row.PreviousClaimedUntil),
|
||||
ManualRetryPending: row.ManualRetryPending.Bool,
|
||||
ManualRetryCycleStarted: row.ManualRetryCycleStarted,
|
||||
SendStartUnsettled: row.SendStartUnsettled,
|
||||
HasUncertainAttempt: row.HasUncertainAttempt,
|
||||
FailureCount: row.FailureCount,
|
||||
}
|
||||
if row.SinceFirstSendSeconds >= 0 {
|
||||
claimed.FirstSendStarted = true
|
||||
@@ -385,11 +504,17 @@ func (repository deliveryRepository) LockClaimed(ctx context.Context, id, owner
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) MarkSendStarted(ctx context.Context, id, owner uuid.UUID) error {
|
||||
if _, err := repository.queries.MarkDeliverySendStarted(ctx, sqlc.MarkDeliverySendStartedParams{ID: pgUUID(id), LeaseOwner: pgUUID(owner)}); err != nil {
|
||||
return fmt.Errorf("deliveryRepository.MarkSendStarted - mark send started: %w", mapDeliveryError(err))
|
||||
func (repository deliveryRepository) MarkSendStarted(ctx context.Context, id, owner uuid.UUID, requireDedupWindow bool, safeWindow time.Duration) (bool, error) {
|
||||
started, err := repository.queries.MarkDeliverySendStarted(ctx, sqlc.MarkDeliverySendStartedParams{
|
||||
ID: pgUUID(id),
|
||||
LeaseOwner: pgUUID(owner),
|
||||
RequireDedupWindow: requireDedupWindow,
|
||||
RetryWindowSeconds: safeWindow.Seconds(),
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("deliveryRepository.MarkSendStarted - mark send started: %w", mapDeliveryError(err))
|
||||
}
|
||||
return nil
|
||||
return started == 1, nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) RecordFailure(ctx context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) {
|
||||
|
||||
@@ -28,9 +28,8 @@ const (
|
||||
// consent records.
|
||||
consentSubjectForeignKey = "consent_records_subject_id_fkey"
|
||||
|
||||
// sessionTouchInterval is the minimum age of last_seen_at before Touch
|
||||
// writes it again. It bounds session writes to one per minute per session
|
||||
// at the cost of ending an idle session up to a minute early.
|
||||
// sessionTouchInterval coalesces session activity writes for frequent
|
||||
// requests. Touch also caps it at half the configured idle timeout.
|
||||
sessionTouchInterval = time.Minute
|
||||
)
|
||||
|
||||
@@ -614,11 +613,12 @@ func (repository sessionRepository) Touch(ctx context.Context, id uuid.UUID, at
|
||||
if err := validateSessionCheck("sessionRepository.Touch", at, idleTimeout); err != nil {
|
||||
return err
|
||||
}
|
||||
touchInterval := min(sessionTouchInterval, idleTimeout/2)
|
||||
result, err := repository.queries.TouchSession(ctx, sqlc.TouchSessionParams{
|
||||
ID: pgUUID(id),
|
||||
At: pgTime(at),
|
||||
IdleCutoff: pgTime(at.Add(-idleTimeout)),
|
||||
TouchCutoff: pgTime(at.Add(-sessionTouchInterval)),
|
||||
TouchCutoff: pgTime(at.Add(-touchInterval)),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("sessionRepository.Touch - update session: %w", mapIdentityError(err))
|
||||
|
||||
@@ -11,6 +11,148 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const authorizeUnknownDeliveryRetry = `-- name: AuthorizeUnknownDeliveryRetry :execrows
|
||||
WITH eligible AS MATERIALIZED (
|
||||
SELECT
|
||||
due.id,
|
||||
(due.claim_owner IS NOT NULL) AS previous_lease_expired,
|
||||
(
|
||||
due.manual_retry_started_at IS NOT NULL
|
||||
AND due.send_started_attempt_count = due.attempt_count
|
||||
) AS unsettled_manual_send,
|
||||
greatest(
|
||||
clock_timestamp(),
|
||||
due.updated_at,
|
||||
coalesce(due.last_attempt_at, due.updated_at)
|
||||
) AS lost_attempt_at
|
||||
FROM deliveries AS due
|
||||
WHERE
|
||||
due.id = $3
|
||||
AND due.status = 'unknown'
|
||||
AND due.next_attempt_at IS NULL
|
||||
AND (
|
||||
due.claim_owner IS NULL
|
||||
OR due.claimed_until <= clock_timestamp()
|
||||
)
|
||||
AND due.attempt_count > 0
|
||||
AND due.provider = $4
|
||||
AND due.provider_account = $5
|
||||
AND due.first_send_started_at IS NOT NULL
|
||||
AND clock_timestamp() - due.first_send_started_at
|
||||
>= make_interval(secs => $6::float8)
|
||||
AND $2::boolean
|
||||
AND $1::text ~ '^operator:[a-z0-9][a-z0-9._-]*$'
|
||||
FOR UPDATE
|
||||
), authorized AS (
|
||||
UPDATE deliveries AS due
|
||||
SET
|
||||
attempt_count = due.attempt_count + CASE WHEN eligible.unsettled_manual_send THEN 1 ELSE 0 END,
|
||||
last_attempt_at = CASE
|
||||
WHEN eligible.unsettled_manual_send THEN eligible.lost_attempt_at
|
||||
ELSE due.last_attempt_at
|
||||
END,
|
||||
next_attempt_at = greatest(
|
||||
$7::timestamptz,
|
||||
due.updated_at,
|
||||
coalesce(eligible.lost_attempt_at, due.updated_at)
|
||||
),
|
||||
manual_retry_authorized_at = clock_timestamp(),
|
||||
manual_retry_started_at = NULL,
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL,
|
||||
version = due.version + 1,
|
||||
updated_at = greatest(
|
||||
due.updated_at,
|
||||
$7::timestamptz,
|
||||
coalesce(eligible.lost_attempt_at, due.updated_at)
|
||||
)
|
||||
FROM eligible
|
||||
WHERE due.id = eligible.id
|
||||
RETURNING
|
||||
due.id,
|
||||
due.attempt_count,
|
||||
eligible.previous_lease_expired,
|
||||
eligible.unsettled_manual_send,
|
||||
eligible.lost_attempt_at
|
||||
), recorded_lost_attempt AS (
|
||||
-- A manual send whose lease expired after Mark but before settlement has
|
||||
-- no provider answer. Preserve it as an unknown attempt before this new
|
||||
-- explicit decision schedules another possible send.
|
||||
INSERT INTO delivery_attempts (
|
||||
delivery_id,
|
||||
attempt_number,
|
||||
attempted_at,
|
||||
outcome,
|
||||
rejection,
|
||||
provider_code,
|
||||
provider_message_id,
|
||||
retry_after_ns,
|
||||
status_after,
|
||||
next_attempt_at
|
||||
)
|
||||
SELECT
|
||||
authorized.id,
|
||||
authorized.attempt_count,
|
||||
authorized.lost_attempt_at,
|
||||
'unknown',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
'unknown',
|
||||
NULL
|
||||
FROM authorized
|
||||
WHERE authorized.unsettled_manual_send
|
||||
RETURNING delivery_id
|
||||
)
|
||||
INSERT INTO delivery_retry_decisions (
|
||||
delivery_id,
|
||||
attempt_count,
|
||||
actor,
|
||||
duplicate_risk_acknowledged,
|
||||
previous_lease_expired,
|
||||
decided_at
|
||||
)
|
||||
SELECT
|
||||
authorized.id,
|
||||
authorized.attempt_count,
|
||||
$1,
|
||||
$2,
|
||||
authorized.previous_lease_expired,
|
||||
clock_timestamp()
|
||||
FROM authorized
|
||||
`
|
||||
|
||||
type AuthorizeUnknownDeliveryRetryParams struct {
|
||||
Actor string
|
||||
DuplicateRiskAcknowledged bool
|
||||
DeliveryID pgtype.UUID
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
MinimumAgeSeconds float64
|
||||
Now pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Authorizes one retry of a terminal unknown delivery. The update and append-
|
||||
// only decision share one statement and lock the current row, so a second or
|
||||
// concurrent operator decision cannot schedule another send for the same
|
||||
// unknown attempt. The provider account must still match the delivery's pin.
|
||||
func (q *Queries) AuthorizeUnknownDeliveryRetry(ctx context.Context, arg AuthorizeUnknownDeliveryRetryParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, authorizeUnknownDeliveryRetry,
|
||||
arg.Actor,
|
||||
arg.DuplicateRiskAcknowledged,
|
||||
arg.DeliveryID,
|
||||
arg.Provider,
|
||||
arg.ProviderAccount,
|
||||
arg.MinimumAgeSeconds,
|
||||
arg.Now,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const cancelUnreadableDelivery = `-- name: CancelUnreadableDelivery :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
@@ -64,12 +206,25 @@ WITH candidate AS (
|
||||
coalesce(
|
||||
extract(EPOCH FROM clock_timestamp() - due.first_send_started_at),
|
||||
-1
|
||||
)::float8 AS since_first_send_seconds
|
||||
)::float8 AS since_first_send_seconds,
|
||||
(due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL)
|
||||
AS manual_retry_pending,
|
||||
(due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started,
|
||||
(
|
||||
due.send_started_attempt_count IS NOT NULL
|
||||
AND due.send_started_attempt_count = due.attempt_count
|
||||
)::boolean AS send_start_unsettled,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM delivery_attempts AS prior_attempt
|
||||
WHERE prior_attempt.delivery_id = due.id
|
||||
AND prior_attempt.outcome = 'unknown'
|
||||
)::boolean AS has_uncertain_attempt
|
||||
FROM deliveries AS due
|
||||
WHERE
|
||||
due.kind IN ('verification', 'password_reset')
|
||||
AND due.kind = any($3::text [])
|
||||
AND due.status IN ('pending', 'waiting_quota')
|
||||
AND due.status IN ('pending', 'waiting_quota', 'unknown')
|
||||
AND due.next_attempt_at IS NOT NULL
|
||||
AND due.next_attempt_at <= $4::timestamptz
|
||||
AND (
|
||||
@@ -125,7 +280,11 @@ RETURNING
|
||||
claimed.created_at,
|
||||
claimed.updated_at,
|
||||
candidate.previous_claimed_until,
|
||||
candidate.since_first_send_seconds
|
||||
candidate.since_first_send_seconds,
|
||||
candidate.manual_retry_pending,
|
||||
candidate.manual_retry_cycle_started,
|
||||
candidate.send_start_unsettled,
|
||||
candidate.has_uncertain_attempt
|
||||
`
|
||||
|
||||
type ClaimDueDeliveryParams struct {
|
||||
@@ -139,37 +298,41 @@ type ClaimDueDeliveryParams struct {
|
||||
}
|
||||
|
||||
type ClaimDueDeliveryRow struct {
|
||||
ID pgtype.UUID
|
||||
SourceEventID pgtype.UUID
|
||||
RecipientUserID pgtype.UUID
|
||||
RecipientEmail string
|
||||
Kind string
|
||||
TemplateVersion string
|
||||
Subject string
|
||||
TextBody string
|
||||
HtmlBody string
|
||||
ContentSha256 []byte
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
IdempotencyKey string
|
||||
Status string
|
||||
AttemptCount int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
LastAttemptAt pgtype.Timestamptz
|
||||
ProviderMessageID pgtype.Text
|
||||
EmailTokenID pgtype.UUID
|
||||
CancelReason pgtype.Text
|
||||
BodyRedactedAt pgtype.Timestamptz
|
||||
FailureCount int32
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
PreviousClaimedUntil pgtype.Timestamptz
|
||||
SinceFirstSendSeconds float64
|
||||
ID pgtype.UUID
|
||||
SourceEventID pgtype.UUID
|
||||
RecipientUserID pgtype.UUID
|
||||
RecipientEmail string
|
||||
Kind string
|
||||
TemplateVersion string
|
||||
Subject string
|
||||
TextBody string
|
||||
HtmlBody string
|
||||
ContentSha256 []byte
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
IdempotencyKey string
|
||||
Status string
|
||||
AttemptCount int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
LastAttemptAt pgtype.Timestamptz
|
||||
ProviderMessageID pgtype.Text
|
||||
EmailTokenID pgtype.UUID
|
||||
CancelReason pgtype.Text
|
||||
BodyRedactedAt pgtype.Timestamptz
|
||||
FailureCount int32
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
PreviousClaimedUntil pgtype.Timestamptz
|
||||
SinceFirstSendSeconds float64
|
||||
ManualRetryPending pgtype.Bool
|
||||
ManualRetryCycleStarted bool
|
||||
SendStartUnsettled bool
|
||||
HasUncertainAttempt bool
|
||||
}
|
||||
|
||||
// Claims the most overdue delivery that the sending worker may send, in one
|
||||
// statement: a pending or waiting_quota delivery of the service mail kinds
|
||||
// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
|
||||
// (the literals match the predicate of deliveries_due_idx, so an idle poll
|
||||
// reads only that small index) whose next_attempt_at has passed, pinned to the
|
||||
// configured provider account (or to rebind_provider before its first
|
||||
@@ -183,10 +346,15 @@ type ClaimDueDeliveryRow struct {
|
||||
// stay on the application clock that wrote them. Neither the version nor
|
||||
// updated_at changes: a claim is not a change of the delivery.
|
||||
// previous_claimed_until is the deadline of an abandoned lease, NULL for a
|
||||
// delivery nobody held; since_first_send_seconds is how long ago, by the
|
||||
// database clock, its first request started, -1 when none did. now is the
|
||||
// application clock. Deliveries that are unknown or wait for an unknown quota
|
||||
// reset have no due time here and wait for an operator.
|
||||
// delivery nobody held; since_first_send_seconds always measures from the
|
||||
// original first request by the database clock, and is -1 when none started.
|
||||
// manual_retry_pending is true until the first provider call of the latest
|
||||
// manual authorization starts. send_start_unsettled means a provider call
|
||||
// started at the current attempt_count but no result was recorded afterward.
|
||||
// has_uncertain_attempt keeps an earlier unknown result visible even if a
|
||||
// later confirmed refusal moved the current delivery back to pending.
|
||||
// now is the application clock. Unknown deliveries without a scheduled retry
|
||||
// and quota waits with an unknown reset wait for an operator.
|
||||
func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error) {
|
||||
row := q.db.QueryRow(ctx, claimDueDelivery,
|
||||
arg.LeaseOwner,
|
||||
@@ -226,6 +394,10 @@ func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryPara
|
||||
&i.UpdatedAt,
|
||||
&i.PreviousClaimedUntil,
|
||||
&i.SinceFirstSendSeconds,
|
||||
&i.ManualRetryPending,
|
||||
&i.ManualRetryCycleStarted,
|
||||
&i.SendStartUnsettled,
|
||||
&i.HasUncertainAttempt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -277,9 +449,40 @@ FROM deliveries
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error) {
|
||||
type GetDeliveryByIDRow struct {
|
||||
ID pgtype.UUID
|
||||
SourceEventID pgtype.UUID
|
||||
RecipientUserID pgtype.UUID
|
||||
RecipientEmail string
|
||||
Kind string
|
||||
TemplateVersion string
|
||||
Subject string
|
||||
TextBody string
|
||||
HtmlBody string
|
||||
ContentSha256 []byte
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
IdempotencyKey string
|
||||
Status string
|
||||
AttemptCount int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
LastAttemptAt pgtype.Timestamptz
|
||||
ProviderMessageID pgtype.Text
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
EmailTokenID pgtype.UUID
|
||||
CancelReason pgtype.Text
|
||||
ClaimOwner pgtype.UUID
|
||||
ClaimedUntil pgtype.Timestamptz
|
||||
FirstSendStartedAt pgtype.Timestamptz
|
||||
FailureCount int32
|
||||
BodyRedactedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error) {
|
||||
row := q.db.QueryRow(ctx, getDeliveryByID, id)
|
||||
var i Delivery
|
||||
var i GetDeliveryByIDRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SourceEventID,
|
||||
@@ -313,6 +516,49 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getDeliveryRetrySnapshot = `-- name: GetDeliveryRetrySnapshot :one
|
||||
SELECT
|
||||
id,
|
||||
provider,
|
||||
provider_account,
|
||||
status,
|
||||
attempt_count,
|
||||
next_attempt_at,
|
||||
first_send_started_at,
|
||||
manual_retry_started_at
|
||||
FROM deliveries
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
type GetDeliveryRetrySnapshotRow struct {
|
||||
ID pgtype.UUID
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
Status string
|
||||
AttemptCount int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
FirstSendStartedAt pgtype.Timestamptz
|
||||
ManualRetryStartedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Reads only the metadata needed by the local operator retry interface. It
|
||||
// intentionally does not select the address, token, subject, or message body.
|
||||
func (q *Queries) GetDeliveryRetrySnapshot(ctx context.Context, id pgtype.UUID) (GetDeliveryRetrySnapshotRow, error) {
|
||||
row := q.db.QueryRow(ctx, getDeliveryRetrySnapshot, id)
|
||||
var i GetDeliveryRetrySnapshotRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Provider,
|
||||
&i.ProviderAccount,
|
||||
&i.Status,
|
||||
&i.AttemptCount,
|
||||
&i.NextAttemptAt,
|
||||
&i.FirstSendStartedAt,
|
||||
&i.ManualRetryStartedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getDeliveryStatistics = `-- name: GetDeliveryStatistics :many
|
||||
SELECT
|
||||
kind,
|
||||
@@ -729,24 +975,53 @@ const markDeliverySendStarted = `-- name: MarkDeliverySendStarted :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()),
|
||||
send_started_attempt_count = deliveries.attempt_count,
|
||||
next_attempt_at = CASE
|
||||
WHEN deliveries.manual_retry_authorized_at IS NOT NULL
|
||||
AND deliveries.manual_retry_started_at IS NULL
|
||||
THEN NULL
|
||||
ELSE deliveries.next_attempt_at
|
||||
END,
|
||||
manual_retry_started_at = CASE
|
||||
WHEN deliveries.manual_retry_authorized_at IS NOT NULL
|
||||
AND deliveries.manual_retry_started_at IS NULL
|
||||
THEN clock_timestamp()
|
||||
ELSE deliveries.manual_retry_started_at
|
||||
END,
|
||||
failure_count = 0
|
||||
WHERE
|
||||
id = $1
|
||||
AND claim_owner = $2
|
||||
AND (
|
||||
NOT $3::boolean
|
||||
OR (deliveries.manual_retry_authorized_at IS NOT NULL AND deliveries.manual_retry_started_at IS NULL)
|
||||
OR coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) IS NULL
|
||||
OR clock_timestamp() - coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at)
|
||||
< make_interval(secs => $4::float8)
|
||||
)
|
||||
`
|
||||
|
||||
type MarkDeliverySendStartedParams struct {
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
RequireDedupWindow bool
|
||||
RetryWindowSeconds float64
|
||||
}
|
||||
|
||||
// Notes that the first request of a claimed delivery is about to start, by the
|
||||
// database clock, and clears the count of worker failures: the claim and the
|
||||
// preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted
|
||||
// from this moment, so a later claim can tell whether repeating the request is
|
||||
// still safe. It never moves.
|
||||
// Notes that a request is about to start, by the database clock, and clears
|
||||
// the count of worker failures. For an operator-authorized send, this sets
|
||||
// its single-use marker without overwriting the original first-send time. The
|
||||
// marker captures the current attempt_count so a lost result can be recovered
|
||||
// as unknown instead of silently retried. When require_dedup_window is true,
|
||||
// the age check is repeated here after quota work and the row lock, immediately
|
||||
// before the network call; manual starts never reset that original window.
|
||||
func (q *Queries) MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, markDeliverySendStarted, arg.ID, arg.LeaseOwner)
|
||||
result, err := q.db.Exec(ctx, markDeliverySendStarted,
|
||||
arg.ID,
|
||||
arg.LeaseOwner,
|
||||
arg.RequireDedupWindow,
|
||||
arg.RetryWindowSeconds,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -1002,6 +1277,39 @@ func (q *Queries) ReleaseDeliveryClaim(ctx context.Context, arg ReleaseDeliveryC
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const stopUnknownDeliveryRetry = `-- name: StopUnknownDeliveryRetry :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
status = 'unknown',
|
||||
next_attempt_at = NULL,
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = greatest(deliveries.updated_at, $1::timestamptz)
|
||||
WHERE
|
||||
id = $2
|
||||
AND status IN ('pending', 'waiting_quota', 'unknown')
|
||||
AND next_attempt_at IS NOT NULL
|
||||
AND claim_owner = $3::uuid
|
||||
`
|
||||
|
||||
type StopUnknownDeliveryRetryParams struct {
|
||||
Now pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
}
|
||||
|
||||
// Stops a due automatic retry of an unknown delivery without recording a
|
||||
// fictitious provider attempt, for example when the 23-hour safety cutoff is
|
||||
// reached after the claim but before the provider call.
|
||||
func (q *Queries) StopUnknownDeliveryRetry(ctx context.Context, arg StopUnknownDeliveryRetryParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, stopUnknownDeliveryRetry, arg.Now, arg.ID, arg.LeaseOwner)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const updateDeliveryState = `-- name: UpdateDeliveryState :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
|
||||
@@ -196,6 +196,12 @@ type Delivery struct {
|
||||
FailureCount int32
|
||||
// Set when the bodies of a token mail were cleared after the delivery reached a terminal status, so a database dump holds no live or dead token.
|
||||
BodyRedactedAt pgtype.Timestamptz
|
||||
// Database time of the latest audited operator authorization to retry a terminal unknown delivery; it does not replace the original send history.
|
||||
ManualRetryAuthorizedAt pgtype.Timestamptz
|
||||
// Database time when the first provider call of the latest manual authorization started; this is a single-use/recovery marker and never resets the provider deduplication window.
|
||||
ManualRetryStartedAt pgtype.Timestamptz
|
||||
// Attempt count when the latest provider call started. Equality with attempt_count means its result was not recorded; a greater attempt_count means a provider result was stored after that send-start.
|
||||
SendStartedAttemptCount pgtype.Int4
|
||||
}
|
||||
|
||||
type DeliveryAttempt struct {
|
||||
@@ -211,6 +217,21 @@ type DeliveryAttempt struct {
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Append-only record of an operator decision to retry a terminal unknown mail delivery after its provider deduplication window. No foreign key so history survives account deletion.
|
||||
type DeliveryRetryDecision struct {
|
||||
DecisionID int64
|
||||
// Opaque ID of the delivery whose current unknown attempt was authorized for another send cycle.
|
||||
DeliveryID pgtype.UUID
|
||||
AttemptCount int32
|
||||
// Operator handle in the form operator:<handle>; never an email address or credential.
|
||||
Actor string
|
||||
// Must be true: after the provider key expires, reusing it does not guarantee deduplication.
|
||||
DuplicateRiskAcknowledged bool
|
||||
// True when this decision also cleared an expired worker lease after a manual send began but its result was not recorded.
|
||||
PreviousLeaseExpired bool
|
||||
DecidedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type EmailToken struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
|
||||
@@ -28,6 +28,11 @@ type Querier interface {
|
||||
// ends every earlier token, and deletes the registration C1 of the earlier
|
||||
// registrant like UpdateUserRegistration does.
|
||||
AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error)
|
||||
// Authorizes one retry of a terminal unknown delivery. The update and append-
|
||||
// only decision share one statement and lock the current row, so a second or
|
||||
// concurrent operator decision cannot schedule another send for the same
|
||||
// unknown attempt. The provider account must still match the delivery's pin.
|
||||
AuthorizeUnknownDeliveryRetry(ctx context.Context, arg AuthorizeUnknownDeliveryRetryParams) (int64, error)
|
||||
// Cancels a job that has not finished. A job whose handler transaction is
|
||||
// in progress holds its row lock, so the statement waits for it: after the
|
||||
// handler committed the job is done and nothing is canceled; otherwise the
|
||||
@@ -40,7 +45,7 @@ type Querier interface {
|
||||
// application clock.
|
||||
CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error)
|
||||
// Claims the most overdue delivery that the sending worker may send, in one
|
||||
// statement: a pending or waiting_quota delivery of the service mail kinds
|
||||
// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
|
||||
// (the literals match the predicate of deliveries_due_idx, so an idle poll
|
||||
// reads only that small index) whose next_attempt_at has passed, pinned to the
|
||||
// configured provider account (or to rebind_provider before its first
|
||||
@@ -54,10 +59,15 @@ type Querier interface {
|
||||
// stay on the application clock that wrote them. Neither the version nor
|
||||
// updated_at changes: a claim is not a change of the delivery.
|
||||
// previous_claimed_until is the deadline of an abandoned lease, NULL for a
|
||||
// delivery nobody held; since_first_send_seconds is how long ago, by the
|
||||
// database clock, its first request started, -1 when none did. now is the
|
||||
// application clock. Deliveries that are unknown or wait for an unknown quota
|
||||
// reset have no due time here and wait for an operator.
|
||||
// delivery nobody held; since_first_send_seconds always measures from the
|
||||
// original first request by the database clock, and is -1 when none started.
|
||||
// manual_retry_pending is true until the first provider call of the latest
|
||||
// manual authorization starts. send_start_unsettled means a provider call
|
||||
// started at the current attempt_count but no result was recorded afterward.
|
||||
// has_uncertain_attempt keeps an earlier unknown result visible even if a
|
||||
// later confirmed refusal moved the current delivery back to pending.
|
||||
// now is the application clock. Unknown deliveries without a scheduled retry
|
||||
// and quota waits with an unknown reset wait for an operator.
|
||||
ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error)
|
||||
// Claims up to batch_limit jobs of the listed kinds in one statement: jobs
|
||||
// whose available_at has passed, and running jobs whose lease expired
|
||||
@@ -163,7 +173,10 @@ type Querier interface {
|
||||
// The database clock, which stamps the effective time of a policy version, so
|
||||
// "the version in force now" is judged against the same clock.
|
||||
GetDatabaseTime(ctx context.Context) (pgtype.Timestamptz, error)
|
||||
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
|
||||
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error)
|
||||
// Reads only the metadata needed by the local operator retry interface. It
|
||||
// intentionally does not select the address, token, subject, or message body.
|
||||
GetDeliveryRetrySnapshot(ctx context.Context, id pgtype.UUID) (GetDeliveryRetrySnapshotRow, error)
|
||||
// Aggregates the deliveries by kind and status for the metrics, at most once
|
||||
// per metrics interval. It reads only kind, status, and next_attempt_at,
|
||||
// never an address, a body, or an ID. No index covers status, so it scans
|
||||
@@ -406,11 +419,13 @@ type Querier interface {
|
||||
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
|
||||
// Locks the active registration C1 while its pending registration is applied.
|
||||
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
|
||||
// Notes that the first request of a claimed delivery is about to start, by the
|
||||
// database clock, and clears the count of worker failures: the claim and the
|
||||
// preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted
|
||||
// from this moment, so a later claim can tell whether repeating the request is
|
||||
// still safe. It never moves.
|
||||
// Notes that a request is about to start, by the database clock, and clears
|
||||
// the count of worker failures. For an operator-authorized send, this sets
|
||||
// its single-use marker without overwriting the original first-send time. The
|
||||
// marker captures the current attempt_count so a lost result can be recovered
|
||||
// as unknown instead of silently retried. When require_dedup_window is true,
|
||||
// the age check is repeated here after quota work and the row lock, immediately
|
||||
// before the network call; manual starts never reset that original window.
|
||||
MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error)
|
||||
// Records that the provider refused a send because the quota of a window is
|
||||
// used up: the usage rises to at least the configured limit, so the local
|
||||
@@ -553,6 +568,10 @@ type Querier interface {
|
||||
// never started on a lease that another worker may take over. now is the
|
||||
// application clock.
|
||||
StartScheduledJob(ctx context.Context, arg StartScheduledJobParams) (int64, error)
|
||||
// Stops a due automatic retry of an unknown delivery without recording a
|
||||
// fictitious provider attempt, for example when the 23-hour safety cutoff is
|
||||
// reached after the claim but before the provider call.
|
||||
StopUnknownDeliveryRetry(ctx context.Context, arg StopUnknownDeliveryRetryParams) (int64, error)
|
||||
// Records activity on an active session and reports whether it is active.
|
||||
// The row is written only when last_seen_at is older than touch_cutoff, so
|
||||
// frequent requests do not rewrite it. last_seen_at never moves back, and a
|
||||
|
||||
@@ -35,10 +35,10 @@ func newAPIHandler(health *v1.HealthHandler, problems *problem.Responder, identi
|
||||
return v1.NewHandler(health, problems, v1.WithIdentity(identityHandler))
|
||||
}
|
||||
|
||||
// newIdentityHandler builds the registration operations and the PostgreSQL
|
||||
// pool they own. Nothing connects here, so an unavailable database never
|
||||
// blocks startup. It returns no handler when DATABASE_URL is unset, and the
|
||||
// operations then answer 501. The application clock is time.Now.
|
||||
// newIdentityHandler builds the registration and session operations and the
|
||||
// PostgreSQL pool they own. Nothing connects here, so an unavailable database
|
||||
// never blocks startup. It returns no handler when DATABASE_URL is unset, and
|
||||
// the operations then answer 501. The application clock is time.Now.
|
||||
func newIdentityHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
@@ -47,7 +47,7 @@ func newIdentityHandler(
|
||||
metrics *prometheus.Metrics,
|
||||
) (*v1.IdentityHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("registration is not served because DATABASE_URL is not set")
|
||||
logger.Warn("identity operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
keyring, err := newIdentityKeyring(settings, logger)
|
||||
@@ -110,16 +110,40 @@ func newIdentityHandler(
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create confirmation: %w", err)
|
||||
}
|
||||
sessions, err := identity.NewSessionService(identity.SessionDependencies{
|
||||
Transactor: transactor,
|
||||
Users: store.Users(),
|
||||
Sessions: store.Sessions(),
|
||||
Credentials: credentials,
|
||||
Limiter: cache,
|
||||
Keyring: keyring,
|
||||
Clock: time.Now,
|
||||
Metrics: metrics,
|
||||
Logger: logger,
|
||||
}, identity.SessionSettings{
|
||||
ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit),
|
||||
EmailHourlyLimit: int64(settings.IdentityLoginEmailHourlyLimit),
|
||||
IdleTimeout: settings.IdentitySessionIdleTimeout,
|
||||
AbsoluteLifetime: settings.IdentitySessionAbsoluteLifetime,
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create sessions: %w", err)
|
||||
}
|
||||
// The HTTP server stops before this cleanup runs, so no request uses the
|
||||
// pool while it closes.
|
||||
return v1.NewIdentityHandler(registration, v1.WithEmailConfirmation(confirmation, settings.AppPublicURL)), pool.Close, nil
|
||||
return v1.NewIdentityHandler(registration,
|
||||
v1.WithEmailConfirmation(confirmation, settings.AppPublicURL),
|
||||
v1.WithSessionService(sessions, settings.AppPublicURL),
|
||||
), pool.Close, nil
|
||||
}
|
||||
|
||||
// newIdentityKeyring keys the idempotency scopes and rate limit buckets with
|
||||
// IDENTITY_KEY_SECRET. Only with IDENTITY_ALLOW_EPHEMERAL_KEY, which the
|
||||
// configuration check demands for an unset secret, a random one is drawn for
|
||||
// this process: idempotency records and counters written before a restart no
|
||||
// longer match, and instances of one deployment do not agree.
|
||||
// newIdentityKeyring derives purpose keys for idempotency scopes, rate-limit
|
||||
// buckets, and session CSRF tokens from IDENTITY_KEY_SECRET. Only with
|
||||
// IDENTITY_ALLOW_EPHEMERAL_KEY, which the configuration check demands for an
|
||||
// unset secret, a random one is drawn for this process. Idempotency records and
|
||||
// counters no longer match after restart, and CSRF tokens differ between
|
||||
// restarts and instances.
|
||||
func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.Keyring, error) {
|
||||
secret := []byte(settings.IdentityKeySecret)
|
||||
if len(secret) == 0 {
|
||||
@@ -127,7 +151,7 @@ func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.
|
||||
if _, err := rand.Read(secret); err != nil {
|
||||
return nil, fmt.Errorf("bootstrap.newIdentityKeyring - generate secret: %w", err)
|
||||
}
|
||||
logger.Warn("IDENTITY_ALLOW_EPHEMERAL_KEY is set and IDENTITY_KEY_SECRET is not; a random secret is used, so idempotency records and rate limits do not survive a restart")
|
||||
logger.Warn("IDENTITY_ALLOW_EPHEMERAL_KEY is set and IDENTITY_KEY_SECRET is not; a random secret is used, so idempotency records and rate limits do not survive a restart and session CSRF tokens differ between restarts and instances")
|
||||
}
|
||||
keyring, err := identity.NewKeyring(secret)
|
||||
if err != nil {
|
||||
|
||||
@@ -39,7 +39,7 @@ func initialize(
|
||||
wire.Bind(new(inbound.Readiness), new(*health.Readiness)),
|
||||
wire.Bind(new(httpmiddleware.RequestMetrics), new(*metrics.Metrics)),
|
||||
wire.Bind(new(apiadapter.Handler), new(*v1.Handler)),
|
||||
wire.Bind(new(apiadapter.SecurityHandler), new(*v1.DenyAllSecurity)),
|
||||
wire.Bind(new(apiadapter.SecurityHandler), new(*v1.SessionSecurity)),
|
||||
newReadiness,
|
||||
metrics.New,
|
||||
newHealthHandler,
|
||||
@@ -47,7 +47,7 @@ func initialize(
|
||||
newAPIHandler,
|
||||
newTrustedProxies,
|
||||
newIdentityHandler,
|
||||
v1.NewDenyAllSecurity,
|
||||
newSessionSecurity,
|
||||
httpadapter.NewRouter,
|
||||
newOutboxRelay,
|
||||
newEventConsumers,
|
||||
@@ -60,6 +60,10 @@ func initialize(
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
func newSessionSecurity(identityHandler *v1.IdentityHandler) *v1.SessionSecurity {
|
||||
return identityHandler.SessionSecurity()
|
||||
}
|
||||
|
||||
func newHealthHandler(readiness inbound.Readiness, config config.Config) *v1.HealthHandler {
|
||||
return v1.NewHealthHandler(readiness, config.ReadinessTimeout)
|
||||
}
|
||||
|
||||
@@ -54,9 +54,9 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
return nil, nil, err
|
||||
}
|
||||
handler := newAPIHandler(healthHandler, responder, identityHandler)
|
||||
denyAllSecurity := v1.NewDenyAllSecurity()
|
||||
sessionSecurity := newSessionSecurity(identityHandler)
|
||||
v := newTrustedProxies(config2)
|
||||
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, denyAllSecurity, responder, metrics, logger, v)
|
||||
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v)
|
||||
if err != nil {
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
@@ -130,6 +130,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
|
||||
// wire.go:
|
||||
|
||||
func newSessionSecurity(identityHandler *v1.IdentityHandler) *v1.SessionSecurity {
|
||||
return identityHandler.SessionSecurity()
|
||||
}
|
||||
|
||||
func newHealthHandler(readiness inbound.Readiness, config2 config.Config) *v1.HealthHandler {
|
||||
return v1.NewHealthHandler(readiness, config2.ReadinessTimeout)
|
||||
}
|
||||
|
||||
@@ -640,6 +640,47 @@ func (delivery Delivery) Rebind(at time.Time, providerAccount MailProviderAccoun
|
||||
return next, nil
|
||||
}
|
||||
|
||||
// StopAutomaticRetry ends the automatic retry schedule without claiming that
|
||||
// an uncertain delivery was not sent. The delivery remains unknown, with no
|
||||
// due time, so only an audited operator decision can start another send cycle.
|
||||
// It also accepts pending or waiting_quota when a later confirmed refusal
|
||||
// leaves an earlier unknown outcome unresolved after the automatic cutoff.
|
||||
func (delivery Delivery) StopAutomaticRetry(at time.Time) (Delivery, error) {
|
||||
const location = "Delivery.StopAutomaticRetry"
|
||||
if err := delivery.checkChangeTime(location, at); err != nil {
|
||||
return Delivery{}, err
|
||||
}
|
||||
if (delivery.status != DeliveryStatusUnknown && delivery.status != DeliveryStatusPending && delivery.status != DeliveryStatusWaitingQuota) || delivery.nextAttemptAt.IsZero() {
|
||||
return Delivery{}, fmt.Errorf("%s - delivery is %s without a scheduled retry: %w", location, delivery.status, ErrDeliveryTransition)
|
||||
}
|
||||
next := delivery
|
||||
next.status = DeliveryStatusUnknown
|
||||
next.nextAttemptAt = time.Time{}
|
||||
next.version = delivery.version + 1
|
||||
next.updatedAt = at
|
||||
return next, nil
|
||||
}
|
||||
|
||||
// ScheduleUnknownRetry keeps an unknown delivery in the due queue until a
|
||||
// provider quota reset. It does not change the outcome or append an attempt.
|
||||
func (delivery Delivery) ScheduleUnknownRetry(at, nextAttemptAt time.Time) (Delivery, error) {
|
||||
const location = "Delivery.ScheduleUnknownRetry"
|
||||
if err := delivery.checkChangeTime(location, at); err != nil {
|
||||
return Delivery{}, err
|
||||
}
|
||||
if delivery.status != DeliveryStatusUnknown || delivery.nextAttemptAt.IsZero() {
|
||||
return Delivery{}, fmt.Errorf("%s - delivery is %s without an automatic retry: %w", location, delivery.status, ErrDeliveryTransition)
|
||||
}
|
||||
if nextAttemptAt.IsZero() || nextAttemptAt.Before(at) {
|
||||
return Delivery{}, invalidDelivery(location, "next retry time must be set and not precede the decision")
|
||||
}
|
||||
next := delivery
|
||||
next.nextAttemptAt = nextAttemptAt
|
||||
next.version = delivery.version + 1
|
||||
next.updatedAt = at
|
||||
return next, nil
|
||||
}
|
||||
|
||||
// checkChangeTime rejects a zero delivery and a change time before the last
|
||||
// recorded change.
|
||||
func (delivery Delivery) checkChangeTime(location string, at time.Time) error {
|
||||
|
||||
@@ -317,6 +317,49 @@ func TestRecordAttemptRejectsInconsistentResults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStopAutomaticRetryKeepsAnUncertainDeliveryUnknown(t *testing.T) {
|
||||
start := newTestDelivery(t)
|
||||
scheduled := mustRecord(t, start, DeliveryAttemptInput{
|
||||
At: after(1), Outcome: DeliveryOutcomeUnknown, NextAttemptAt: after(2),
|
||||
})
|
||||
stopped, err := scheduled.StopAutomaticRetry(after(3))
|
||||
if err != nil {
|
||||
t.Fatalf("StopAutomaticRetry() error = %v", err)
|
||||
}
|
||||
if stopped.Status() != DeliveryStatusUnknown || !stopped.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("stopped delivery is %s due %s, want unknown without a due time", stopped.Status(), stopped.NextAttemptAt())
|
||||
}
|
||||
if stopped.AttemptCount() != scheduled.AttemptCount() || stopped.Version() != scheduled.Version()+1 {
|
||||
t.Fatalf("stopped delivery has %d attempts and version %d, want %d and %d", stopped.AttemptCount(), stopped.Version(), scheduled.AttemptCount(), scheduled.Version()+1)
|
||||
}
|
||||
if stopped.IdempotencyKey() != scheduled.IdempotencyKey() || stopped.Content().Hash() != scheduled.Content().Hash() {
|
||||
t.Fatal("stopping retries changed the idempotency key or message content")
|
||||
}
|
||||
if _, err := stopped.StopAutomaticRetry(after(4)); !errors.Is(err, ErrDeliveryTransition) {
|
||||
t.Fatalf("StopAutomaticRetry() without a scheduled retry error = %v, want ErrDeliveryTransition", err)
|
||||
}
|
||||
|
||||
quotaWait := mustRecord(t, newTestDelivery(t), DeliveryAttemptInput{
|
||||
At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, NextAttemptAt: after(2),
|
||||
})
|
||||
quotaStopped, err := quotaWait.StopAutomaticRetry(after(3))
|
||||
if err != nil || quotaStopped.Status() != DeliveryStatusUnknown || !quotaStopped.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("StopAutomaticRetry() after a manual-cycle quota refusal = %s due %s, %v; want unknown without a due time",
|
||||
quotaStopped.Status(), quotaStopped.NextAttemptAt(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMailRetryActor(t *testing.T) {
|
||||
if got, err := ParseMailRetryActor("operator:mail-ops"); err != nil || got != "operator:mail-ops" {
|
||||
t.Fatalf("ParseMailRetryActor() = %q, %v", got, err)
|
||||
}
|
||||
for _, value := range []string{"", "operator:Upper", "operator:has space", "person:mail-ops", "operator:" + strings.Repeat("a", 122)} {
|
||||
if _, err := ParseMailRetryActor(value); !errors.Is(err, ErrInvalidDelivery) {
|
||||
t.Fatalf("ParseMailRetryActor(%q) error = %v, want ErrInvalidDelivery", value, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func deliverySnapshot(delivery Delivery) DeliverySnapshot {
|
||||
return DeliverySnapshot{
|
||||
ID: delivery.ID(),
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package domain
|
||||
|
||||
import "regexp"
|
||||
|
||||
var mailRetryActorPattern = regexp.MustCompile(`^operator:[a-z0-9][a-z0-9._-]*$`)
|
||||
|
||||
// MailRetryActor identifies an operator who authorized a retry of an unknown
|
||||
// delivery. It is a handle, not an account ID, email address, or credential.
|
||||
type MailRetryActor string
|
||||
|
||||
// ParseMailRetryActor accepts an operator handle in the form
|
||||
// "operator:<handle>".
|
||||
func ParseMailRetryActor(value string) (MailRetryActor, error) {
|
||||
if len(value) > 128 || !mailRetryActorPattern.MatchString(value) {
|
||||
return "", invalidDelivery("domain.ParseMailRetryActor", "actor must be operator:<handle> of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'")
|
||||
}
|
||||
return MailRetryActor(value), nil
|
||||
}
|
||||
@@ -19,6 +19,11 @@ var (
|
||||
// exists. Nothing was written; read the delivery again.
|
||||
ErrDeliveryVersionConflict = errors.New("delivery changed concurrently")
|
||||
|
||||
// ErrDeliveryRetryNotAllowed reports that an operator retry did not match
|
||||
// the current terminal unknown delivery, its provider account, the
|
||||
// deduplication cutoff, or the required duplicate-risk acknowledgement.
|
||||
ErrDeliveryRetryNotAllowed = errors.New("unknown delivery retry is not allowed in its current state")
|
||||
|
||||
// ErrDeliveryContentImmutable reports a statement that tried to change
|
||||
// the recipient, content, provider account, or idempotency key of a
|
||||
// stored delivery, or a recorded attempt. The database refuses it; it
|
||||
@@ -67,6 +72,11 @@ type DeliveryRepository interface {
|
||||
// no longer matches its hash.
|
||||
Get(ctx context.Context, id uuid.UUID) (domain.Delivery, error)
|
||||
|
||||
// GetRetrySnapshot returns operational state for one delivery without its
|
||||
// recipient address or message content. It is used by the bounded local
|
||||
// operator retry interface and logs.
|
||||
GetRetrySnapshot(ctx context.Context, id uuid.UUID) (DeliveryRetrySnapshot, error)
|
||||
|
||||
// ListAttempts returns the recorded attempts in attempt order; an empty
|
||||
// list for a delivery without attempts or an unknown ID.
|
||||
ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error)
|
||||
@@ -100,6 +110,22 @@ type DeliveryRepository interface {
|
||||
// the sending worker's lease.
|
||||
Cancel(ctx context.Context, next domain.Delivery) error
|
||||
|
||||
// AuthorizeUnknownRetry atomically schedules one operator-approved retry
|
||||
// and appends its immutable audit record. It succeeds only for an unknown
|
||||
// delivery with no automatic retry or live lease, after the safe provider
|
||||
// window, pinned to account, with an operator actor and explicit risk ack.
|
||||
// It returns ErrDeliveryRetryNotAllowed when that state no longer matches.
|
||||
AuthorizeUnknownRetry(ctx context.Context, id uuid.UUID, account domain.MailProviderAccount, actor domain.MailRetryActor, acknowledgeDuplicateRisk bool, at time.Time, safeWindow time.Duration) error
|
||||
|
||||
// StopUnknownRetry stores next as returned by domain.Delivery.StopAutomaticRetry
|
||||
// and releases owner lease without appending a provider attempt.
|
||||
StopUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error
|
||||
|
||||
// ScheduleUnknownRetry stores next as returned by
|
||||
// domain.Delivery.ScheduleUnknownRetry and releases owner lease without an
|
||||
// attempt, for a quota wait that applies to an uncertain retry.
|
||||
ScheduleUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error
|
||||
|
||||
// ClaimDue gives the claim's owner a lease on the most overdue delivery
|
||||
// it may send and returns it, or returns ErrNoDeliveryDue. A claimed row
|
||||
// that cannot be restored is reported as an *UnreadableDeliveryError;
|
||||
@@ -122,9 +148,12 @@ type DeliveryRepository interface {
|
||||
// lock before the quota rows, as the claim does.
|
||||
LockClaimed(ctx context.Context, id, owner uuid.UUID) (bool, error)
|
||||
|
||||
// MarkSendStarted records, by the database clock and only the first time,
|
||||
// that the first request of the claimed delivery is about to start.
|
||||
MarkSendStarted(ctx context.Context, id, owner uuid.UUID) error
|
||||
// MarkSendStarted records, by the database clock, that the request is about
|
||||
// to start. When requireDedupWindow is true it returns false if the provider
|
||||
// safety window expired after claim; this check is the last storage action
|
||||
// before the network call. An authorized manual cycle records a separate
|
||||
// first-start timestamp without replacing the original history.
|
||||
MarkSendStarted(ctx context.Context, id, owner uuid.UUID, requireDedupWindow bool, safeWindow time.Duration) (started bool, err error)
|
||||
|
||||
// RecordFailure counts a failure of the sending worker on the delivery
|
||||
// (not a provider answer), ends its lease, and makes it due again at
|
||||
@@ -151,6 +180,19 @@ type DeliveryRepository interface {
|
||||
ServiceMailState(ctx context.Context, id uuid.UUID) (domain.ServiceMailState, error)
|
||||
}
|
||||
|
||||
// DeliveryRetrySnapshot contains only the metadata needed to inspect an
|
||||
// unknown delivery before an operator decision.
|
||||
type DeliveryRetrySnapshot struct {
|
||||
ID uuid.UUID
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
Status domain.DeliveryStatus
|
||||
AttemptCount int32
|
||||
NextAttemptAt time.Time
|
||||
FirstSendStartedAt time.Time
|
||||
ManualRetryStartedAt time.Time
|
||||
}
|
||||
|
||||
// DeliveryClaim selects and leases the next delivery for a sending worker.
|
||||
type DeliveryClaim struct {
|
||||
// Owner identifies the worker; a lease belongs to it.
|
||||
@@ -180,11 +222,23 @@ type ClaimedDelivery struct {
|
||||
// and let expire without finishing, so an attempt may be in doubt; zero
|
||||
// when no worker held the delivery before.
|
||||
PreviousClaimedUntil time.Time
|
||||
// SinceFirstSend is how long ago, by the database clock, the first
|
||||
// request of the delivery started; meaningful only when FirstSendStarted.
|
||||
// The provider keeps the idempotency key for a window counted from then.
|
||||
// SinceFirstSend is how long ago, by the database clock, the original
|
||||
// first provider request started. A manual decision never resets this
|
||||
// provider idempotency age. Meaningful only when FirstSendStarted.
|
||||
SinceFirstSend time.Duration
|
||||
FirstSendStarted bool
|
||||
// ManualRetryPending is true after operator authorization and until the
|
||||
// first provider call of that manual cycle starts.
|
||||
ManualRetryPending bool
|
||||
// ManualRetryCycleStarted is true after that first manual provider call
|
||||
// starts. It is a single-use and recovery marker, not a new provider window.
|
||||
ManualRetryCycleStarted bool
|
||||
// SendStartUnsettled is true when the latest provider call started with the
|
||||
// current attempt_count and no result was recorded afterward.
|
||||
SendStartUnsettled bool
|
||||
// HasUncertainAttempt is true when this delivery has any recorded unknown
|
||||
// provider result, even if a later confirmed refusal moved it to pending.
|
||||
HasUncertainAttempt bool
|
||||
// FailureCount is the number of consecutive failures of the worker on
|
||||
// this delivery so far.
|
||||
FailureCount int32
|
||||
|
||||
@@ -3,12 +3,16 @@ package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
//nolint:gosec // G101: this fixed value is only used for dummy Argon2 work and never authenticates an account.
|
||||
const dummyLoginPassword = "lincodex-login-dummy-password"
|
||||
|
||||
// Credentials applies the password rules in the order that keeps hashing
|
||||
// bounded: the cheap length and encoding checks first, the expensive KDF only
|
||||
// for a password that passes them.
|
||||
@@ -52,3 +56,18 @@ func (credentials *Credentials) VerifyLoginPassword(ctx context.Context, raw str
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifyDummyLoginPassword spends the same password-hash work for an unknown
|
||||
// account as VerifyLoginPassword does for a known one. The result is always a
|
||||
// mismatch unless the hasher fails for an operational reason.
|
||||
func (credentials *Credentials) VerifyDummyLoginPassword(ctx context.Context, raw string) error {
|
||||
password, err := domain.ParseLoginPassword(raw)
|
||||
if err != nil {
|
||||
password, _ = domain.ParseLoginPassword(dummyLoginPassword)
|
||||
}
|
||||
err = credentials.hasher.VerifyDummy(ctx, password)
|
||||
if errors.Is(err, outbound.ErrPasswordMismatch) {
|
||||
return outbound.ErrPasswordMismatch
|
||||
}
|
||||
return fmt.Errorf("Credentials.VerifyDummyLoginPassword - verify dummy hash: %w", err)
|
||||
}
|
||||
@@ -20,6 +20,7 @@ type countingHasher struct {
|
||||
hashCalls int
|
||||
hashed domain.Password
|
||||
verifyCalls int
|
||||
dummyCalls int
|
||||
verified domain.Password
|
||||
stored domain.PasswordHash
|
||||
verifyErr error
|
||||
@@ -39,7 +40,8 @@ func (hasher *countingHasher) Verify(_ context.Context, password domain.Password
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) VerifyDummy(context.Context, domain.Password) error {
|
||||
return errors.New("countingHasher.VerifyDummy - not used")
|
||||
hasher.dummyCalls++
|
||||
return outbound.ErrPasswordMismatch
|
||||
}
|
||||
|
||||
var _ outbound.PasswordHasher = (*countingHasher)(nil)
|
||||
@@ -116,3 +118,16 @@ func TestVerifyLoginPasswordRejectsEmptyInputBeforeKDF(t *testing.T) {
|
||||
t.Fatalf("VerifyLoginPassword(empty) = %v after %d verify calls, want ErrInvalidPassword before KDF", err, hasher.verifyCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyDummyLoginPasswordAlwaysRunsDummyHashWork(t *testing.T) {
|
||||
hasher := &countingHasher{}
|
||||
credentials := NewCredentials(hasher)
|
||||
for _, password := range []string{"correct horse battery staple", ""} {
|
||||
if err := credentials.VerifyDummyLoginPassword(context.Background(), password); !errors.Is(err, outbound.ErrPasswordMismatch) {
|
||||
t.Fatalf("VerifyDummyLoginPassword() error = %v, want ErrPasswordMismatch", err)
|
||||
}
|
||||
}
|
||||
if hasher.dummyCalls != 2 || hasher.verifyCalls != 0 {
|
||||
t.Fatalf("dummy calls=%d normal calls=%d, want two dummy calls", hasher.dummyCalls, hasher.verifyCalls)
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,18 @@ var (
|
||||
// ErrVerificationTokenExpired reports an email verification token past its
|
||||
// expiry time.
|
||||
ErrVerificationTokenExpired = errors.New("verification token expired")
|
||||
|
||||
// ErrInvalidCredentials represents an unknown account or an incorrect
|
||||
// password with one public outcome.
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
|
||||
// ErrEmailNotVerified reports correct credentials for an unverified
|
||||
// account. It never creates a session.
|
||||
ErrEmailNotVerified = errors.New("email not verified")
|
||||
|
||||
// ErrUnauthenticated reports a missing, invalid, expired, idle, or revoked
|
||||
// server session.
|
||||
ErrUnauthenticated = errors.New("unauthenticated")
|
||||
)
|
||||
|
||||
// RateLimitedError carries how long the caller waits before a repeat can be
|
||||
|
||||
@@ -3,9 +3,11 @@ package identity
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
@@ -20,6 +22,7 @@ const (
|
||||
labelEmailBucket = "lincodex/identity/email-bucket/v1"
|
||||
labelClientBucket = "lincodex/identity/client-bucket/v1"
|
||||
labelTokenBucket = "lincodex/identity/verification-token-bucket/v1"
|
||||
labelSessionCSRF = "lincodex/identity/session-csrf/v1"
|
||||
)
|
||||
|
||||
// Keyring computes the keyed digests of the anonymous identity operations:
|
||||
@@ -33,6 +36,7 @@ type Keyring struct {
|
||||
bucketKey []byte
|
||||
clientKey []byte
|
||||
tokenKey []byte
|
||||
sessionCSRFKey []byte
|
||||
}
|
||||
|
||||
// NewKeyring derives the purpose keys from secret.
|
||||
@@ -46,6 +50,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
bucketKey: derive(secret, labelEmailBucket),
|
||||
clientKey: derive(secret, labelClientBucket),
|
||||
tokenKey: derive(secret, labelTokenBucket),
|
||||
sessionCSRFKey: derive(secret, labelSessionCSRF),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -99,3 +104,26 @@ func (keyring *Keyring) VerificationTokenBucket(rawToken string) string {
|
||||
mac.Write([]byte(rawToken))
|
||||
return "identity:verification-token:" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// SessionCSRF derives a synchronizer token for exactly one session. The
|
||||
// purpose key and message are both domain-separated from every other keyring
|
||||
// use, and only the encoded result is returned to the HTTP adapter.
|
||||
func (keyring *Keyring) SessionCSRF(token domain.SecretToken) string {
|
||||
if token.IsZero() {
|
||||
return ""
|
||||
}
|
||||
mac := hmac.New(sha256.New, keyring.sessionCSRFKey)
|
||||
mac.Write([]byte(labelSessionCSRF))
|
||||
mac.Write([]byte{0})
|
||||
mac.Write([]byte(token.Reveal()))
|
||||
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// VerifySessionCSRF compares the supplied synchronizer token in constant
|
||||
// time with the token bound to this session.
|
||||
func (keyring *Keyring) VerifySessionCSRF(token domain.SecretToken, supplied string) bool {
|
||||
if token.IsZero() {
|
||||
return false
|
||||
}
|
||||
return hmac.Equal([]byte(keyring.SessionCSRF(token)), []byte(supplied))
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// SessionSettings bounds login attempts and the life of a server-side
|
||||
// session. Session expiry is enforced by PostgreSQL on every lookup.
|
||||
type SessionSettings struct {
|
||||
ClientHourlyLimit int64
|
||||
EmailHourlyLimit int64
|
||||
IdleTimeout time.Duration
|
||||
AbsoluteLifetime time.Duration
|
||||
}
|
||||
|
||||
// SessionDependencies are the collaborators of SessionService. Metrics and
|
||||
// logger are optional; all other dependencies are required.
|
||||
type SessionDependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Users outbound.UserRepository
|
||||
Sessions outbound.SessionRepository
|
||||
Credentials *Credentials
|
||||
Limiter outbound.RateLimiter
|
||||
Keyring *Keyring
|
||||
Clock func() time.Time
|
||||
Metrics RateLimitMetrics
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
// SessionService authenticates accounts and manages their server-side
|
||||
// sessions. It keeps no mutable per-request state.
|
||||
type SessionService struct {
|
||||
deps SessionDependencies
|
||||
settings SessionSettings
|
||||
}
|
||||
|
||||
func NewSessionService(deps SessionDependencies, settings SessionSettings) (*SessionService, error) {
|
||||
switch {
|
||||
case deps.Transactor == nil, deps.Users == nil, deps.Sessions == nil, deps.Credentials == nil,
|
||||
deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil:
|
||||
return nil, errors.New("identity.NewSessionService - every dependency must be set")
|
||||
case settings.ClientHourlyLimit < 1, settings.EmailHourlyLimit < 1,
|
||||
settings.IdleTimeout <= 0, settings.AbsoluteLifetime <= 0,
|
||||
settings.IdleTimeout > settings.AbsoluteLifetime:
|
||||
return nil, errors.New("identity.NewSessionService - invalid session settings")
|
||||
}
|
||||
if deps.Logger == nil {
|
||||
deps.Logger = slog.Default()
|
||||
}
|
||||
return &SessionService{deps: deps, settings: settings}, nil
|
||||
}
|
||||
|
||||
// LoginCommand is the content of an unvalidated login request.
|
||||
type LoginCommand struct {
|
||||
Email string
|
||||
Password string
|
||||
ClientKey string
|
||||
Incoming domain.SecretToken
|
||||
}
|
||||
|
||||
// LoginResult contains the user-facing session response and the raw cookie
|
||||
// token. The token is redacted by domain.SecretToken and must only be revealed
|
||||
// by the HTTP adapter when it writes Set-Cookie.
|
||||
type LoginResult struct {
|
||||
User domain.User
|
||||
Session domain.Session
|
||||
Token domain.SecretToken
|
||||
CSRFToken string
|
||||
}
|
||||
|
||||
// AuthenticatedSession is the server-side identity resolved from a cookie.
|
||||
// It contains no raw session token or credential material.
|
||||
type AuthenticatedSession struct {
|
||||
User domain.User
|
||||
SessionID uuid.UUID
|
||||
CSRFToken string
|
||||
}
|
||||
|
||||
// Login checks both rate limits before password verification. Unknown
|
||||
// addresses receive the dummy password-hash work; an invalid stored hash is
|
||||
// logged without account details and follows the same public failure path.
|
||||
func (service *SessionService) Login(ctx context.Context, command LoginCommand) (LoginResult, error) {
|
||||
const location = "SessionService.Login"
|
||||
email, err := domain.NewEmailAddress(command.Email)
|
||||
if err != nil {
|
||||
return LoginResult{}, fmt.Errorf("%s - validate email: %w", location, invalidField(emailPointer, err))
|
||||
}
|
||||
if err := service.takeLoginAttempt(ctx, email, command.ClientKey); err != nil {
|
||||
return LoginResult{}, fmt.Errorf("%s - limit login: %w", location, err)
|
||||
}
|
||||
user, err := service.loginUser(ctx, email, command.Password)
|
||||
if err != nil {
|
||||
return LoginResult{}, err
|
||||
}
|
||||
|
||||
token, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
return LoginResult{}, fmt.Errorf("%s - create session token: %w", location, err)
|
||||
}
|
||||
authenticatedUser, created, err := service.createLoginSession(ctx, user, command.Incoming, token)
|
||||
if err != nil {
|
||||
return LoginResult{}, fmt.Errorf("%s - rotate session: %w", location, err)
|
||||
}
|
||||
return LoginResult{
|
||||
User: authenticatedUser,
|
||||
Session: created,
|
||||
Token: token,
|
||||
CSRFToken: service.deps.Keyring.SessionCSRF(token),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *SessionService) loginUser(ctx context.Context, email domain.EmailAddress, password string) (domain.User, error) {
|
||||
user, err := service.deps.Users.GetByEmail(ctx, email)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
if dummyErr := service.verifyDummyLoginPassword(ctx, password); dummyErr != nil {
|
||||
return domain.User{}, dummyErr
|
||||
}
|
||||
return domain.User{}, ErrInvalidCredentials
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("SessionService.Login - read account: %w", err)
|
||||
}
|
||||
if err := service.verifyLoginPassword(ctx, password, user.PasswordHash); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return domain.User{}, ErrEmailNotVerified
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (service *SessionService) verifyLoginPassword(ctx context.Context, password string, passwordHash domain.PasswordHash) error {
|
||||
err := service.deps.Credentials.VerifyLoginPassword(ctx, password, passwordHash)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, outbound.ErrPasswordMismatch) {
|
||||
return ErrInvalidCredentials
|
||||
}
|
||||
if errors.Is(err, domain.ErrInvalidPassword) || errors.Is(err, outbound.ErrPasswordHashCorrupt) ||
|
||||
errors.Is(err, domain.ErrInvalidPasswordHash) {
|
||||
if errors.Is(err, outbound.ErrPasswordHashCorrupt) || errors.Is(err, domain.ErrInvalidPasswordHash) {
|
||||
service.deps.Logger.ErrorContext(ctx, "login rejected because the stored password hash is invalid")
|
||||
}
|
||||
if dummyErr := service.verifyDummyLoginPassword(ctx, password); dummyErr != nil {
|
||||
return dummyErr
|
||||
}
|
||||
return ErrInvalidCredentials
|
||||
}
|
||||
return fmt.Errorf("SessionService.Login - verify password: %w", err)
|
||||
}
|
||||
|
||||
func (service *SessionService) verifyDummyLoginPassword(ctx context.Context, password string) error {
|
||||
err := service.deps.Credentials.VerifyDummyLoginPassword(ctx, password)
|
||||
if err == nil || errors.Is(err, outbound.ErrPasswordMismatch) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("SessionService.Login - verify dummy password: %w", err)
|
||||
}
|
||||
|
||||
func (service *SessionService) createLoginSession(
|
||||
ctx context.Context,
|
||||
loginSnapshot domain.User,
|
||||
incoming, token domain.SecretToken,
|
||||
) (domain.User, domain.Session, error) {
|
||||
startedAt := service.deps.Clock()
|
||||
var authenticatedUser domain.User
|
||||
var created domain.Session
|
||||
err := service.deps.Transactor.WithinTransaction(ctx, func(tx context.Context, unit outbound.UnitOfWork) error {
|
||||
user, session, err := service.createLoginSessionInTransaction(tx, unit, loginSnapshot, incoming, token, startedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
authenticatedUser = user
|
||||
created = session
|
||||
return nil
|
||||
})
|
||||
return authenticatedUser, created, err
|
||||
}
|
||||
|
||||
func (service *SessionService) createLoginSessionInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
loginSnapshot domain.User,
|
||||
incoming, token domain.SecretToken,
|
||||
startedAt time.Time,
|
||||
) (domain.User, domain.Session, error) {
|
||||
const location = "SessionService.Login"
|
||||
user, err := unit.Users().GetByID(ctx, loginSnapshot.ID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return domain.User{}, domain.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, domain.Session{}, fmt.Errorf("%s - recheck account: %w", location, err)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return domain.User{}, domain.Session{}, ErrEmailNotVerified
|
||||
}
|
||||
if !sameLoginCredentials(loginSnapshot, user) {
|
||||
return domain.User{}, domain.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
if err := service.revokeIncomingSession(ctx, unit.Sessions(), incoming, startedAt); err != nil {
|
||||
return domain.User{}, domain.Session{}, err
|
||||
}
|
||||
session, err := domain.NewSession(domain.NewSessionInput{
|
||||
UserID: user.ID,
|
||||
TokenHash: token.Hash(),
|
||||
StartedAt: startedAt,
|
||||
AbsoluteLifetime: service.settings.AbsoluteLifetime,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.User{}, domain.Session{}, fmt.Errorf("%s - build session: %w", location, err)
|
||||
}
|
||||
if err := unit.Sessions().Create(ctx, session); err != nil {
|
||||
return domain.User{}, domain.Session{}, fmt.Errorf("%s - create session: %w", location, err)
|
||||
}
|
||||
return user, session, nil
|
||||
}
|
||||
|
||||
func sameLoginCredentials(snapshot, current domain.User) bool {
|
||||
return snapshot.RegistrationVersion == current.RegistrationVersion &&
|
||||
snapshot.PasswordHash.PHC() == current.PasswordHash.PHC()
|
||||
}
|
||||
|
||||
func (service *SessionService) revokeIncomingSession(
|
||||
ctx context.Context,
|
||||
sessions outbound.SessionRepository,
|
||||
incoming domain.SecretToken,
|
||||
now time.Time,
|
||||
) error {
|
||||
if incoming.IsZero() {
|
||||
return nil
|
||||
}
|
||||
old, err := sessions.FindActive(ctx, incoming.Hash(), now, service.settings.IdleTimeout)
|
||||
if errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("SessionService.Login - read incoming session: %w", err)
|
||||
}
|
||||
if err := sessions.Revoke(ctx, old.ID, now); err != nil && !errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return fmt.Errorf("SessionService.Login - revoke incoming session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Authenticate validates the cookie against PostgreSQL, checks the account
|
||||
// remains verified, and records activity subject to the session idle timeout.
|
||||
func (service *SessionService) Authenticate(ctx context.Context, rawToken string) (AuthenticatedSession, error) {
|
||||
const location = "SessionService.Authenticate"
|
||||
token, err := domain.ParseSecretToken(rawToken)
|
||||
if err != nil {
|
||||
return AuthenticatedSession{}, ErrUnauthenticated
|
||||
}
|
||||
now := service.deps.Clock()
|
||||
session, err := service.deps.Sessions.FindActive(ctx, token.Hash(), now, service.settings.IdleTimeout)
|
||||
if errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return AuthenticatedSession{}, ErrUnauthenticated
|
||||
}
|
||||
if err != nil {
|
||||
return AuthenticatedSession{}, fmt.Errorf("%s - read session: %w", location, err)
|
||||
}
|
||||
user, err := service.deps.Users.GetByID(ctx, session.UserID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) || err == nil && !user.EmailVerified() {
|
||||
return AuthenticatedSession{}, ErrUnauthenticated
|
||||
}
|
||||
if err != nil {
|
||||
return AuthenticatedSession{}, fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if err := service.deps.Sessions.Touch(ctx, session.ID, now, service.settings.IdleTimeout); errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return AuthenticatedSession{}, ErrUnauthenticated
|
||||
} else if err != nil {
|
||||
return AuthenticatedSession{}, fmt.Errorf("%s - record activity: %w", location, err)
|
||||
}
|
||||
return AuthenticatedSession{
|
||||
User: user,
|
||||
SessionID: session.ID,
|
||||
CSRFToken: service.deps.Keyring.SessionCSRF(token),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Logout revokes the session ID placed in context by authentication. A
|
||||
// repeated logout is treated as an unauthenticated stale session.
|
||||
func (service *SessionService) Logout(ctx context.Context, sessionID uuid.UUID) error {
|
||||
if sessionID == uuid.Nil {
|
||||
return ErrUnauthenticated
|
||||
}
|
||||
if err := service.deps.Sessions.Revoke(ctx, sessionID, service.deps.Clock()); errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return ErrUnauthenticated
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("SessionService.Logout - revoke session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *SessionService) takeLoginAttempt(ctx context.Context, email domain.EmailAddress, clientKey string) error {
|
||||
if clientKey != "" {
|
||||
if err := service.take(ctx, ScopeClient, service.deps.Keyring.ClientBucket(clientKey), service.settings.ClientHourlyLimit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return service.take(ctx, ScopeAddress, service.deps.Keyring.EmailBucket(email.Normalized()), service.settings.EmailHourlyLimit)
|
||||
}
|
||||
|
||||
func (service *SessionService) take(ctx context.Context, scope, bucket string, limit int64) error {
|
||||
decision, err := service.deps.Limiter.Take(ctx, bucket, outbound.RateLimitRule{Window: time.Hour, Limit: limit})
|
||||
if err != nil {
|
||||
return fmt.Errorf("take %s login limit: %w", scope, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
if service.deps.Metrics != nil {
|
||||
service.deps.Metrics.ObserveIdentityRateLimited(scope)
|
||||
}
|
||||
return &RateLimitedError{RetryAfter: decision.RetryAfter}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type sessionTestUserRepository struct {
|
||||
outbound.UserRepository
|
||||
|
||||
users map[uuid.UUID]domain.User
|
||||
byEmail map[string]domain.User
|
||||
getByEmailCalls int
|
||||
afterGetByEmail func()
|
||||
}
|
||||
|
||||
func (repository *sessionTestUserRepository) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, ok := repository.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (repository *sessionTestUserRepository) GetByEmail(_ context.Context, email domain.EmailAddress) (domain.User, error) {
|
||||
repository.getByEmailCalls++
|
||||
user, ok := repository.byEmail[email.Normalized()]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
if repository.afterGetByEmail != nil {
|
||||
repository.afterGetByEmail()
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type sessionTestSessionRepository struct {
|
||||
outbound.SessionRepository
|
||||
|
||||
active map[domain.SecretTokenHash]domain.Session
|
||||
created []domain.Session
|
||||
revoked []uuid.UUID
|
||||
touched []uuid.UUID
|
||||
}
|
||||
|
||||
func (repository *sessionTestSessionRepository) Create(_ context.Context, session domain.Session) error {
|
||||
repository.active[session.TokenHash] = session
|
||||
repository.created = append(repository.created, session)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository *sessionTestSessionRepository) FindActive(
|
||||
_ context.Context,
|
||||
hash domain.SecretTokenHash,
|
||||
at time.Time,
|
||||
idleTimeout time.Duration,
|
||||
) (domain.Session, error) {
|
||||
session, ok := repository.active[hash]
|
||||
if !ok || session.RevokedAt != nil || !session.ExpiresAt.After(at) || !session.LastSeenAt.After(at.Add(-idleTimeout)) {
|
||||
return domain.Session{}, outbound.ErrSessionNotFound
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (repository *sessionTestSessionRepository) Touch(_ context.Context, id uuid.UUID, at time.Time, idleTimeout time.Duration) error {
|
||||
for hash, session := range repository.active {
|
||||
if session.ID != id {
|
||||
continue
|
||||
}
|
||||
if session.RevokedAt != nil || !session.ExpiresAt.After(at) || !session.LastSeenAt.After(at.Add(-idleTimeout)) {
|
||||
return outbound.ErrSessionNotFound
|
||||
}
|
||||
session.LastSeenAt = at
|
||||
repository.active[hash] = session
|
||||
repository.touched = append(repository.touched, id)
|
||||
return nil
|
||||
}
|
||||
return outbound.ErrSessionNotFound
|
||||
}
|
||||
|
||||
func (repository *sessionTestSessionRepository) Revoke(_ context.Context, id uuid.UUID, at time.Time) error {
|
||||
for hash, session := range repository.active {
|
||||
if session.ID != id {
|
||||
continue
|
||||
}
|
||||
if session.RevokedAt != nil {
|
||||
return outbound.ErrSessionNotFound
|
||||
}
|
||||
session.RevokedAt = &at
|
||||
repository.active[hash] = session
|
||||
repository.revoked = append(repository.revoked, id)
|
||||
return nil
|
||||
}
|
||||
return outbound.ErrSessionNotFound
|
||||
}
|
||||
|
||||
type sessionTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
users outbound.UserRepository
|
||||
sessions outbound.SessionRepository
|
||||
}
|
||||
|
||||
func (unit sessionTestUnit) Users() outbound.UserRepository { return unit.users }
|
||||
func (unit sessionTestUnit) Sessions() outbound.SessionRepository { return unit.sessions }
|
||||
|
||||
type sessionTestTransactor struct{ unit outbound.UnitOfWork }
|
||||
|
||||
func (transactor sessionTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
type sessionTestLimiter struct {
|
||||
decision outbound.RateLimitDecision
|
||||
keys []string
|
||||
}
|
||||
|
||||
func (limiter *sessionTestLimiter) Take(_ context.Context, key string, _ ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) {
|
||||
limiter.keys = append(limiter.keys, key)
|
||||
return limiter.decision, nil
|
||||
}
|
||||
|
||||
type sessionTestHasher struct {
|
||||
verifyErr error
|
||||
dummyErr error
|
||||
verifyCalls int
|
||||
dummyCalls int
|
||||
}
|
||||
|
||||
func (*sessionTestHasher) Hash(context.Context, domain.Password) (domain.PasswordHash, error) {
|
||||
return domain.NewPasswordHash(testPasswordPHC)
|
||||
}
|
||||
|
||||
func (hasher *sessionTestHasher) Verify(context.Context, domain.Password, domain.PasswordHash) (bool, error) {
|
||||
hasher.verifyCalls++
|
||||
return false, hasher.verifyErr
|
||||
}
|
||||
|
||||
func (hasher *sessionTestHasher) VerifyDummy(context.Context, domain.Password) error {
|
||||
hasher.dummyCalls++
|
||||
if hasher.dummyErr != nil {
|
||||
return hasher.dummyErr
|
||||
}
|
||||
return outbound.ErrPasswordMismatch
|
||||
}
|
||||
|
||||
type sessionTestFixture struct {
|
||||
service *SessionService
|
||||
users *sessionTestUserRepository
|
||||
sessions *sessionTestSessionRepository
|
||||
limiter *sessionTestLimiter
|
||||
hasher *sessionTestHasher
|
||||
keyring *Keyring
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func newSessionTestFixture(t *testing.T, user domain.User, limiterDecision outbound.RateLimitDecision, verifyErr error) sessionTestFixture {
|
||||
t.Helper()
|
||||
now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
users := &sessionTestUserRepository{
|
||||
users: map[uuid.UUID]domain.User{user.ID: user},
|
||||
byEmail: map[string]domain.User{user.Email.Normalized(): user},
|
||||
}
|
||||
sessions := &sessionTestSessionRepository{active: make(map[domain.SecretTokenHash]domain.Session)}
|
||||
unit := sessionTestUnit{users: users, sessions: sessions}
|
||||
transactor := sessionTestTransactor{unit: unit}
|
||||
limiter := &sessionTestLimiter{decision: limiterDecision}
|
||||
hasher := &sessionTestHasher{verifyErr: verifyErr}
|
||||
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service, err := NewSessionService(SessionDependencies{
|
||||
Transactor: transactor,
|
||||
Users: users,
|
||||
Sessions: sessions,
|
||||
Credentials: NewCredentials(hasher),
|
||||
Limiter: limiter,
|
||||
Keyring: keyring,
|
||||
Clock: func() time.Time { return now },
|
||||
Logger: slog.New(slog.NewTextHandler(&strings.Builder{}, nil)),
|
||||
}, SessionSettings{
|
||||
ClientHourlyLimit: 30,
|
||||
EmailHourlyLimit: 10,
|
||||
IdleTimeout: 24 * time.Hour,
|
||||
AbsoluteLifetime: 7 * 24 * time.Hour,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sessionTestFixture{service: service, users: users, sessions: sessions, limiter: limiter, hasher: hasher, keyring: keyring, now: now}
|
||||
}
|
||||
|
||||
func sessionTestUser(t *testing.T, address string, verified bool, at time.Time) domain.User {
|
||||
t.Helper()
|
||||
email, err := domain.NewEmailAddress(address)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash, err := domain.NewPasswordHash(testPasswordPHC)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user, err := domain.NewUser(domain.Registration{
|
||||
Email: email,
|
||||
PasswordHash: hash,
|
||||
Scenario: domain.ScenarioCandidate,
|
||||
RegisteredAt: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if verified {
|
||||
verifiedAt := at
|
||||
user.EmailVerifiedAt = &verifiedAt
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
func TestSessionServiceLoginRotatesIncomingSessionAtomically(t *testing.T) {
|
||||
now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
user := sessionTestUser(t, "person@example.com", true, now)
|
||||
fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil)
|
||||
incoming, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old, err := domain.NewSession(domain.NewSessionInput{
|
||||
UserID: user.ID,
|
||||
TokenHash: incoming.Hash(),
|
||||
StartedAt: now.Add(-time.Hour),
|
||||
AbsoluteLifetime: 7 * 24 * time.Hour,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixture.sessions.active[old.TokenHash] = old
|
||||
|
||||
result, err := fixture.service.Login(context.Background(), LoginCommand{
|
||||
Email: "PERSON@example.com",
|
||||
Password: "correct horse battery staple",
|
||||
ClientKey: "client-address",
|
||||
Incoming: incoming,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Login() error = %v", err)
|
||||
}
|
||||
if len(fixture.sessions.created) != 1 || len(fixture.sessions.revoked) != 1 || fixture.sessions.revoked[0] != old.ID {
|
||||
t.Fatalf("rotation created %d sessions and revoked %v", len(fixture.sessions.created), fixture.sessions.revoked)
|
||||
}
|
||||
if result.Session.TokenHash == incoming.Hash() || result.Session.UserID != user.ID || !result.Session.ExpiresAt.Equal(now.Add(7*24*time.Hour)) {
|
||||
t.Fatalf("new session = %+v, want a fresh token for the verified user with the configured deadline", result.Session)
|
||||
}
|
||||
if result.Token.Hash() != result.Session.TokenHash || !fixture.keyring.VerifySessionCSRF(result.Token, result.CSRFToken) {
|
||||
t.Fatal("login result did not bind the cookie token, database hash, and CSRF token")
|
||||
}
|
||||
if fixture.hasher.verifyCalls != 1 || fixture.limiter.keys[0] != fixture.keyring.ClientBucket("client-address") ||
|
||||
fixture.limiter.keys[1] != fixture.keyring.EmailBucket(user.Email.Normalized()) {
|
||||
t.Fatalf("login checks: hash calls=%d, limiter keys=%v", fixture.hasher.verifyCalls, fixture.limiter.keys)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionServiceLoginKeepsUnknownAndWrongCredentialsIndistinguishable(t *testing.T) {
|
||||
now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
user *domain.User
|
||||
verifyErr error
|
||||
wantDummy int
|
||||
}{
|
||||
{name: "unknown account", wantDummy: 1},
|
||||
{name: "wrong password", verifyErr: outbound.ErrPasswordMismatch},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var user domain.User
|
||||
if test.user != nil {
|
||||
user = *test.user
|
||||
} else if test.verifyErr != nil {
|
||||
user = sessionTestUser(t, "person@example.com", true, now)
|
||||
}
|
||||
fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, test.verifyErr)
|
||||
_, err := fixture.service.Login(context.Background(), LoginCommand{Email: "person@example.com", Password: "not the password"})
|
||||
if !errors.Is(err, ErrInvalidCredentials) || fixture.hasher.dummyCalls != test.wantDummy || len(fixture.sessions.created) != 0 {
|
||||
t.Fatalf("Login() error=%v dummy=%d sessions=%d", err, fixture.hasher.dummyCalls, len(fixture.sessions.created))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionServiceLoginDoesNotCreateOrRotateForUnverifiedAccount(t *testing.T) {
|
||||
now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
user := sessionTestUser(t, "pending@example.com", false, now)
|
||||
fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil)
|
||||
incoming, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old, err := domain.NewSession(domain.NewSessionInput{
|
||||
UserID: user.ID, TokenHash: incoming.Hash(), StartedAt: now.Add(-time.Hour), AbsoluteLifetime: 7 * 24 * time.Hour,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixture.sessions.active[old.TokenHash] = old
|
||||
|
||||
_, err = fixture.service.Login(context.Background(), LoginCommand{
|
||||
Email: "pending@example.com", Password: "correct horse battery staple", Incoming: incoming,
|
||||
})
|
||||
if !errors.Is(err, ErrEmailNotVerified) || len(fixture.sessions.created) != 0 || len(fixture.sessions.revoked) != 0 {
|
||||
t.Fatalf("Login() error=%v created=%d revoked=%v", err, len(fixture.sessions.created), fixture.sessions.revoked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionServiceLoginRejectsChangedCredentialSnapshot(t *testing.T) {
|
||||
now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
changedPasswordHash, err := domain.NewPasswordHash(strings.Replace(testPasswordPHC, "aGFza", "bGFza", 1))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
change func(domain.User) domain.User
|
||||
}{
|
||||
{
|
||||
name: "registration version",
|
||||
change: func(user domain.User) domain.User {
|
||||
user.RegistrationVersion++
|
||||
return user
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "password hash",
|
||||
change: func(user domain.User) domain.User {
|
||||
user.PasswordHash = changedPasswordHash
|
||||
return user
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
user := sessionTestUser(t, "person@example.com", true, now)
|
||||
fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil)
|
||||
fixture.users.afterGetByEmail = func() {
|
||||
changed := fixture.users.users[user.ID]
|
||||
fixture.users.users[user.ID] = test.change(changed)
|
||||
}
|
||||
|
||||
_, err := fixture.service.Login(context.Background(), LoginCommand{
|
||||
Email: "person@example.com", Password: "correct horse battery staple",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCredentials) || len(fixture.sessions.created) != 0 || len(fixture.sessions.revoked) != 0 {
|
||||
t.Fatalf("Login() error=%v created=%d revoked=%v, want changed snapshot rejected without session writes", err, len(fixture.sessions.created), fixture.sessions.revoked)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionServiceLoginAppliesEmailLimitBeforeAccountLookup(t *testing.T) {
|
||||
now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
user := sessionTestUser(t, "person@example.com", true, now)
|
||||
fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: false, RetryAfter: time.Minute}, nil)
|
||||
_, err := fixture.service.Login(context.Background(), LoginCommand{Email: "person@example.com", Password: "correct horse battery staple"})
|
||||
var limited *RateLimitedError
|
||||
if !errors.As(err, &limited) || limited.RetryAfter != time.Minute || fixture.users.getByEmailCalls != 0 || fixture.hasher.verifyCalls != 0 {
|
||||
t.Fatalf("Login() error=%v, lookups=%d, verifies=%d", err, fixture.users.getByEmailCalls, fixture.hasher.verifyCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionServiceAuthenticateUsesDatabaseSessionState(t *testing.T) {
|
||||
now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
user := sessionTestUser(t, "person@example.com", true, now)
|
||||
fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil)
|
||||
token, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
session, err := domain.NewSession(domain.NewSessionInput{
|
||||
UserID: user.ID, TokenHash: token.Hash(), StartedAt: now.Add(-time.Minute), AbsoluteLifetime: 7 * 24 * time.Hour,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixture.sessions.active[session.TokenHash] = session
|
||||
|
||||
authenticated, err := fixture.service.Authenticate(context.Background(), token.Reveal())
|
||||
if err != nil || authenticated.SessionID != session.ID || authenticated.User.ID != user.ID || len(fixture.sessions.touched) != 1 {
|
||||
t.Fatalf("Authenticate() = %+v, %v, touches=%v", authenticated, err, fixture.sessions.touched)
|
||||
}
|
||||
if !fixture.keyring.VerifySessionCSRF(token, authenticated.CSRFToken) {
|
||||
t.Fatal("authenticated session returned a CSRF token for a different session")
|
||||
}
|
||||
if _, err := fixture.service.Authenticate(context.Background(), "bad"); !errors.Is(err, ErrUnauthenticated) {
|
||||
t.Fatalf("Authenticate(malformed) error = %v, want ErrUnauthenticated", err)
|
||||
}
|
||||
|
||||
expired, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expiredSession, err := domain.NewSession(domain.NewSessionInput{
|
||||
UserID: user.ID, TokenHash: expired.Hash(), StartedAt: now.Add(-8 * 24 * time.Hour), AbsoluteLifetime: 7 * 24 * time.Hour,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixture.sessions.active[expiredSession.TokenHash] = expiredSession
|
||||
if _, err := fixture.service.Authenticate(context.Background(), expired.Reveal()); !errors.Is(err, ErrUnauthenticated) {
|
||||
t.Fatalf("Authenticate(expired) error = %v, want ErrUnauthenticated", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyringSessionCSRFIsDomainSeparatedAndFailsClosed(t *testing.T) {
|
||||
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
csrf := keyring.SessionCSRF(first)
|
||||
if len(csrf) != 43 || !keyring.VerifySessionCSRF(first, csrf) || keyring.VerifySessionCSRF(second, csrf) ||
|
||||
keyring.VerifySessionCSRF(domain.SecretToken{}, "") {
|
||||
t.Fatal("session CSRF derivation did not stay bound to a valid session token")
|
||||
}
|
||||
}
|
||||
|
||||
var _ outbound.UserRepository = (*sessionTestUserRepository)(nil)
|
||||
var _ outbound.SessionRepository = (*sessionTestSessionRepository)(nil)
|
||||
var _ outbound.UnitOfWork = sessionTestUnit{}
|
||||
var _ outbound.Transactor = sessionTestTransactor{}
|
||||
var _ outbound.RateLimiter = (*sessionTestLimiter)(nil)
|
||||
var _ outbound.PasswordHasher = (*sessionTestHasher)(nil)
|
||||
@@ -0,0 +1,130 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var ErrDuplicateRiskAcknowledgementRequired = errors.New("duplicate-risk acknowledgement is required")
|
||||
|
||||
const DuplicateRiskWarning = "The earlier send may already have been accepted. After the provider's deduplication window, the old key does not guarantee deduplication; retrying can send a duplicate."
|
||||
|
||||
// DeliveryRetryInspection contains the metadata an operator needs to decide
|
||||
// whether an unknown delivery is eligible for a manual retry. It has no
|
||||
// recipient address, token, subject, or body.
|
||||
type DeliveryRetryInspection struct {
|
||||
DeliveryID uuid.UUID
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
Status domain.DeliveryStatus
|
||||
AttemptCount int32
|
||||
NextAttemptAt time.Time
|
||||
FirstSendStartedAt time.Time
|
||||
ManualCycleStarted time.Time
|
||||
}
|
||||
|
||||
// DeliveryRetryOperator inspects and authorizes retries of terminal unknown
|
||||
// deliveries. Authorization only schedules work; the normal sender uses the
|
||||
// delivery's pinned provider account, key, and stored body for the call.
|
||||
type DeliveryRetryOperator struct {
|
||||
transactor outbound.Transactor
|
||||
deliveries outbound.DeliveryRepository
|
||||
account domain.MailProviderAccount
|
||||
providerWindow time.Duration
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewDeliveryRetryOperator(
|
||||
transactor outbound.Transactor,
|
||||
deliveries outbound.DeliveryRepository,
|
||||
account domain.MailProviderAccount,
|
||||
providerWindow time.Duration,
|
||||
clock func() time.Time,
|
||||
) (*DeliveryRetryOperator, error) {
|
||||
switch {
|
||||
case transactor == nil:
|
||||
return nil, errors.New("notification.NewDeliveryRetryOperator - transactor must be set")
|
||||
case deliveries == nil:
|
||||
return nil, errors.New("notification.NewDeliveryRetryOperator - delivery repository must be set")
|
||||
case account.IsZero():
|
||||
return nil, errors.New("notification.NewDeliveryRetryOperator - provider account must be set")
|
||||
case providerWindow < 0:
|
||||
return nil, errors.New("notification.NewDeliveryRetryOperator - provider window must not be negative")
|
||||
case clock == nil:
|
||||
return nil, errors.New("notification.NewDeliveryRetryOperator - clock must be set")
|
||||
}
|
||||
return &DeliveryRetryOperator{
|
||||
transactor: transactor,
|
||||
deliveries: deliveries,
|
||||
account: account,
|
||||
providerWindow: providerWindow,
|
||||
clock: clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (operator *DeliveryRetryOperator) Inspect(ctx context.Context, id uuid.UUID) (DeliveryRetryInspection, error) {
|
||||
if id == uuid.Nil {
|
||||
return DeliveryRetryInspection{}, fmt.Errorf("DeliveryRetryOperator.Inspect - delivery ID is required: %w", domain.ErrInvalidDelivery)
|
||||
}
|
||||
snapshot, err := operator.deliveries.GetRetrySnapshot(ctx, id)
|
||||
if err != nil {
|
||||
return DeliveryRetryInspection{}, fmt.Errorf("DeliveryRetryOperator.Inspect - read delivery: %w", err)
|
||||
}
|
||||
return DeliveryRetryInspection{
|
||||
DeliveryID: snapshot.ID,
|
||||
Provider: snapshot.Provider,
|
||||
ProviderAccount: snapshot.ProviderAccount,
|
||||
Status: snapshot.Status,
|
||||
AttemptCount: snapshot.AttemptCount,
|
||||
NextAttemptAt: snapshot.NextAttemptAt,
|
||||
FirstSendStartedAt: snapshot.FirstSendStartedAt,
|
||||
ManualCycleStarted: snapshot.ManualRetryStartedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RetryUnknown requires the operator identity and explicit duplicate-risk
|
||||
// acknowledgement, then atomically schedules the current terminal unknown
|
||||
// attempt and appends its audit record.
|
||||
func (operator *DeliveryRetryOperator) RetryUnknown(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
actor string,
|
||||
acknowledgeDuplicateRisk bool,
|
||||
) (string, error) {
|
||||
if id == uuid.Nil {
|
||||
return "", fmt.Errorf("DeliveryRetryOperator.RetryUnknown - delivery ID is required: %w", domain.ErrInvalidDelivery)
|
||||
}
|
||||
if !acknowledgeDuplicateRisk {
|
||||
return "", ErrDuplicateRiskAcknowledgementRequired
|
||||
}
|
||||
parsedActor, err := domain.ParseMailRetryActor(actor)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
minimumAge := time.Duration(0)
|
||||
if operator.providerWindow > 0 {
|
||||
minimumAge = max(operator.providerWindow-dedupSafetyMargin, 0)
|
||||
}
|
||||
err = operator.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.Deliveries().AuthorizeUnknownRetry(
|
||||
ctx,
|
||||
id,
|
||||
operator.account,
|
||||
parsedActor,
|
||||
acknowledgeDuplicateRisk,
|
||||
operator.clock(),
|
||||
minimumAge,
|
||||
)
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("DeliveryRetryOperator.RetryUnknown - authorize retry: %w", err)
|
||||
}
|
||||
return DuplicateRiskWarning, nil
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestDeliveryRetryOperatorAuthorizesOneRetryAfterTheAutomaticCutoff(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("initial pass = %+v, want unknown", result)
|
||||
}
|
||||
operator, err := NewDeliveryRetryOperator(h.transactor, h.deliveries, testAccount(t, "resend"), testIdempotencyWindow, func() time.Time { return h.now })
|
||||
if err != nil {
|
||||
t.Fatalf("NewDeliveryRetryOperator() error = %v", err)
|
||||
}
|
||||
|
||||
inspection, err := operator.Inspect(t.Context(), h.delivery.ID())
|
||||
if err != nil || inspection.DeliveryID != h.delivery.ID() || inspection.Status != domain.DeliveryStatusUnknown ||
|
||||
inspection.ProviderAccount != "main" || inspection.AttemptCount != 1 {
|
||||
t.Fatalf("Inspect() = %+v, %v; want only delivery retry metadata", inspection, err)
|
||||
}
|
||||
if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", false); !errors.Is(err, ErrDuplicateRiskAcknowledgementRequired) {
|
||||
t.Fatalf("RetryUnknown() without acknowledgement error = %v, want acknowledgement required", err)
|
||||
}
|
||||
if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) {
|
||||
t.Fatalf("RetryUnknown() before cutoff error = %v, want not allowed", err)
|
||||
}
|
||||
if len(h.deliveries.retryDecisions) != 0 || len(h.transport.mails) != 1 {
|
||||
t.Fatal("a denied operator decision changed audit history or sent mail")
|
||||
}
|
||||
|
||||
h.now = h.now.Add(23 * time.Hour)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("pass at the safety cutoff = %+v, want the automatic retry to stop as unknown", result)
|
||||
}
|
||||
if got := h.stored().delivery; got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("delivery at the safety cutoff is %s due %s, want unknown without a due time", got.Status(), got.NextAttemptAt())
|
||||
}
|
||||
|
||||
warning, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true)
|
||||
if err != nil || warning != DuplicateRiskWarning {
|
||||
t.Fatalf("RetryUnknown() after cutoff = %q, %v; want the duplicate-risk warning", warning, err)
|
||||
}
|
||||
if len(h.deliveries.retryDecisions) != 1 || h.deliveries.retryDecisions[0].actor != "operator:mail-ops" ||
|
||||
!h.deliveries.retryDecisions[0].duplicateRiskAcknowledged || h.deliveries.retryDecisions[0].previousLeaseExpired {
|
||||
t.Fatalf("retry audit = %+v, want one acknowledged operator decision", h.deliveries.retryDecisions)
|
||||
}
|
||||
if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) {
|
||||
t.Fatalf("second RetryUnknown() error = %v, want not allowed", err)
|
||||
}
|
||||
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("manual retry pass = %+v, want accepted", result)
|
||||
}
|
||||
if len(h.transport.mails) != 2 || h.transport.mails[0].IdempotencyKey != h.transport.mails[1].IdempotencyKey ||
|
||||
h.transport.mails[0].IdempotencyKey != h.delivery.IdempotencyKey() ||
|
||||
h.transport.mails[0].TextBody != h.transport.mails[1].TextBody ||
|
||||
h.transport.mails[0].To.Address() != h.transport.mails[1].To.Address() {
|
||||
t.Fatal("the manual retry did not reuse the pinned key and original message")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliveryRetryOperatorRequiresAnotherDecisionAfterManualUnknown(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("initial pass = %+v, want unknown", result)
|
||||
}
|
||||
operator, err := NewDeliveryRetryOperator(h.transactor, h.deliveries, testAccount(t, "resend"), testIdempotencyWindow, func() time.Time { return h.now })
|
||||
if err != nil {
|
||||
t.Fatalf("NewDeliveryRetryOperator() error = %v", err)
|
||||
}
|
||||
h.now = h.now.Add(23 * time.Hour)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("pass at cutoff = %+v, want unknown", result)
|
||||
}
|
||||
if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil {
|
||||
t.Fatalf("RetryUnknown() after cutoff error = %v", err)
|
||||
}
|
||||
|
||||
h.transport.result = outbound.SendResult{
|
||||
Outcome: outbound.MailOutcomeRejected,
|
||||
Rejection: outbound.MailRejectionRateLimited,
|
||||
RetryAfter: 5 * time.Minute,
|
||||
}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassRetry {
|
||||
t.Fatalf("manual rate-limit pass = %+v, want a scheduled retry", result)
|
||||
}
|
||||
pending := h.stored().delivery
|
||||
if pending.Status() != domain.DeliveryStatusPending || !pending.NextAttemptAt().Equal(h.now.Add(5*time.Minute)) {
|
||||
t.Fatalf("manual rate-limit state = %s due %s, want pending with Retry-After", pending.Status(), pending.NextAttemptAt())
|
||||
}
|
||||
h.now = pending.NextAttemptAt()
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("manual uncertain pass = %+v, want unknown", result)
|
||||
}
|
||||
unknown := h.stored().delivery
|
||||
if unknown.Status() != domain.DeliveryStatusUnknown || !unknown.NextAttemptAt().IsZero() || len(h.deliveries.retryDecisions) != 1 {
|
||||
t.Fatalf("manual uncertain state = %s due %s with %d decisions, want terminal unknown and one audit decision", unknown.Status(), unknown.NextAttemptAt(), len(h.deliveries.retryDecisions))
|
||||
}
|
||||
calls := len(h.transport.mails)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassIdle || len(h.transport.mails) != calls {
|
||||
t.Fatalf("pass after manual unknown = %+v with %d calls, want idle without a retry", result, len(h.transport.mails))
|
||||
}
|
||||
if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil {
|
||||
t.Fatalf("second RetryUnknown() after explicit acknowledgement = %v, want a fresh decision against the original cutoff", err)
|
||||
}
|
||||
if len(h.deliveries.retryDecisions) != 2 {
|
||||
t.Fatalf("manual decisions = %d, want a new audit decision after the second unknown", len(h.deliveries.retryDecisions))
|
||||
}
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("pass after the new decision = %+v, want accepted", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliveryRetryOperatorKeepsConfirmedRefusalRetriesAfterTheDeduplicationCutoff(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("initial pass = %+v, want unknown", result)
|
||||
}
|
||||
operator, err := NewDeliveryRetryOperator(h.transactor, h.deliveries, testAccount(t, "resend"), testIdempotencyWindow, func() time.Time { return h.now })
|
||||
if err != nil {
|
||||
t.Fatalf("NewDeliveryRetryOperator() error = %v", err)
|
||||
}
|
||||
h.now = h.now.Add(23 * time.Hour)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("automatic pass at cutoff = %+v, want unknown", result)
|
||||
}
|
||||
if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil {
|
||||
t.Fatalf("RetryUnknown() after cutoff error = %v", err)
|
||||
}
|
||||
refusal := outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionRateLimited, RetryAfter: 5 * time.Minute}
|
||||
h.transport.result = refusal
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassRetry {
|
||||
t.Fatalf("first manual refusal = %+v, want retry", result)
|
||||
}
|
||||
h.now = h.stored().delivery.NextAttemptAt().Add(25 * time.Hour)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassRetry {
|
||||
t.Fatalf("confirmed refusal after the old provider window = %+v, want a scheduled retry", result)
|
||||
}
|
||||
if got := h.stored().delivery; got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 3 || got.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("delivery after repeated confirmed refusals is %s after %d attempts due %s; want pending without a fabricated unknown", got.Status(), got.AttemptCount(), got.NextAttemptAt())
|
||||
}
|
||||
h.now = h.stored().delivery.NextAttemptAt()
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("manual unknown result = %+v, want terminal unknown", result)
|
||||
}
|
||||
unknown := h.stored().delivery
|
||||
if unknown.Status() != domain.DeliveryStatusUnknown || !unknown.NextAttemptAt().IsZero() {
|
||||
t.Fatalf("delivery after unknown is %s due %s, want terminal unknown", unknown.Status(), unknown.NextAttemptAt())
|
||||
}
|
||||
calls := len(h.transport.mails)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassIdle || len(h.transport.mails) != calls {
|
||||
t.Fatalf("pass after unknown = %+v with %d calls, want idle", result, len(h.transport.mails))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliveryRetryOperatorRecoversManualSendStartedWithoutAResult(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("initial pass = %+v, want unknown", result)
|
||||
}
|
||||
operator, err := NewDeliveryRetryOperator(h.transactor, h.deliveries, testAccount(t, "resend"), testIdempotencyWindow, func() time.Time { return h.now })
|
||||
if err != nil {
|
||||
t.Fatalf("NewDeliveryRetryOperator() error = %v", err)
|
||||
}
|
||||
h.now = h.now.Add(23 * time.Hour)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("automatic pass at cutoff = %+v, want unknown", result)
|
||||
}
|
||||
if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil {
|
||||
t.Fatalf("RetryUnknown() after cutoff error = %v", err)
|
||||
}
|
||||
refusal := outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionRateLimited, RetryAfter: time.Minute}
|
||||
h.transport.result = refusal
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassRetry {
|
||||
t.Fatalf("first manual rate limit = %+v, want a confirmed refusal retry", result)
|
||||
}
|
||||
h.now = h.stored().delivery.NextAttemptAt()
|
||||
h.transactor.calls, h.transactor.settlementDown = 0, true
|
||||
if _, err := h.service.ProcessNext(t.Context(), t.Context()); !errors.Is(err, errSettlementDown) {
|
||||
t.Fatalf("ProcessNext() error = %v, want lost settlement after a started manual send", err)
|
||||
}
|
||||
if len(h.transport.mails) != 3 || !h.stored().hasSendStarted || h.stored().sendStartedAttemptCount != h.stored().delivery.AttemptCount() {
|
||||
t.Fatalf("manual send starts = %d, marker = %d, attempt_count = %d; want an unresolved send after a confirmed refusal", len(h.transport.mails), h.stored().sendStartedAttemptCount, h.stored().delivery.AttemptCount())
|
||||
}
|
||||
h.now = h.now.Add(testSenderLease)
|
||||
h.transactor.settlementDown = false
|
||||
calls := len(h.transport.mails)
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown || len(h.transport.mails) != calls {
|
||||
t.Fatalf("recovery after lost manual result = %+v with %d calls, want terminal unknown without a provider call", result, len(h.transport.mails)-calls)
|
||||
}
|
||||
if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil {
|
||||
t.Fatalf("new decision after expired manual send lease = %v, want authorization from the original cutoff", err)
|
||||
}
|
||||
if len(h.deliveries.retryDecisions) != 2 || h.deliveries.retryDecisions[1].attemptCount != 3 ||
|
||||
len(h.stored().attempts) != 3 || h.stored().attempts[1].Outcome != domain.DeliveryOutcomeRejected ||
|
||||
h.stored().attempts[2].Outcome != domain.DeliveryOutcomeUnknown {
|
||||
t.Fatalf("retry audit = %+v, attempts = %+v; want confirmed refusal then recovered unknown before the second decision", h.deliveries.retryDecisions, h.stored().attempts)
|
||||
}
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassAccepted {
|
||||
t.Fatalf("pass after a new manual decision = %+v, want accepted", result)
|
||||
}
|
||||
}
|
||||
@@ -150,8 +150,14 @@ func NewServiceMailSender(
|
||||
// claimedSend is a delivery that passed the claim transaction and is ready to
|
||||
// be sent, or the final result of a delivery the transaction already decided.
|
||||
type claimedSend struct {
|
||||
delivery domain.Delivery
|
||||
permit QuotaPermit
|
||||
delivery domain.Delivery
|
||||
permit QuotaPermit
|
||||
firstSendStarted bool
|
||||
sinceFirstSend time.Duration
|
||||
manualRetryPending bool
|
||||
manualRetryCycleStarted bool
|
||||
sendStartUnsettled bool
|
||||
requireDedupWindow bool
|
||||
// decided is set when the claim transaction ended the pass: the result
|
||||
// is final and nothing is sent.
|
||||
decided bool
|
||||
@@ -353,19 +359,23 @@ func (sender *ServiceMailSender) beforeSend(ctx context.Context, claim claimedSe
|
||||
return fmt.Errorf("read token and account: %w", err)
|
||||
}
|
||||
now := sender.clock()
|
||||
if reason := delivery.CheckServiceMail(state, now); reason != "" {
|
||||
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
|
||||
return fmt.Errorf("give the reservation back: %w", err)
|
||||
if result, handled, err := sender.handleInvalidClaim(ctx, unit, claim, delivery, state, now); err != nil || handled {
|
||||
if handled {
|
||||
decided = &result
|
||||
}
|
||||
cancelled, err := sender.cancel(ctx, unit, delivery, now, reason)
|
||||
return err
|
||||
}
|
||||
started, err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner,
|
||||
claim.requireDedupWindow, sender.safeRetryWindow())
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark send started: %w", err)
|
||||
}
|
||||
if !started {
|
||||
result, err := sender.handleUnmarkedSend(ctx, unit, claim, delivery, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
decided = &cancelled.result
|
||||
return nil
|
||||
}
|
||||
if err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner); err != nil {
|
||||
return fmt.Errorf("mark send started: %w", err)
|
||||
decided = &result
|
||||
}
|
||||
return nil
|
||||
})
|
||||
@@ -375,6 +385,64 @@ func (sender *ServiceMailSender) beforeSend(ctx context.Context, claim claimedSe
|
||||
return decided, nil
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) handleInvalidClaim(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
claim claimedSend,
|
||||
delivery domain.Delivery,
|
||||
state domain.ServiceMailState,
|
||||
now time.Time,
|
||||
) (inbound.MailPassResult, bool, error) {
|
||||
reason := delivery.CheckServiceMail(state, now)
|
||||
if reason == "" {
|
||||
return inbound.MailPassResult{}, false, nil
|
||||
}
|
||||
if delivery.Status() == domain.DeliveryStatusUnknown {
|
||||
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
|
||||
return inbound.MailPassResult{}, true, err
|
||||
}
|
||||
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
|
||||
return stopped.result, true, err
|
||||
}
|
||||
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
|
||||
return inbound.MailPassResult{}, true, fmt.Errorf("give the reservation back: %w", err)
|
||||
}
|
||||
cancelled, err := sender.cancel(ctx, unit, delivery, now, reason)
|
||||
return cancelled.result, true, err
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) handleUnmarkedSend(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
claim claimedSend,
|
||||
delivery domain.Delivery,
|
||||
now time.Time,
|
||||
) (inbound.MailPassResult, error) {
|
||||
if delivery.Status() == domain.DeliveryStatusUnknown {
|
||||
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
|
||||
return inbound.MailPassResult{}, err
|
||||
}
|
||||
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
|
||||
return stopped.result, err
|
||||
}
|
||||
if claim.sendStartUnsettled {
|
||||
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
|
||||
return inDoubt.result, err
|
||||
}
|
||||
if claim.requireDedupWindow && claim.firstSendStarted {
|
||||
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
|
||||
return inbound.MailPassResult{}, err
|
||||
}
|
||||
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
|
||||
return stopped.result, err
|
||||
}
|
||||
if claim.firstSendStarted {
|
||||
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
|
||||
return inDoubt.result, err
|
||||
}
|
||||
return resultOf(inbound.MailPassLeaseLost, delivery), nil
|
||||
}
|
||||
|
||||
// errNotSent stands for "the message did not leave the process" when a
|
||||
// reservation is given back before the transport was called.
|
||||
var errNotSent = errors.New("message was not sent")
|
||||
@@ -401,9 +469,17 @@ func (sender *ServiceMailSender) prepare(ctx context.Context, unit outbound.Unit
|
||||
}
|
||||
delivery = rebound
|
||||
}
|
||||
if sender.abandonedBeyondDeduplication(claimed) {
|
||||
if claimed.ManualRetryCycleStarted && claimed.SendStartUnsettled {
|
||||
// A manually authorized send started but its result was not recorded.
|
||||
// Do not spend that authorization on another provider call.
|
||||
return sender.recordInDoubt(ctx, unit, delivery, now)
|
||||
}
|
||||
if sender.retryBeyondDeduplication(claimed) {
|
||||
if claimed.SendStartUnsettled {
|
||||
return sender.recordInDoubt(ctx, unit, delivery, now)
|
||||
}
|
||||
return sender.stopAutomaticRetry(ctx, unit, delivery, now)
|
||||
}
|
||||
state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID())
|
||||
if err != nil {
|
||||
return claimedSend{}, fmt.Errorf("read token and account: %w", err)
|
||||
@@ -416,9 +492,39 @@ func (sender *ServiceMailSender) prepare(ctx context.Context, unit outbound.Unit
|
||||
return claimedSend{}, fmt.Errorf("prepare send: %w", err)
|
||||
}
|
||||
if !decision.Proceed() {
|
||||
return sender.waitForQuota(ctx, unit, delivery, decision, now)
|
||||
}
|
||||
return claimedSend{
|
||||
delivery: decision.Delivery,
|
||||
permit: decision.Permit,
|
||||
firstSendStarted: claimed.FirstSendStarted,
|
||||
sinceFirstSend: claimed.SinceFirstSend,
|
||||
manualRetryPending: claimed.ManualRetryPending,
|
||||
manualRetryCycleStarted: claimed.ManualRetryCycleStarted,
|
||||
sendStartUnsettled: claimed.SendStartUnsettled,
|
||||
requireDedupWindow: sender.requiresDedupWindow(claimed),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) waitForQuota(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
delivery domain.Delivery,
|
||||
decision SendDecision,
|
||||
now time.Time,
|
||||
) (claimedSend, error) {
|
||||
if delivery.Status() != domain.DeliveryStatusUnknown || decision.ResetAt.IsZero() {
|
||||
return claimedSend{decided: true, result: resultOf(inbound.MailPassWaitingQuota, decision.Delivery)}, nil
|
||||
}
|
||||
return claimedSend{delivery: decision.Delivery, permit: decision.Permit}, nil
|
||||
at := latest(now, delivery.UpdatedAt())
|
||||
deferred, err := delivery.ScheduleUnknownRetry(at, latest(decision.ResetAt, at))
|
||||
if err != nil {
|
||||
return claimedSend{}, fmt.Errorf("schedule uncertain quota retry: %w", err)
|
||||
}
|
||||
if err := unit.Deliveries().ScheduleUnknownRetry(ctx, sender.owner, deferred); err != nil {
|
||||
return claimedSend{}, fmt.Errorf("store uncertain quota retry: %w", err)
|
||||
}
|
||||
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, deferred)}, nil
|
||||
}
|
||||
|
||||
// abandonedBeyondDeduplication reports a delivery whose earlier sender let its
|
||||
@@ -430,15 +536,31 @@ func (sender *ServiceMailSender) prepare(ctx context.Context, unit outbound.Unit
|
||||
// less a safety margin. A transport without provider-side deduplication
|
||||
// (window zero) never repeats a request that may have been sent. A lease
|
||||
// that never reached the request leaves nothing in doubt.
|
||||
func (sender *ServiceMailSender) abandonedBeyondDeduplication(claimed outbound.ClaimedDelivery) bool {
|
||||
if claimed.PreviousClaimedUntil.IsZero() || !claimed.FirstSendStarted {
|
||||
return false
|
||||
}
|
||||
window := sender.gate.IdempotencyWindow()
|
||||
if window <= 0 {
|
||||
func (sender *ServiceMailSender) requiresDedupWindow(claimed outbound.ClaimedDelivery) bool {
|
||||
if claimed.SendStartUnsettled {
|
||||
return true
|
||||
}
|
||||
return claimed.SinceFirstSend >= max(window-dedupSafetyMargin, 0)
|
||||
if claimed.ManualRetryPending {
|
||||
return false
|
||||
}
|
||||
if claimed.Delivery.Status() == domain.DeliveryStatusUnknown {
|
||||
return true
|
||||
}
|
||||
return claimed.HasUncertainAttempt && !claimed.ManualRetryCycleStarted
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) retryBeyondDeduplication(claimed outbound.ClaimedDelivery) bool {
|
||||
if !sender.requiresDedupWindow(claimed) {
|
||||
return false
|
||||
}
|
||||
if !claimed.FirstSendStarted {
|
||||
return true
|
||||
}
|
||||
return claimed.SinceFirstSend >= sender.safeRetryWindow()
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) safeRetryWindow() time.Duration {
|
||||
return max(sender.gate.IdempotencyWindow()-dedupSafetyMargin, 0)
|
||||
}
|
||||
|
||||
// recordInDoubt records the lost attempt as unknown, without a next attempt,
|
||||
@@ -460,6 +582,35 @@ func (sender *ServiceMailSender) recordInDoubt(ctx context.Context, unit outboun
|
||||
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) stopAutomaticRetry(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
delivery domain.Delivery,
|
||||
now time.Time,
|
||||
) (claimedSend, error) {
|
||||
next, err := delivery.StopAutomaticRetry(latest(now, delivery.UpdatedAt()))
|
||||
if err != nil {
|
||||
return claimedSend{}, fmt.Errorf("stop automatic retry: %w", err)
|
||||
}
|
||||
if err := unit.Deliveries().StopUnknownRetry(ctx, sender.owner, next); err != nil {
|
||||
return claimedSend{}, fmt.Errorf("store stopped retry: %w", err)
|
||||
}
|
||||
sender.logger.WarnContext(ctx, "automatic retries stopped before the provider deduplication cutoff; the delivery remains unknown for an operator decision",
|
||||
slog.String("delivery_id", delivery.ID().String()),
|
||||
slog.String("kind", string(delivery.Kind())))
|
||||
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) releaseUnsentReservation(ctx context.Context, unit outbound.UnitOfWork, claim claimedSend) error {
|
||||
if claim.permit.IsZero() || claim.permit.Reused() {
|
||||
return nil
|
||||
}
|
||||
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
|
||||
return fmt.Errorf("release unused reservation: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sender *ServiceMailSender) cancel(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
@@ -572,7 +723,8 @@ func (sender *ServiceMailSender) applyResult(
|
||||
return sender.applyNotSent(ctx, unit, claim, now, sendErr)
|
||||
}
|
||||
at := latest(now, delivery.UpdatedAt())
|
||||
next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until))
|
||||
manualRetry := claim.manualRetryPending || claim.manualRetryCycleStarted
|
||||
next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until, manualRetry))
|
||||
if err != nil {
|
||||
return inbound.MailPassResult{}, fmt.Errorf("record attempt: %w", err)
|
||||
}
|
||||
@@ -588,7 +740,7 @@ func (sender *ServiceMailSender) applyResult(
|
||||
// attemptInput maps a transport answer to the attempt the delivery records.
|
||||
// until is the quota reset that SettleSend returned for a provider quota
|
||||
// refusal.
|
||||
func (sender *ServiceMailSender) attemptInput(delivery domain.Delivery, result outbound.SendResult, at, until time.Time) domain.DeliveryAttemptInput {
|
||||
func (sender *ServiceMailSender) attemptInput(delivery domain.Delivery, result outbound.SendResult, at, until time.Time, manualRetry bool) domain.DeliveryAttemptInput {
|
||||
input := domain.DeliveryAttemptInput{
|
||||
At: at,
|
||||
Outcome: domain.DeliveryAttemptOutcome(result.Outcome),
|
||||
@@ -608,6 +760,8 @@ func (sender *ServiceMailSender) attemptInput(delivery domain.Delivery, result o
|
||||
// Zero means that the reset is unknown, and the delivery waits for an
|
||||
// operator.
|
||||
input.NextAttemptAt = latest(until, at)
|
||||
case result.Outcome == outbound.MailOutcomeUnknown && !manualRetry && sender.gate.IdempotencyWindow() > 0:
|
||||
input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter)
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
@@ -36,8 +36,12 @@ type leasedRow struct {
|
||||
attempts []domain.DeliveryAttempt
|
||||
// firstSend is when the first request started, by the fake clock; zero
|
||||
// when none did. failures counts failures of the worker on the row.
|
||||
firstSend time.Time
|
||||
failures int32
|
||||
firstSend time.Time
|
||||
manualRetryAuthorizedAt time.Time
|
||||
manualRetryStartedAt time.Time
|
||||
sendStartedAttemptCount int32
|
||||
hasSendStarted bool
|
||||
failures int32
|
||||
// seq is the insertion order, so the fake claims in a stable order like
|
||||
// the store, which orders by the due time and then by identifier.
|
||||
seq int
|
||||
@@ -60,8 +64,18 @@ type memoryDeliveries struct {
|
||||
brokenDecode uuid.UUID
|
||||
// stateErr makes the token and account read fail; stateSeq, when set,
|
||||
// answers successive reads with successive states.
|
||||
stateErr error
|
||||
stateSeq []domain.ServiceMailState
|
||||
stateErr error
|
||||
stateSeq []domain.ServiceMailState
|
||||
retryDecisions []memoryRetryDecision
|
||||
}
|
||||
|
||||
type memoryRetryDecision struct {
|
||||
deliveryID uuid.UUID
|
||||
attemptCount int32
|
||||
actor string
|
||||
duplicateRiskAcknowledged bool
|
||||
previousLeaseExpired bool
|
||||
decidedAt time.Time
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) Get(_ context.Context, id uuid.UUID) (domain.Delivery, error) {
|
||||
@@ -88,7 +102,7 @@ func (store *memoryDeliveries) ClaimDue(_ context.Context, claim outbound.Delive
|
||||
due := !delivery.NextAttemptAt().IsZero() && !delivery.NextAttemptAt().After(claim.Now)
|
||||
pinned := delivery.ProviderAccount() == claim.Account ||
|
||||
(delivery.ProviderAccount().Provider() == claim.RebindProvider && delivery.AttemptCount() == 0)
|
||||
waiting := delivery.Status() == domain.DeliveryStatusPending || delivery.Status() == domain.DeliveryStatusWaitingQuota
|
||||
waiting := delivery.Status() == domain.DeliveryStatusPending || delivery.Status() == domain.DeliveryStatusWaitingQuota || delivery.Status() == domain.DeliveryStatusUnknown
|
||||
free := row.owner == uuid.Nil || !row.until.After(claim.Now)
|
||||
if !due || !pinned || !waiting || !free || !containsKind(claim.Kinds, delivery.Kind()) {
|
||||
continue
|
||||
@@ -109,7 +123,17 @@ func (store *memoryDeliveries) ClaimDue(_ context.Context, claim outbound.Delive
|
||||
return outbound.ClaimedDelivery{}, &outbound.UnreadableDeliveryError{DeliveryID: delivery.ID(), Cancelled: true, Err: domain.ErrMailContentIntegrity}
|
||||
}
|
||||
row.owner, row.until = claim.Owner, claim.Now.Add(claim.Lease)
|
||||
claimed := outbound.ClaimedDelivery{Delivery: delivery, PreviousClaimedUntil: previous, FailureCount: row.failures}
|
||||
claimed := outbound.ClaimedDelivery{
|
||||
Delivery: delivery,
|
||||
PreviousClaimedUntil: previous,
|
||||
ManualRetryPending: !row.manualRetryAuthorizedAt.IsZero() && row.manualRetryStartedAt.IsZero(),
|
||||
ManualRetryCycleStarted: !row.manualRetryStartedAt.IsZero(),
|
||||
SendStartUnsettled: row.hasSendStarted && row.sendStartedAttemptCount == delivery.AttemptCount(),
|
||||
HasUncertainAttempt: slices.ContainsFunc(row.attempts, func(attempt domain.DeliveryAttempt) bool {
|
||||
return attempt.Outcome == domain.DeliveryOutcomeUnknown
|
||||
}),
|
||||
FailureCount: row.failures,
|
||||
}
|
||||
if !row.firstSend.IsZero() {
|
||||
claimed.FirstSendStarted, claimed.SinceFirstSend = true, claim.Now.Sub(row.firstSend)
|
||||
}
|
||||
@@ -127,6 +151,76 @@ func containsKind(kinds []domain.MailKind, kind domain.MailKind) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) GetRetrySnapshot(_ context.Context, id uuid.UUID) (outbound.DeliveryRetrySnapshot, error) {
|
||||
row := store.rows[id]
|
||||
if row == nil {
|
||||
return outbound.DeliveryRetrySnapshot{}, outbound.ErrDeliveryNotFound
|
||||
}
|
||||
return outbound.DeliveryRetrySnapshot{
|
||||
ID: id,
|
||||
Provider: row.delivery.ProviderAccount().Provider(),
|
||||
ProviderAccount: row.delivery.ProviderAccount().Account(),
|
||||
Status: row.delivery.Status(),
|
||||
AttemptCount: row.delivery.AttemptCount(),
|
||||
NextAttemptAt: row.delivery.NextAttemptAt(),
|
||||
FirstSendStartedAt: row.firstSend,
|
||||
ManualRetryStartedAt: row.manualRetryStartedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) AuthorizeUnknownRetry(
|
||||
_ context.Context,
|
||||
id uuid.UUID,
|
||||
account domain.MailProviderAccount,
|
||||
actor domain.MailRetryActor,
|
||||
acknowledgeDuplicateRisk bool,
|
||||
at time.Time,
|
||||
minimumAge time.Duration,
|
||||
) error {
|
||||
row := store.rows[id]
|
||||
if row == nil || account != row.delivery.ProviderAccount() || row.delivery.Status() != domain.DeliveryStatusUnknown ||
|
||||
!row.delivery.NextAttemptAt().IsZero() || row.delivery.AttemptCount() == 0 || actor == "" ||
|
||||
!acknowledgeDuplicateRisk || minimumAge < 0 ||
|
||||
(row.owner != uuid.Nil && row.until.After(store.now())) {
|
||||
return outbound.ErrDeliveryRetryNotAllowed
|
||||
}
|
||||
started := row.firstSend
|
||||
if started.IsZero() || at.Sub(started) < minimumAge {
|
||||
return outbound.ErrDeliveryRetryNotAllowed
|
||||
}
|
||||
previousLeaseExpired := row.owner != uuid.Nil
|
||||
if !row.manualRetryStartedAt.IsZero() && row.hasSendStarted && row.sendStartedAttemptCount == row.delivery.AttemptCount() {
|
||||
lostAttemptAt := latest(at, latest(row.delivery.UpdatedAt(), row.delivery.LastAttemptAt()))
|
||||
lost, attempt, err := row.delivery.RecordAttempt(domain.DeliveryAttemptInput{
|
||||
At: lostAttemptAt,
|
||||
Outcome: domain.DeliveryOutcomeUnknown,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
row.delivery = lost
|
||||
row.attempts = append(row.attempts, attempt)
|
||||
}
|
||||
updatedAt := latest(at, row.delivery.UpdatedAt())
|
||||
next, err := restoreMemoryDelivery(row.delivery, updatedAt, updatedAt, row.delivery.Version()+1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
row.delivery = next
|
||||
row.manualRetryAuthorizedAt = at
|
||||
row.manualRetryStartedAt = time.Time{}
|
||||
row.owner, row.until = uuid.Nil, time.Time{}
|
||||
store.retryDecisions = append(store.retryDecisions, memoryRetryDecision{
|
||||
deliveryID: id,
|
||||
attemptCount: row.delivery.AttemptCount(),
|
||||
actor: string(actor),
|
||||
duplicateRiskAcknowledged: acknowledgeDuplicateRisk,
|
||||
previousLeaseExpired: previousLeaseExpired,
|
||||
decidedAt: at,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) ReleaseClaim(_ context.Context, id, owner uuid.UUID) (bool, error) {
|
||||
row := store.rows[id]
|
||||
if row == nil || row.owner != owner {
|
||||
@@ -162,6 +256,44 @@ func (store *memoryDeliveries) replace(next domain.Delivery, release bool) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func restoreMemoryDelivery(delivery domain.Delivery, nextAttemptAt, updatedAt time.Time, version int64) (domain.Delivery, error) {
|
||||
return domain.RestoreDelivery(domain.DeliverySnapshot{
|
||||
ID: delivery.ID(),
|
||||
SourceEventID: delivery.SourceEventID(),
|
||||
RecipientUserID: delivery.RecipientUserID(),
|
||||
RecipientAddress: delivery.Recipient().Address(),
|
||||
Content: delivery.Content(),
|
||||
ProviderAccount: delivery.ProviderAccount(),
|
||||
IdempotencyKey: delivery.IdempotencyKey(),
|
||||
Status: delivery.Status(),
|
||||
AttemptCount: delivery.AttemptCount(),
|
||||
NextAttemptAt: nextAttemptAt,
|
||||
LastAttemptAt: delivery.LastAttemptAt(),
|
||||
ProviderMessageID: delivery.ProviderMessageID(),
|
||||
EmailTokenID: delivery.EmailTokenID(),
|
||||
CancelReason: delivery.CancelReason(),
|
||||
Version: version,
|
||||
CreatedAt: delivery.CreatedAt(),
|
||||
UpdatedAt: updatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) StopUnknownRetry(_ context.Context, owner uuid.UUID, next domain.Delivery) error {
|
||||
row := store.rows[next.ID()]
|
||||
if row == nil || row.owner != owner || next.Status() != domain.DeliveryStatusUnknown || !next.NextAttemptAt().IsZero() {
|
||||
return outbound.ErrDeliveryVersionConflict
|
||||
}
|
||||
return store.replace(next, true)
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) ScheduleUnknownRetry(_ context.Context, owner uuid.UUID, next domain.Delivery) error {
|
||||
row := store.rows[next.ID()]
|
||||
if row == nil || row.owner != owner || next.Status() != domain.DeliveryStatusUnknown || next.NextAttemptAt().IsZero() {
|
||||
return outbound.ErrDeliveryVersionConflict
|
||||
}
|
||||
return store.replace(next, true)
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) RecordAttempt(_ context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error {
|
||||
if err := store.replace(next, true); err != nil {
|
||||
return err
|
||||
@@ -185,11 +317,31 @@ func (store *memoryDeliveries) LockClaimed(_ context.Context, id, owner uuid.UUI
|
||||
return row != nil && row.owner == owner, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) MarkSendStarted(_ context.Context, id, owner uuid.UUID) error {
|
||||
if row := store.rows[id]; row != nil && row.owner == owner && row.firstSend.IsZero() {
|
||||
func (store *memoryDeliveries) MarkSendStarted(_ context.Context, id, owner uuid.UUID, requireDedupWindow bool, safeWindow time.Duration) (bool, error) {
|
||||
row := store.rows[id]
|
||||
if row == nil || row.owner != owner {
|
||||
return false, nil
|
||||
}
|
||||
manualPending := !row.manualRetryAuthorizedAt.IsZero() && row.manualRetryStartedAt.IsZero()
|
||||
startedAt := row.firstSend
|
||||
if requireDedupWindow && !manualPending && !startedAt.IsZero() && store.now().Sub(startedAt) >= safeWindow {
|
||||
return false, nil
|
||||
}
|
||||
if row.firstSend.IsZero() {
|
||||
row.firstSend = store.now()
|
||||
}
|
||||
return nil
|
||||
row.sendStartedAttemptCount = row.delivery.AttemptCount()
|
||||
row.hasSendStarted = true
|
||||
if manualPending {
|
||||
row.manualRetryStartedAt = store.now()
|
||||
next, err := restoreMemoryDelivery(row.delivery, time.Time{}, row.delivery.UpdatedAt(), row.delivery.Version())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
row.delivery = next
|
||||
}
|
||||
row.failures = 0
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) RecordFailure(_ context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) {
|
||||
@@ -435,14 +587,14 @@ func TestServiceMailSenderMapsEveryTransportResultToTheDeliveryState(t *testing.
|
||||
wantOutcome: inbound.MailPassWaitingQuota, wantStatus: domain.DeliveryStatusWaitingQuota, wantAttempts: 1,
|
||||
},
|
||||
{
|
||||
name: "an uncertain answer is unknown, counted, and not retried",
|
||||
name: "an uncertain answer is unknown and retried within the provider window",
|
||||
result: outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"},
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1,
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantNext: start.Add(time.Minute), wantAttempts: 1, wantUsed: 1,
|
||||
},
|
||||
{
|
||||
name: "a transport that answers without an outcome is unknown, never not sent",
|
||||
name: "a transport that answers without an outcome is unknown and retried within the provider window",
|
||||
result: outbound.SendResult{},
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1,
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantNext: start.Add(time.Minute), wantAttempts: 1, wantUsed: 1,
|
||||
},
|
||||
{
|
||||
name: "no transport leaves the delivery as it was",
|
||||
@@ -490,6 +642,53 @@ func TestServiceMailSenderMapsEveryTransportResultToTheDeliveryState(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderKeepsEarlierUnknownVisibleAcrossConfirmedRefusal(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
age time.Duration
|
||||
wantOutcome inbound.MailPassOutcome
|
||||
wantStatus domain.DeliveryStatus
|
||||
wantCalls int
|
||||
}{
|
||||
{name: "before cutoff continues under the same key", age: 22 * time.Hour, wantOutcome: inbound.MailPassAccepted, wantStatus: domain.DeliveryStatusAccepted, wantCalls: 3},
|
||||
{name: "at cutoff stops without inventing an attempt", age: 23 * time.Hour, wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantCalls: 2},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("initial pass = %+v, want unknown", result)
|
||||
}
|
||||
|
||||
h.now = h.now.Add(time.Minute)
|
||||
h.transport.result = outbound.SendResult{
|
||||
Outcome: outbound.MailOutcomeRejected,
|
||||
Rejection: outbound.MailRejectionRateLimited,
|
||||
RetryAfter: time.Minute,
|
||||
}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassRetry {
|
||||
t.Fatalf("confirmed 429 pass = %+v, want retry", result)
|
||||
}
|
||||
row := h.stored()
|
||||
if row.delivery.Status() != domain.DeliveryStatusPending || len(row.attempts) != 2 ||
|
||||
row.attempts[0].Outcome != domain.DeliveryOutcomeUnknown || row.attempts[1].Rejection != domain.DeliveryRejectionRateLimited {
|
||||
t.Fatalf("delivery = %s with attempts %+v, want pending after unknown then confirmed 429", row.delivery.Status(), row.attempts)
|
||||
}
|
||||
|
||||
h.now = row.firstSend.Add(test.age)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
result := h.pass(t)
|
||||
if result.Outcome != test.wantOutcome || row.delivery.Status() != test.wantStatus || len(h.transport.mails) != test.wantCalls {
|
||||
t.Fatalf("pass = %+v, delivery %s, provider calls %d; want %s and %d calls", result, row.delivery.Status(), len(h.transport.mails), test.wantOutcome, test.wantCalls)
|
||||
}
|
||||
if test.wantStatus == domain.DeliveryStatusUnknown &&
|
||||
(len(row.attempts) != 2 || !row.delivery.NextAttemptAt().IsZero()) {
|
||||
t.Fatalf("cutoff stop added an attempt or remained due: %s, due %s, attempts %+v", row.delivery.Status(), row.delivery.NextAttemptAt(), row.attempts)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderCancelsBeforeTheTransportWhenTheMailIsNoLongerValid(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
change func(*domain.ServiceMailState, time.Time)
|
||||
|
||||
Reference in new issue
Block a user