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

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

No files matched your search

@@ -0,0 +1,196 @@
// Package mailretry implements the local operator command for inspecting and
// authorizing a retry of an unknown mail delivery.
package mailretry
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strings"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
)
const usage = "usage: mail-retry inspect --delivery <uuid> | mail-retry retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk"
type action uint8
const (
inspectAction action = iota + 1
retryAction
)
// Command is a parsed, validated local mail retry command.
type Command struct {
Action action
DeliveryID uuid.UUID
Actor string
AcknowledgeDuplicateRisk bool
}
// Operator is the metadata-only and audit-backed retry usecase.
type Operator interface {
Inspect(ctx context.Context, deliveryID uuid.UUID) (notification.DeliveryRetryInspection, error)
RetryUnknown(ctx context.Context, deliveryID uuid.UUID, actor string, acknowledgeDuplicateRisk bool) (string, error)
}
// Parse validates every argument before Run reads configuration or connects
// to PostgreSQL.
func Parse(args []string) (Command, error) {
if len(args) == 0 {
return Command{}, errors.New(usage)
}
var command Command
var actor *string
var acknowledge *bool
switch args[0] {
case "inspect":
command.Action = inspectAction
case "retry":
command.Action = retryAction
default:
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("mail-retry "+args[0], flag.ContinueOnError)
flags.SetOutput(io.Discard)
deliveryID := flags.String("delivery", "", "delivery UUID")
if command.Action == retryAction {
actor = flags.String("actor", "", "operator handle")
acknowledge = flags.Bool("acknowledge-duplicate-risk", false, "acknowledge that a duplicate may be sent")
}
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
return Command{}, errors.New(usage)
}
parsedID, err := uuid.Parse(strings.TrimSpace(*deliveryID))
if err != nil || parsedID == uuid.Nil {
return Command{}, errors.New("delivery must be a non-zero UUID")
}
command.DeliveryID = parsedID
if command.Action == retryAction {
if _, err := domain.ParseMailRetryActor(strings.TrimSpace(*actor)); err != nil {
return Command{}, errors.New("actor must be operator:<handle>")
}
if !*acknowledge {
return Command{}, errors.New("--acknowledge-duplicate-risk is required")
}
command.Actor = strings.TrimSpace(*actor)
command.AcknowledgeDuplicateRisk = true
}
return command, nil
}
// Run parses the command, loads only its database and mail-account settings
// from the supplied environment, then executes the operator usecase. It does
// not load dotenv files or read transport credentials.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil {
return errors.New("mail retry command dependencies are required")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return errors.New("DATABASE_URL is not set")
}
provider := strings.ToLower(strings.TrimSpace(envValue(lookup, "EMAIL_PROVIDER", "")))
if provider != string(config.EmailProviderResend) {
return errors.New("mail retry is available only with EMAIL_PROVIDER=resend in this build")
}
accountLabel := strings.TrimSpace(envValue(lookup, "EMAIL_ACCOUNT", "default"))
account, err := domain.NewMailProviderAccount(provider, accountLabel)
if err != nil {
return errors.New("mail provider account configuration is invalid")
}
pool, err := postgres.NewPool(ctx, databaseURL)
if err != nil {
return errors.New("database configuration is invalid")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("database is unavailable")
}
deliveries := postgres.NewDeliveryStore(pool).Deliveries()
operator, err := notification.NewDeliveryRetryOperator(
postgres.NewTransactor(pool),
deliveries,
account,
resend.IdempotencyWindow,
time.Now,
)
if err != nil {
return errors.New("mail retry is unavailable")
}
return Execute(ctx, command, operator, output)
}
// Execute prints the duplicate-risk warning before retry authorization can
// mutate the delivery or append an audit decision.
func Execute(ctx context.Context, command Command, operator Operator, output io.Writer) error {
if operator == nil || output == nil {
return errors.New("mail retry command dependencies are required")
}
snapshot, err := operator.Inspect(ctx, command.DeliveryID)
if err != nil {
return safeOperationError(err)
}
if command.Action == inspectAction {
if _, err := fmt.Fprintf(output,
"delivery: %s\nprovider: %s\nstatus: %s\nattempts: %d\n%s\n",
snapshot.DeliveryID, snapshot.Provider, snapshot.Status, snapshot.AttemptCount, notification.DuplicateRiskWarning,
); err != nil {
return errors.New("could not write mail retry inspection")
}
return nil
}
if command.Action != retryAction || !command.AcknowledgeDuplicateRisk {
return errors.New(usage)
}
if _, err := fmt.Fprintln(output, notification.DuplicateRiskWarning); err != nil {
return errors.New("could not write duplicate-risk warning")
}
if _, err := operator.RetryUnknown(ctx, command.DeliveryID, command.Actor, command.AcknowledgeDuplicateRisk); err != nil {
return safeOperationError(err)
}
if _, err := fmt.Fprintln(output, "retry scheduled; audit decision recorded"); err != nil {
return errors.New("retry was scheduled, but the result could not be written")
}
return nil
}
func envValue(lookup config.LookupEnv, name, fallback string) string {
value, ok := lookup(name)
if !ok || strings.TrimSpace(value) == "" {
return fallback
}
return value
}
func safeOperationError(err error) error {
switch {
case errors.Is(err, outbound.ErrDeliveryNotFound):
return errors.New("delivery not found")
case errors.Is(err, outbound.ErrDeliveryRetryNotAllowed):
return errors.New("delivery is not eligible for manual retry")
case errors.Is(err, notification.ErrDuplicateRiskAcknowledgementRequired):
return errors.New("duplicate-risk acknowledgement is required")
case errors.Is(err, domain.ErrInvalidDelivery):
return errors.New("delivery or actor is invalid")
default:
return errors.New("mail retry operation failed")
}
}
@@ -0,0 +1,142 @@
package mailretry
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
)
const testDeliveryID = "2e203b62-3fb5-4ef7-b118-360bbff7f2aa"
func TestParseRequiresExplicitCommandFields(t *testing.T) {
tests := []struct {
name string
args []string
want string
}{
{name: "command", args: nil, want: "usage:"},
{name: "unknown command", args: []string{"send"}, want: "usage:"},
{name: "inspect delivery", args: []string{"inspect"}, want: "non-zero UUID"},
{name: "invalid delivery", args: []string{"inspect", "--delivery", "not-a-uuid"}, want: "non-zero UUID"},
{name: "retry delivery", args: []string{"retry", "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk"}, want: "non-zero UUID"},
{name: "retry actor", args: []string{"retry", "--delivery", testDeliveryID, "--acknowledge-duplicate-risk"}, want: "actor must be"},
{name: "retry acknowledgement", args: []string{"retry", "--delivery", testDeliveryID, "--actor", "operator:mail-ops"}, want: "--acknowledge-duplicate-risk is required"},
{name: "invalid actor", args: []string{"retry", "--delivery", testDeliveryID, "--actor", "mail-ops", "--acknowledge-duplicate-risk"}, want: "actor must be"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := Parse(test.args)
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("Parse(%q) error = %v, want text %q", test.args, err, test.want)
}
})
}
}
func TestRunValidatesArgumentsBeforeReadingEnvironment(t *testing.T) {
var reads int
err := Run(context.Background(), []string{"retry", "--delivery", testDeliveryID, "--actor", "operator:mail-ops"}, func(string) (string, bool) {
reads++
return "", false
}, &bytes.Buffer{})
if err == nil || reads != 0 {
t.Fatalf("Run() error = %v, environment reads = %d; want argument error before config access", err, reads)
}
}
func TestRunDoesNotPrintDatabaseURL(t *testing.T) {
const secretURL = "postgres://operator:secret-password@127.0.0.1:1/mail"
lookup := func(key string) (string, bool) {
switch key {
case "DATABASE_URL":
return secretURL, true
case "EMAIL_PROVIDER":
return "resend", true
default:
return "", false
}
}
var output bytes.Buffer
err := Run(context.Background(), []string{"inspect", "--delivery", testDeliveryID}, lookup, &output)
if err == nil || strings.Contains(err.Error(), "secret-password") || strings.Contains(output.String(), "secret-password") {
t.Fatalf("Run() error/output leaked connection details: error %v, output %q", err, output.String())
}
}
func TestExecuteWarnsBeforeSchedulingAndRedactsMetadata(t *testing.T) {
deliveryID := uuid.MustParse(testDeliveryID)
var output bytes.Buffer
operator := &testOperator{
inspection: notification.DeliveryRetryInspection{
DeliveryID: deliveryID,
Provider: "resend",
ProviderAccount: "sensitive-account-label",
Status: domain.DeliveryStatusUnknown,
AttemptCount: 2,
},
output: &output,
}
command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true}
if err := Execute(context.Background(), command, operator, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if !operator.retryCalled || !strings.Contains(output.String(), notification.DuplicateRiskWarning) ||
strings.Contains(output.String(), "sensitive-account-label") {
t.Fatalf("Execute() output/calls = %q, %t; want warning before retry and redacted account", output.String(), operator.retryCalled)
}
}
func TestExecuteDoesNotScheduleWhenWarningCannotBeWritten(t *testing.T) {
deliveryID := uuid.MustParse(testDeliveryID)
operator := &testOperator{inspection: notification.DeliveryRetryInspection{DeliveryID: deliveryID, Status: domain.DeliveryStatusUnknown}}
command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true}
if err := Execute(context.Background(), command, operator, errorWriter{}); err == nil || operator.retryCalled {
t.Fatalf("Execute() error = %v, retry called = %t; want output error before mutation", err, operator.retryCalled)
}
}
func TestExecuteReturnsSafeStateError(t *testing.T) {
deliveryID := uuid.MustParse(testDeliveryID)
operator := &testOperator{
inspection: notification.DeliveryRetryInspection{DeliveryID: deliveryID, Status: domain.DeliveryStatusUnknown},
retryErr: errors.Join(outbound.ErrDeliveryRetryNotAllowed, errors.New("recipient private@example.invalid")),
}
var output bytes.Buffer
command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true}
err := Execute(context.Background(), command, operator, &output)
if err == nil || err.Error() != "delivery is not eligible for manual retry" || strings.Contains(err.Error(), "private@example.invalid") {
t.Fatalf("Execute() error = %v; want a safe state error", err)
}
}
type testOperator struct {
inspection notification.DeliveryRetryInspection
inspectErr error
retryErr error
output *bytes.Buffer
retryCalled bool
}
func (operator *testOperator) Inspect(context.Context, uuid.UUID) (notification.DeliveryRetryInspection, error) {
return operator.inspection, operator.inspectErr
}
func (operator *testOperator) RetryUnknown(context.Context, uuid.UUID, string, bool) (string, error) {
operator.retryCalled = true
if operator.output != nil && !strings.Contains(operator.output.String(), notification.DuplicateRiskWarning) {
return "", errors.New("retry called before warning")
}
return "", operator.retryErr
}
type errorWriter struct{}
func (errorWriter) Write([]byte) (int, error) { return 0, errors.New("output unavailable") }