diff --git a/.env.example b/.env.example index c0cdf6d..34904f9 100644 --- a/.env.example +++ b/.env.example @@ -19,6 +19,27 @@ SEAWEEDFS_BUCKET=lincodex # before the first start; changing it later stops Kafka from using the existing volume. KAFKA_CLUSTER_ID=SJv4PXUUSJGbK3eSPC57qA +# Mail. EMAIL_PROVIDER is required and selects exactly one transport: +# resend, smtp, or disabled. The working stand uses resend; this build has no +# Resend or SMTP transport yet, so both fail startup after their settings are +# validated. disabled sends nothing and reports the mail channel as +# unavailable; it never confirms an address or skips an account check. +EMAIL_PROVIDER=disabled +EMAIL_FROM=no-reply@example.com +EMAIL_TIMEOUT=10s +# Public origin for links in mail: https, or http only for a loopback host. +APP_PUBLIC_URL=http://localhost:8080 +# Read only when EMAIL_PROVIDER=resend. Keep the real key in the server +# environment only. +RESEND_API_KEY= +# Read only when EMAIL_PROVIDER=smtp. SMTP_TLS_MODE is starttls or tls; +# plaintext SMTP is not supported. +SMTP_HOST= +SMTP_PORT= +SMTP_USERNAME= +SMTP_PASSWORD= +SMTP_TLS_MODE= + # Optional PostgreSQL metrics login, created when the database volume is initialized. POSTGRES_EXPORTER_USER=metrics_reader POSTGRES_EXPORTER_PASSWORD=replace-this-metrics-password diff --git a/backend/config/config.go b/backend/config/config.go index d27bd55..3230330 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -41,9 +41,24 @@ type Config struct { SeaweedFSRegion string SeaweedFSTimeout time.Duration KafkaBrokers []string - LogLevel string - ReadinessTimeout time.Duration - ShutdownTimeout time.Duration + // EmailProvider selects the only active mail transport. Settings of the + // other transports are not loaded. + EmailProvider EmailProvider + // EmailFrom is the sender mailbox for every outgoing message. + EmailFrom string + EmailTimeout time.Duration + // AppPublicURL is the public origin without a trailing slash, for links + // in mail. + AppPublicURL string + ResendAPIKey string + SMTPHost string + SMTPPort int + SMTPUsername string + SMTPPassword string + SMTPTLSMode SMTPTLSMode + LogLevel string + ReadinessTimeout time.Duration + ShutdownTimeout time.Duration } type LookupEnv func(string) (string, bool) @@ -75,6 +90,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { if err := config.loadRedis(lookup); err != nil { return Config{}, err } + if err := config.loadMail(lookup); err != nil { + return Config{}, err + } var err error config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart) @@ -113,6 +131,9 @@ func (config Config) Validate() error { if err := config.ValidateKafka(); err != nil { return err } + if err := config.ValidateMail(); err != nil { + return err + } if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil { return err } diff --git a/backend/config/config_test.go b/backend/config/config_test.go index 6542b62..ec179cb 100644 --- a/backend/config/config_test.go +++ b/backend/config/config_test.go @@ -118,10 +118,21 @@ func testEnvironment(values map[string]string) LookupEnv { if key == "SEAWEEDFS_SECRET_KEY" { return "test-secret", true } + if value, ok := mailFixture[key]; ok { + return value, true + } return "", false } } +// mailFixture is the smallest valid mail configuration. Mail tests override +// or remove entries to cover each transport. +var mailFixture = map[string]string{ + "EMAIL_PROVIDER": "disabled", + "EMAIL_FROM": "Lincodex ", + "APP_PUBLIC_URL": "http://localhost:8080", +} + func TestLoadFromEnvSeaweedFS(t *testing.T) { settings, err := LoadFromEnv(testEnvironment(nil)) if err != nil { diff --git a/backend/config/mail.go b/backend/config/mail.go new file mode 100644 index 0000000..cb753e4 --- /dev/null +++ b/backend/config/mail.go @@ -0,0 +1,240 @@ +package config + +import ( + "errors" + "fmt" + "net" + "net/mail" + "net/url" + "strconv" + "strings" + "time" + + "lincodex/backend/internal/domain" +) + +// EmailProvider selects exactly one mail transport. There is no implicit +// fallback between transports. +type EmailProvider string + +const ( + EmailProviderResend EmailProvider = "resend" + EmailProviderSMTP EmailProvider = "smtp" + EmailProviderDisabled EmailProvider = "disabled" +) + +// SMTPTLSMode selects how the SMTP transport protects the connection. +// Plaintext SMTP is not supported. +type SMTPTLSMode string + +const ( + // SMTPTLSModeStartTLS upgrades the connection with STARTTLS and fails + // when the server does not offer it (submission, usually port 587). + SMTPTLSModeStartTLS SMTPTLSMode = "starttls" + // SMTPTLSModeImplicit opens TLS before the SMTP dialog (usually port 465). + SMTPTLSModeImplicit SMTPTLSMode = "tls" +) + +const ( + defaultEmailTimeout = 10 * time.Second + // One attempt waits at least long enough for a TLS handshake and an API + // answer, and at most one minute so that a hung provider cannot hold a + // delivery worker indefinitely. + minEmailTimeout = time.Second + maxEmailTimeout = time.Minute +) + +// loadMail reads the common mail settings and only the settings of the +// selected transport, so settings of an inactive transport, including its +// secrets, never reach Config. +// +// EMAIL_PROVIDER has no default. The working stand uses resend, but a default +// would either pick a transport that this build may not provide or silently +// turn mail off; an explicit choice makes both visible at deployment time. +func (config *Config) loadMail(lookup LookupEnv) error { + provider := strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "EMAIL_PROVIDER", ""))) + config.EmailProvider = EmailProvider(provider) + config.EmailFrom = strings.TrimSpace(valueOrDefault(lookup, "EMAIL_FROM", "")) + // One trailing slash is accepted and dropped so that the stored value is + // an origin that links can be appended to. + config.AppPublicURL = strings.TrimSuffix(strings.TrimSpace(valueOrDefault(lookup, "APP_PUBLIC_URL", "")), "/") + + var err error + config.EmailTimeout, err = durationOrDefault(lookup, "EMAIL_TIMEOUT", defaultEmailTimeout) + if err != nil { + return err + } + + switch config.EmailProvider { + case EmailProviderResend: + config.ResendAPIKey = valueOrDefault(lookup, "RESEND_API_KEY", "") + case EmailProviderSMTP: + return config.loadSMTP(lookup) + case EmailProviderDisabled: + // No transport settings are read. + } + return nil +} + +func (config *Config) loadSMTP(lookup LookupEnv) error { + config.SMTPHost = strings.TrimSpace(valueOrDefault(lookup, "SMTP_HOST", "")) + config.SMTPUsername = strings.TrimSpace(valueOrDefault(lookup, "SMTP_USERNAME", "")) + config.SMTPPassword = valueOrDefault(lookup, "SMTP_PASSWORD", "") + config.SMTPTLSMode = SMTPTLSMode(strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "SMTP_TLS_MODE", "")))) + + // An unset or empty port stays zero, which validation reports as missing. + port := strings.TrimSpace(valueOrDefault(lookup, "SMTP_PORT", "")) + if port == "" { + return nil + } + number, err := strconv.Atoi(port) + if err != nil { + return fmt.Errorf("Config.loadSMTP - SMTP_PORT must be an integer between 1 and %d", maxPortNumber) + } + config.SMTPPort = number + return nil +} + +// ValidateMail checks the common mail settings and the selected transport. +// Errors name the setting and never include secret values. +func (config Config) ValidateMail() error { + // The value is not echoed: a misplaced secret must not reach the logs. + switch config.EmailProvider { + case EmailProviderResend, EmailProviderSMTP, EmailProviderDisabled: + case "": + return errors.New("Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled") + default: + return errors.New("Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled") + } + if err := validateEmailFrom(config.EmailFrom); err != nil { + return err + } + if err := validateAppPublicURL(config.AppPublicURL); err != nil { + return err + } + if config.EmailTimeout < minEmailTimeout || config.EmailTimeout > maxEmailTimeout { + return fmt.Errorf("Config.ValidateMail - EMAIL_TIMEOUT must be between %s and %s", minEmailTimeout, maxEmailTimeout) + } + + switch config.EmailProvider { + case EmailProviderResend: + return validateResendAPIKey(config.ResendAPIKey) + case EmailProviderSMTP: + return config.validateSMTP() + case EmailProviderDisabled: + } + return nil +} + +// validateEmailFrom accepts one RFC 5322 mailbox, with or without a display +// name. The address itself follows the account address rules of +// domain.NewEmailAddress: ASCII only, because the mailer does not support +// SMTPUTF8, an unquoted local part, and a DNS domain with at least two labels. +func validateEmailFrom(raw string) error { + if raw == "" { + return errors.New("config.validateEmailFrom - EMAIL_FROM must be set") + } + // Control characters such as CR and LF could inject header lines. + if !isPrintableASCII(raw) { + return errors.New("config.validateEmailFrom - EMAIL_FROM must contain printable ASCII characters only") + } + mailbox, err := mail.ParseAddress(raw) + if err != nil { + return errors.New("config.validateEmailFrom - EMAIL_FROM must be one mailbox such as Lincodex ") + } + if _, err := domain.NewEmailAddress(mailbox.Address); err != nil { + return errors.New("config.validateEmailFrom - EMAIL_FROM address must be an ASCII addr-spec with a DNS domain of at least two labels") + } + return nil +} + +// validateAppPublicURL accepts the public origin that links in mail point +// to. Plain HTTP is accepted only for a loopback host in local runs. +func validateAppPublicURL(raw string) error { + if raw == "" { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be set") + } + origin, err := url.Parse(raw) + if err != nil || origin.Hostname() == "" || !validHostOrIP(origin.Hostname()) { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL with a valid host") + } + switch { + case origin.Scheme == "https": + case origin.Scheme == "http" && isLoopbackHost(origin.Hostname()): + default: + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must use https; http is allowed only for localhost, 127.0.0.1, or [::1]") + } + + if !isBareOrigin(origin, raw) { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be an origin without credentials, a path, query, or fragment") + } + if !validEndpointPort(origin) { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port") + } + return nil +} + +// isBareOrigin reports a URL with nothing after the authority. raw is checked +// for "#" because url.Parse drops an empty fragment. +func isBareOrigin(origin *url.URL, raw string) bool { + hasCredentials := origin.User != nil + hasPath := origin.Path != "" || origin.RawPath != "" + hasQuery := origin.RawQuery != "" || origin.ForceQuery + hasFragment := origin.Fragment != "" || strings.Contains(raw, "#") + return !hasCredentials && !hasPath && !hasQuery && !hasFragment +} + +// validateResendAPIKey checks only what the Authorization header needs. Resend +// shows keys as "re_..." in examples but does not document a stable format, +// so the prefix is not enforced; the provider itself rejects a wrong key. +func validateResendAPIKey(key string) error { + if key == "" { + return errors.New("config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend") + } + if !isPrintableASCII(key) || strings.Contains(key, " ") { + return errors.New("config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace or non-ASCII characters") + } + return nil +} + +func (config Config) validateSMTP() error { + if config.SMTPHost == "" { + return errors.New("Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp") + } + if !validHostOrIP(config.SMTPHost) { + return errors.New("Config.validateSMTP - SMTP_HOST must be a hostname or IP address without a port") + } + if config.SMTPPort < 1 || config.SMTPPort > maxPortNumber { + return fmt.Errorf("Config.validateSMTP - SMTP_PORT must be set to a port between 1 and %d when EMAIL_PROVIDER is smtp", maxPortNumber) + } + // An anonymous relay is not supported: both credentials are required. + if config.SMTPUsername == "" { + return errors.New("Config.validateSMTP - SMTP_USERNAME must be set when EMAIL_PROVIDER is smtp") + } + if config.SMTPPassword == "" { + return errors.New("Config.validateSMTP - SMTP_PASSWORD must be set when EMAIL_PROVIDER is smtp") + } + switch config.SMTPTLSMode { + case SMTPTLSModeStartTLS, SMTPTLSModeImplicit: + return nil + default: + return errors.New("Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls; plaintext SMTP is not supported") + } +} + +func validHostOrIP(host string) bool { + return net.ParseIP(host) != nil || validHostname(host) +} + +func isLoopbackHost(host string) bool { + return strings.EqualFold(host, "localhost") || host == "127.0.0.1" || host == "::1" +} + +func isPrintableASCII(value string) bool { + for index := range len(value) { + if value[index] < ' ' || value[index] > '~' { + return false + } + } + return true +} diff --git a/backend/config/mail_test.go b/backend/config/mail_test.go new file mode 100644 index 0000000..ed5fb4f --- /dev/null +++ b/backend/config/mail_test.go @@ -0,0 +1,206 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +const ( + testResendAPIKey = "re_test-key-value" + testSMTPPassword = "smtp password value" + secretMarker = "hidden-secret-marker" + testSMTPHost = "smtp.example.com" + testPublicOrigin = "https://lincodex.example" + testSenderMailbox = "Lincodex " +) + +// mailEnvironment overrides mail settings on top of the shared test +// environment and removes the keys named in unset. +func mailEnvironment(values map[string]string, unset ...string) LookupEnv { + base := testEnvironment(values) + return func(key string) (string, bool) { + for _, removed := range unset { + if key == removed { + return "", false + } + } + return base(key) + } +} + +func smtpValues(overrides map[string]string) map[string]string { + values := map[string]string{ + "EMAIL_PROVIDER": "smtp", + "SMTP_HOST": testSMTPHost, + "SMTP_PORT": "587", + "SMTP_USERNAME": "mailer", + "SMTP_PASSWORD": testSMTPPassword, + "SMTP_TLS_MODE": "starttls", + } + for key, value := range overrides { + values[key] = value + } + return values +} + +func TestLoadFromEnvMailDisabledIgnoresTransportSettings(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(map[string]string{ + "EMAIL_PROVIDER": " Disabled ", + "EMAIL_FROM": " " + testSenderMailbox + " ", + "APP_PUBLIC_URL": testPublicOrigin + "/", + "RESEND_API_KEY": testResendAPIKey, + "SMTP_HOST": testSMTPHost, + "SMTP_PORT": "not-a-port", + "SMTP_PASSWORD": testSMTPPassword, + "SMTP_TLS_MODE": "plaintext", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.EmailProvider != EmailProviderDisabled { + t.Fatalf("EmailProvider = %q, want disabled", settings.EmailProvider) + } + if settings.EmailFrom != testSenderMailbox || settings.AppPublicURL != testPublicOrigin { + t.Fatalf("EmailFrom = %q, AppPublicURL = %q", settings.EmailFrom, settings.AppPublicURL) + } + if settings.EmailTimeout != 10*time.Second { + t.Fatalf("EmailTimeout = %s, want the 10s default", settings.EmailTimeout) + } + if settings.ResendAPIKey != "" || settings.SMTPHost != "" || settings.SMTPPort != 0 || settings.SMTPPassword != "" || settings.SMTPTLSMode != "" { + t.Fatal("settings of an inactive transport were loaded") + } +} + +func TestLoadFromEnvMailResendLoadsOnlyResendSettings(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(map[string]string{ + "EMAIL_PROVIDER": "RESEND", + "EMAIL_TIMEOUT": "15s", + "RESEND_API_KEY": testResendAPIKey, + "SMTP_HOST": testSMTPHost, + "SMTP_PASSWORD": testSMTPPassword, + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.EmailProvider != EmailProviderResend || settings.ResendAPIKey != testResendAPIKey || settings.EmailTimeout != 15*time.Second { + t.Fatalf("Resend settings were not loaded: provider=%q timeout=%s", settings.EmailProvider, settings.EmailTimeout) + } + if settings.SMTPHost != "" || settings.SMTPPassword != "" { + t.Fatal("SMTP settings were loaded for EMAIL_PROVIDER=resend") + } +} + +func TestLoadFromEnvMailSMTPLoadsOnlySMTPSettings(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(smtpValues(map[string]string{ + "SMTP_PORT": " 465 ", + "SMTP_TLS_MODE": " TLS ", + "RESEND_API_KEY": testResendAPIKey, + }))) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.SMTPHost != testSMTPHost || settings.SMTPPort != 465 || settings.SMTPUsername != "mailer" || settings.SMTPPassword != testSMTPPassword || settings.SMTPTLSMode != SMTPTLSModeImplicit { + t.Fatal("SMTP settings were not loaded") + } + if settings.ResendAPIKey != "" { + t.Fatal("RESEND_API_KEY was loaded for EMAIL_PROVIDER=smtp") + } +} + +func TestLoadFromEnvAcceptsMailBoundaries(t *testing.T) { + tests := []struct { + name string + values map[string]string + }{ + {name: "bare sender address", values: map[string]string{"EMAIL_FROM": "no-reply@example.com"}}, + {name: "quoted display name", values: map[string]string{"EMAIL_FROM": `"Lincodex Team" `}}, + {name: "punycode sender domain", values: map[string]string{"EMAIL_FROM": "no-reply@xn--e1afmkfd.xn--p1ai"}}, + {name: "minimum timeout", values: map[string]string{"EMAIL_TIMEOUT": "1s"}}, + {name: "maximum timeout", values: map[string]string{"EMAIL_TIMEOUT": "60s"}}, + {name: "HTTPS origin with port", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:8443"}}, + {name: "HTTP loopback IPv4", values: map[string]string{"APP_PUBLIC_URL": "http://127.0.0.1:8080"}}, + {name: "HTTP loopback IPv6", values: map[string]string{"APP_PUBLIC_URL": "http://[::1]:8080/"}}, + {name: "SMTP over STARTTLS", values: smtpValues(map[string]string{"SMTP_TLS_MODE": "STARTTLS"})}, + {name: "SMTP host as IP address", values: smtpValues(map[string]string{"SMTP_HOST": "10.0.0.25"})}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if _, err := LoadFromEnv(mailEnvironment(test.values)); err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + }) + } +} + +func TestLoadFromEnvRejectsMailSettings(t *testing.T) { + resend := func(key string) map[string]string { + return map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": key} + } + tests := []struct { + name string + values map[string]string + unset []string + want string + }{ + {name: "provider unset", unset: []string{"EMAIL_PROVIDER"}, want: "Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled"}, + {name: "provider empty", values: map[string]string{"EMAIL_PROVIDER": " "}, want: "Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled"}, + {name: "unknown provider", values: map[string]string{"EMAIL_PROVIDER": "sendgrid"}, want: "Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled"}, + {name: "secret pasted as provider", values: map[string]string{"EMAIL_PROVIDER": secretMarker}, want: "Config.ValidateMail - EMAIL_PROVIDER must be one of"}, + {name: "sender unset", unset: []string{"EMAIL_FROM"}, want: "config.validateEmailFrom - EMAIL_FROM must be set"}, + {name: "sender empty", values: map[string]string{"EMAIL_FROM": " "}, want: "config.validateEmailFrom - EMAIL_FROM must be set"}, + {name: "sender without domain", values: map[string]string{"EMAIL_FROM": "no-reply"}, want: "config.validateEmailFrom - EMAIL_FROM must be one mailbox"}, + {name: "sender list", values: map[string]string{"EMAIL_FROM": "a@example.com, b@example.com"}, want: "config.validateEmailFrom - EMAIL_FROM must be one mailbox"}, + {name: "sender header injection", values: map[string]string{"EMAIL_FROM": "a@example.com\r\nBcc: b@example.com"}, want: "config.validateEmailFrom - EMAIL_FROM must contain printable ASCII"}, + {name: "sender non-ASCII name", values: map[string]string{"EMAIL_FROM": "Линкодекс "}, want: "config.validateEmailFrom - EMAIL_FROM must contain printable ASCII"}, + {name: "sender single-label domain", values: map[string]string{"EMAIL_FROM": "no-reply@localhost"}, want: "config.validateEmailFrom - EMAIL_FROM address must be"}, + {name: "sender IP literal", values: map[string]string{"EMAIL_FROM": "no-reply@[127.0.0.1]"}, want: "config.validateEmailFrom - EMAIL_FROM address must be"}, + {name: "sender quoted local part", values: map[string]string{"EMAIL_FROM": `"no reply"@example.com`}, want: "config.validateEmailFrom - EMAIL_FROM address must be"}, + {name: "timeout unparsable", values: map[string]string{"EMAIL_TIMEOUT": "soon"}, want: "config.durationOrDefault - parse EMAIL_TIMEOUT"}, + {name: "timeout empty", values: map[string]string{"EMAIL_TIMEOUT": ""}, want: "config.durationOrDefault - parse EMAIL_TIMEOUT"}, + {name: "timeout zero", values: map[string]string{"EMAIL_TIMEOUT": "0s"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between 1s and 1m0s"}, + {name: "timeout too short", values: map[string]string{"EMAIL_TIMEOUT": "500ms"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between"}, + {name: "timeout too long", values: map[string]string{"EMAIL_TIMEOUT": "61s"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between"}, + {name: "public URL unset", unset: []string{"APP_PUBLIC_URL"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be set"}, + {name: "public URL without scheme", values: map[string]string{"APP_PUBLIC_URL": "lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL"}, + {name: "public URL with space", values: map[string]string{"APP_PUBLIC_URL": "https://linco dex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL"}, + {name: "public URL other scheme", values: map[string]string{"APP_PUBLIC_URL": "ftp://lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https"}, + {name: "public URL plain HTTP", values: map[string]string{"APP_PUBLIC_URL": "http://lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https"}, + {name: "public URL loopback lookalike", values: map[string]string{"APP_PUBLIC_URL": "http://localhost.lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https"}, + {name: "public URL credentials", values: map[string]string{"APP_PUBLIC_URL": "https://user:" + secretMarker + "@lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL path", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example/app"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL double slash", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example//"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL query", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example?token=" + secretMarker}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL fragment", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example#top"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL empty fragment", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example#"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL zero port", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:0"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port"}, + {name: "public URL port out of range", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:70000"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port"}, + {name: "Resend key unset", values: map[string]string{"EMAIL_PROVIDER": "resend"}, want: "config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend"}, + {name: "Resend key empty", values: resend(""), want: "config.validateResendAPIKey - RESEND_API_KEY must be set"}, + {name: "Resend key with space", values: resend("re_" + secretMarker + " x"), want: "config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace"}, + {name: "Resend key with newline", values: resend("re_" + secretMarker + "\n"), want: "config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace"}, + {name: "SMTP host unset", values: smtpValues(nil), unset: []string{"SMTP_HOST"}, want: "Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp"}, + {name: "SMTP host with port", values: smtpValues(map[string]string{"SMTP_HOST": "smtp.example.com:587"}), want: "Config.validateSMTP - SMTP_HOST must be a hostname or IP address"}, + {name: "SMTP port unset", values: smtpValues(nil), unset: []string{"SMTP_PORT"}, want: "Config.validateSMTP - SMTP_PORT must be set to a port between 1 and 65535"}, + {name: "SMTP port not a number", values: smtpValues(map[string]string{"SMTP_PORT": "submission"}), want: "Config.loadSMTP - SMTP_PORT must be an integer"}, + {name: "SMTP port zero", values: smtpValues(map[string]string{"SMTP_PORT": "0"}), want: "Config.validateSMTP - SMTP_PORT must be set to a port"}, + {name: "SMTP port out of range", values: smtpValues(map[string]string{"SMTP_PORT": "70000"}), want: "Config.validateSMTP - SMTP_PORT must be set to a port"}, + {name: "SMTP username unset", values: smtpValues(nil), unset: []string{"SMTP_USERNAME"}, want: "Config.validateSMTP - SMTP_USERNAME must be set when EMAIL_PROVIDER is smtp"}, + {name: "SMTP password unset", values: smtpValues(nil), unset: []string{"SMTP_PASSWORD"}, want: "Config.validateSMTP - SMTP_PASSWORD must be set when EMAIL_PROVIDER is smtp"}, + {name: "SMTP TLS mode unset", values: smtpValues(nil), unset: []string{"SMTP_TLS_MODE"}, want: "Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls"}, + {name: "SMTP plaintext", values: smtpValues(map[string]string{"SMTP_TLS_MODE": "none"}), want: "Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls; plaintext SMTP is not supported"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := LoadFromEnv(mailEnvironment(test.values, test.unset...)) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want) + } + for _, secret := range []string{secretMarker, testResendAPIKey, testSMTPPassword} { + if strings.Contains(err.Error(), secret) { + t.Fatalf("configuration error discloses a configured value: %v", err) + } + } + }) + } +} diff --git a/backend/integration_test/bootstrap_test.go b/backend/integration_test/bootstrap_test.go index a3becac..006250c 100644 --- a/backend/integration_test/bootstrap_test.go +++ b/backend/integration_test/bootstrap_test.go @@ -86,6 +86,10 @@ func bootstrap(t *testing.T, services ...service) *testEnvironment { "SEAWEEDFS_SECRET_KEY": seaweedfsSecretKey, "SEAWEEDFS_BUCKET": seaweedfsBucket, "SEAWEEDFS_TIMEOUT": storageTimeout.String(), + // Integration tests send no mail; disabled is the explicit choice. + "EMAIL_PROVIDER": "disabled", + "EMAIL_FROM": "no-reply@example.com", + "APP_PUBLIC_URL": "http://localhost:8080", } settings, err := config.LoadFromEnv(func(key string) (string, bool) { value, ok := fixtures[key] diff --git a/backend/internal/adapter/secondary/mail/.gitkeep b/backend/internal/adapter/secondary/mail/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/backend/internal/adapter/secondary/mail/disabled/sender.go b/backend/internal/adapter/secondary/mail/disabled/sender.go new file mode 100644 index 0000000..97b5787 --- /dev/null +++ b/backend/internal/adapter/secondary/mail/disabled/sender.go @@ -0,0 +1,30 @@ +// Package disabled provides the mail transport for EMAIL_PROVIDER=disabled. +package disabled + +import ( + "context" + "fmt" + + "lincodex/backend/internal/port/outbound" +) + +// Sender sends nothing. Every valid message is reported as +// outbound.ErrMailChannelUnavailable, never as an accepted or delivered +// message, so a caller cannot mistake the disabled mode for a delivery. +type Sender struct{} + +var _ outbound.MailSender = (*Sender)(nil) + +func NewSender() *Sender { + return &Sender{} +} + +// Send validates the message first so that local runs without a transport +// still expose invalid messages, then reports the channel as unavailable. It +// logs nothing and keeps no copy of the recipient or the content. +func (sender *Sender) Send(_ context.Context, mail outbound.OutgoingMail) (outbound.SendResult, error) { + if err := mail.Validate(); err != nil { + return outbound.SendResult{}, fmt.Errorf("Sender.Send - validate mail: %w", err) + } + return outbound.SendResult{}, fmt.Errorf("Sender.Send - EMAIL_PROVIDER is disabled: %w", outbound.ErrMailChannelUnavailable) +} diff --git a/backend/internal/adapter/secondary/mail/disabled/sender_test.go b/backend/internal/adapter/secondary/mail/disabled/sender_test.go new file mode 100644 index 0000000..f9d6ece --- /dev/null +++ b/backend/internal/adapter/secondary/mail/disabled/sender_test.go @@ -0,0 +1,57 @@ +package disabled_test + +import ( + "context" + "errors" + "strings" + "testing" + + "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const testRecipient = "candidate@example.com" + +func TestSenderReportsChannelUnavailableAndNeverAcceptance(t *testing.T) { + recipient, err := domain.NewEmailAddress(testRecipient) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + mail := outbound.OutgoingMail{ + To: recipient, + Subject: "Confirm your address", + TextBody: "verification link with raw-token-value", + IdempotencyKey: "email_verification/1", + } + canceled, cancel := context.WithCancel(context.Background()) + cancel() + + for name, ctx := range map[string]context.Context{"active context": context.Background(), "canceled context": canceled} { + t.Run(name, func(t *testing.T) { + result, err := disabled.NewSender().Send(ctx, mail) + if !errors.Is(err, outbound.ErrMailChannelUnavailable) { + t.Fatalf("Send() error = %v, want ErrMailChannelUnavailable", err) + } + // Delivery and email verification code reads Outcome and + // ProviderMessageID; neither may suggest that a provider took the + // message. + if result != (outbound.SendResult{}) || result.Outcome == outbound.MailOutcomeAccepted || result.ProviderMessageID != "" { + t.Fatalf("Send() result = %+v, want the zero result", result) + } + if strings.Contains(err.Error(), testRecipient) || strings.Contains(err.Error(), "raw-token-value") { + t.Fatalf("Send() error exposes message content: %v", err) + } + }) + } +} + +func TestSenderRejectsInvalidMailBeforeReportingUnavailability(t *testing.T) { + result, err := disabled.NewSender().Send(context.Background(), outbound.OutgoingMail{}) + if !errors.Is(err, outbound.ErrInvalidOutgoingMail) || errors.Is(err, outbound.ErrMailChannelUnavailable) { + t.Fatalf("Send() error = %v, want only ErrInvalidOutgoingMail", err) + } + if result != (outbound.SendResult{}) { + t.Fatalf("Send() result = %+v, want the zero result", result) + } +} diff --git a/backend/internal/bootstrap/app.go b/backend/internal/bootstrap/app.go index 3356404..b44e44c 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -16,6 +16,7 @@ import ( "lincodex/backend/config" "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/port/outbound" ) const ( @@ -28,6 +29,9 @@ type Application struct { apiHandler http.Handler metrics *prometheus.Metrics logger *slog.Logger + // mailSender is the transport selected by EMAIL_PROVIDER. No usecase + // sends mail yet; the delivery layer will take it from here. + mailSender outbound.MailSender } func NewApplication( @@ -35,8 +39,9 @@ func NewApplication( apiHandler http.Handler, metrics *prometheus.Metrics, logger *slog.Logger, + mailSender outbound.MailSender, ) *Application { - return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger} + return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger, mailSender: mailSender} } func Run() (runErr error) { @@ -69,20 +74,35 @@ func Run() (runErr error) { } func run(ctx context.Context, config config.Config, logger *slog.Logger) error { - if err := config.Validate(); err != nil { - return fmt.Errorf("bootstrap.run - validate configuration: %w", err) - } - if err := migrateDatabase(ctx, config, logger); err != nil { - return fmt.Errorf("bootstrap.run - migrate database: %w", err) - } - application, cleanup, err := initialize(ctx, config, logger) + application, cleanup, err := start(ctx, config, logger) if err != nil { - return fmt.Errorf("bootstrap.run - initialize application: %w", err) + return err } defer cleanup() return application.run(ctx) } +// start prepares the application without opening listeners. The mail +// transport is selected before migrations, so a configuration that cannot +// start never changes the database. +func start(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) { + if err := config.Validate(); err != nil { + return nil, nil, fmt.Errorf("bootstrap.start - validate configuration: %w", err) + } + mailSender, err := newMailSender(config, logger) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.start - select mail transport: %w", err) + } + if err := migrateDatabase(ctx, config, logger); err != nil { + return nil, nil, fmt.Errorf("bootstrap.start - migrate database: %w", err) + } + application, cleanup, err := initialize(ctx, config, logger, mailSender) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err) + } + return application, cleanup, nil +} + func logLevel(value string) logkit.Level { switch value { case "debug": diff --git a/backend/internal/bootstrap/mail.go b/backend/internal/bootstrap/mail.go new file mode 100644 index 0000000..83c6c92 --- /dev/null +++ b/backend/internal/bootstrap/mail.go @@ -0,0 +1,48 @@ +package bootstrap + +import ( + "errors" + "fmt" + "log/slog" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/port/outbound" +) + +// errMailTransportNotBuilt reports a valid EMAIL_PROVIDER whose transport has +// no adapter in this build yet. Startup fails instead of falling back to +// another transport. +var errMailTransportNotBuilt = errors.New("mail transport is not available in this build") + +// newMailSender binds the MailSender port to the one transport that +// EMAIL_PROVIDER selects. Each provider maps to exactly one constructor, and +// a failure never falls back to another transport. A transport task replaces +// the errMailTransportNotBuilt return in its case with its constructor; until +// then resend and smtp fail startup after their settings are validated. +func newMailSender(settings config.Config, logger *slog.Logger) (outbound.MailSender, error) { + if err := settings.ValidateMail(); err != nil { + return nil, fmt.Errorf("bootstrap.newMailSender - validate mail settings: %w", err) + } + + var sender outbound.MailSender + switch settings.EmailProvider { + case config.EmailProviderDisabled: + sender = disabled.NewSender() + case config.EmailProviderResend: + return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=resend: %w", errMailTransportNotBuilt) + case config.EmailProviderSMTP: + return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=smtp: %w", errMailTransportNotBuilt) + default: + // ValidateMail rejects unknown providers; this guards a new constant + // that has no case here yet. + return nil, errors.New("bootstrap.newMailSender - EMAIL_PROVIDER has no transport") + } + + // Only the provider name is logged, never the sender, keys, or hosts. + logger.Info("mail transport selected", slog.String("email_provider", string(settings.EmailProvider))) + if settings.EmailProvider == config.EmailProviderDisabled { + logger.Warn("mail delivery is disabled; every send is reported as channel unavailable and nothing is sent") + } + return sender, nil +} diff --git a/backend/internal/bootstrap/mail_test.go b/backend/internal/bootstrap/mail_test.go new file mode 100644 index 0000000..a7f1ce6 --- /dev/null +++ b/backend/internal/bootstrap/mail_test.go @@ -0,0 +1,186 @@ +package bootstrap + +import ( + "bytes" + "errors" + "log/slog" + "strings" + "testing" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + testSenderAddress = "no-reply@example.com" + testResendAPIKey = "re_bootstrap-test-key" + testSMTPPassword = "bootstrap-smtp-password" + // unreachableDatabaseURL fails as soon as migrations try to use it, so a + // startup error that is not a migration error proves that the mail + // transport was selected before the database was touched. + unreachableDatabaseURL = "postgres://app:db-password@db:not-a-port/app" +) + +// loadMailConfig loads the full process configuration with the given mail +// settings, as Run does from the environment. +func loadMailConfig(t *testing.T, mail map[string]string) config.Config { + t.Helper() + values := map[string]string{ + "SEAWEEDFS_ACCESS_KEY": "test-access", + "SEAWEEDFS_SECRET_KEY": "test-secret", + "EMAIL_FROM": "Lincodex <" + testSenderAddress + ">", + "APP_PUBLIC_URL": "http://localhost:8080", + // Settings of every transport are present so that each case also + // shows that only the selected transport's settings are used. + "RESEND_API_KEY": testResendAPIKey, + "SMTP_HOST": "smtp.example.com", + "SMTP_PORT": "587", + "SMTP_USERNAME": "mailer", + "SMTP_PASSWORD": testSMTPPassword, + "SMTP_TLS_MODE": "starttls", + } + for key, value := range mail { + values[key] = value + } + settings, err := config.LoadFromEnv(func(key string) (string, bool) { + value, ok := values[key] + return value, ok + }) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + return settings +} + +func captureLogs() (*slog.Logger, *bytes.Buffer) { + var logs bytes.Buffer + return slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})), &logs +} + +func assertNoMailSecrets(t *testing.T, output string) { + t.Helper() + for _, secret := range []string{testSenderAddress, testResendAPIKey, testSMTPPassword, "smtp.example.com", "db-password"} { + if strings.Contains(output, secret) { + t.Fatalf("startup output exposes a mail setting: %s", output) + } + } +} + +func TestStartWithDisabledMailSelectsTheDisabledTransport(t *testing.T) { + settings := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "disabled"}) + logger, logs := captureLogs() + + application, cleanup, err := start(t.Context(), settings, logger) + if err != nil { + t.Fatalf("start() error = %v", err) + } + t.Cleanup(cleanup) + + if _, ok := application.mailSender.(*disabled.Sender); !ok { + t.Fatalf("mail sender = %T, want *disabled.Sender", application.mailSender) + } + recipient, err := domain.NewEmailAddress("candidate@example.com") + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + result, err := application.mailSender.Send(t.Context(), outbound.OutgoingMail{ + To: recipient, + Subject: "Confirm your address", + TextBody: "Confirm your address", + IdempotencyKey: "email_verification/harness", + }) + if !errors.Is(err, outbound.ErrMailChannelUnavailable) { + t.Fatalf("Send() error = %v, want ErrMailChannelUnavailable", err) + } + if result.Outcome == outbound.MailOutcomeAccepted || result.ProviderMessageID != "" { + t.Fatalf("Send() result = %+v, disabled mode must never report acceptance", result) + } + + output := logs.String() + if !strings.Contains(output, `msg="mail transport selected" email_provider=disabled`) { + t.Fatalf("startup did not log the selected provider: %s", output) + } + if !strings.Contains(output, "level=WARN msg=\"mail delivery is disabled") { + t.Fatalf("startup did not warn that mail is disabled: %s", output) + } + assertNoMailSecrets(t, output) +} + +func TestStartRejectsTransportsThatThisBuildDoesNotProvide(t *testing.T) { + tests := []struct { + provider string + want string + }{ + {provider: "resend", want: "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=resend: mail transport is not available in this build"}, + {provider: "smtp", want: "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=smtp: mail transport is not available in this build"}, + } + for _, test := range tests { + t.Run(test.provider, func(t *testing.T) { + settings := loadMailConfig(t, map[string]string{ + "EMAIL_PROVIDER": test.provider, + "DATABASE_URL": unreachableDatabaseURL, + }) + logger, logs := captureLogs() + + application, cleanup, err := start(t.Context(), settings, logger) + if err == nil { + cleanup() + t.Fatalf("start() = %v, want a startup error", application) + } + if err.Error() != test.want || !errors.Is(err, errMailTransportNotBuilt) { + t.Fatalf("start() error = %q, want %q", err, test.want) + } + if strings.Contains(logs.String(), "mail transport selected") { + t.Fatalf("startup logged a selected transport after failing: %s", logs.String()) + } + assertNoMailSecrets(t, err.Error()+logs.String()) + }) + } +} + +func TestStartRejectsInvalidMailSettingsBeforeMigrations(t *testing.T) { + valid := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "disabled", "DATABASE_URL": unreachableDatabaseURL}) + tests := []struct { + name string + change func(*config.Config) + want string + }{ + {name: "unknown provider", change: func(settings *config.Config) { settings.EmailProvider = "sendgrid" }, want: "Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled"}, + {name: "missing provider", change: func(settings *config.Config) { settings.EmailProvider = "" }, want: "Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled"}, + {name: "missing sender", change: func(settings *config.Config) { settings.EmailFrom = "" }, want: "config.validateEmailFrom - EMAIL_FROM must be set"}, + {name: "plain HTTP public URL", change: func(settings *config.Config) { settings.AppPublicURL = "http://lincodex.example" }, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https; http is allowed only for localhost, 127.0.0.1, or [::1]"}, + {name: "timeout out of range", change: func(settings *config.Config) { settings.EmailTimeout = 0 }, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between 1s and 1m0s"}, + {name: "Resend without key", change: func(settings *config.Config) { settings.EmailProvider = config.EmailProviderResend }, want: "config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend"}, + {name: "SMTP without settings", change: func(settings *config.Config) { settings.EmailProvider = config.EmailProviderSMTP }, want: "Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + settings := valid + test.change(&settings) + logger, logs := captureLogs() + + _, _, err := start(t.Context(), settings, logger) + want := "bootstrap.start - validate configuration: " + test.want + if err == nil || err.Error() != want { + t.Fatalf("start() error = %v, want %q", err, want) + } + assertNoMailSecrets(t, err.Error()+logs.String()) + }) + } +} + +func TestNewMailSenderValidatesSettingsItself(t *testing.T) { + settings := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "disabled"}) + settings.EmailFrom = "not a mailbox" + logger, logs := captureLogs() + + sender, err := newMailSender(settings, logger) + if sender != nil || err == nil || !strings.HasPrefix(err.Error(), "bootstrap.newMailSender - validate mail settings: config.validateEmailFrom - ") { + t.Fatalf("newMailSender() = (%v, %v), want a validation error", sender, err) + } + if logs.Len() != 0 { + t.Fatalf("newMailSender() logged a selection for invalid settings: %s", logs.String()) + } +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 9efc53b..4f3e4aa 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -19,10 +19,18 @@ import ( redisadapter "lincodex/backend/internal/adapter/secondary/redis" "lincodex/backend/internal/adapter/secondary/seaweedfs" "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/health" ) -func initialize(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) { +// initialize receives the mail sender that start selected, so an unusable +// EMAIL_PROVIDER fails before any dependency is created. +func initialize( + ctx context.Context, + config config.Config, + logger *slog.Logger, + mailSender outbound.MailSender, +) (*Application, func(), error) { wire.Build( wire.NewSet( postgres.NewHealthChecker, diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index 5957f04..ae487f1 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -17,13 +17,16 @@ import ( "lincodex/backend/internal/adapter/secondary/redis" "lincodex/backend/internal/adapter/secondary/seaweedfs" "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/health" "log/slog" ) // Injectors from wire.go: -func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger) (*Application, func(), error) { +// initialize receives the mail sender that start selected, so an unusable +// EMAIL_PROVIDER fails before any dependency is created. +func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, mailSender outbound.MailSender) (*Application, func(), error) { healthChecker, cleanup, err := postgres.NewHealthChecker(ctx, config2) if err != nil { return nil, nil, err @@ -52,7 +55,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger) cleanup() return nil, nil, err } - application := NewApplication(config2, httpHandler, metrics, logger) + application := NewApplication(config2, httpHandler, metrics, logger, mailSender) return application, func() { cleanup3() cleanup2() diff --git a/backend/internal/port/outbound/mail.go b/backend/internal/port/outbound/mail.go new file mode 100644 index 0000000..4815430 --- /dev/null +++ b/backend/internal/port/outbound/mail.go @@ -0,0 +1,181 @@ +package outbound + +import ( + "context" + "errors" + "fmt" + "log/slog" + "strings" + "time" + + "lincodex/backend/internal/domain" +) + +const ( + // maxMailIdempotencyKeyLength follows the Resend Idempotency-Key limit of + // 256 characters; SMTP has no such key, so the strictest provider rule + // applies. + maxMailIdempotencyKeyLength = 256 + redactedOutgoingMail = "[redacted outgoing mail]" +) + +var ( + // ErrMailChannelUnavailable reports that no mail transport is active + // (EMAIL_PROVIDER=disabled). Nothing was sent and nothing was handed to a + // provider. Callers must record the message as not sent; it is never a + // delivery, and it never confirms an email address or satisfies an + // account check. + ErrMailChannelUnavailable = errors.New("mail channel unavailable") + + // ErrInvalidOutgoingMail reports a message that fails + // OutgoingMail.Validate. It is a caller bug, not a provider rejection, and + // nothing was sent. + ErrInvalidOutgoingMail = errors.New("invalid outgoing mail") +) + +// MailOutcome is what one transport attempt established about a message. The +// zero value is not an outcome and must never be read as acceptance. +type MailOutcome string + +const ( + // MailOutcomeAccepted means the provider accepted the request and returned + // a message ID. It does not mean the message was delivered or read. + MailOutcomeAccepted MailOutcome = "accepted" + + // MailOutcomeRejected means the provider answered and refused the + // request; it did not take the message. Rejection says why. + MailOutcomeRejected MailOutcome = "rejected" + + // MailOutcomeUnknown means the request may have reached the provider but + // no conclusive answer came back, for example a timeout or a connection + // lost after the request was written. The message may or may not have + // been accepted (delivery_uncertain). It is not a failure: a retry must + // reuse the same IdempotencyKey so a provider that supports keys can + // deduplicate it. + MailOutcomeUnknown MailOutcome = "unknown" +) + +// MailRejection is a provider-independent reason for MailOutcomeRejected that +// the delivery layer can map to its retry policy. It never carries provider +// text, recipients, or message content. +type MailRejection string + +const ( + // MailRejectionPermanent means the provider will not accept this message, + // for example an unverified sender domain or a suppressed recipient. + MailRejectionPermanent MailRejection = "permanent" + + // MailRejectionInvalidRequest means the provider rejected the request + // shape or credentials; retrying the same request cannot help. + MailRejectionInvalidRequest MailRejection = "invalid_request" + + // MailRejectionRateLimited means a short-term rate limit; RetryAfter may + // say when to try again. + MailRejectionRateLimited MailRejection = "rate_limited" + + // MailRejectionQuotaExhausted means a daily or monthly sending quota is + // used up; retrying before the quota resets cannot help. + MailRejectionQuotaExhausted MailRejection = "quota_exhausted" + + // MailRejectionTemporary means a transient provider-side refusal, such as + // a 5xx answer or an SMTP 4xx reply, that a later attempt may overcome. + MailRejectionTemporary MailRejection = "temporary" +) + +// OutgoingMail is one rendered message. The sender address comes from the +// transport configuration (EMAIL_FROM), so usecases and templates never choose +// or depend on it, nor on the provider. +// +// String, GoString, Format, and LogValue redact the whole message, because the +// recipient and the bodies are personal data and a body can carry a +// verification link. Read the fields directly where they are needed. +type OutgoingMail struct { + To domain.EmailAddress + Subject string + TextBody string + HTMLBody string + + // IdempotencyKey is stable for one logical delivery across every retry, + // for example "email_verification/". A transport that supports + // provider-side deduplication sends it; others ignore it. It must not + // contain personal data. + IdempotencyKey string +} + +// Validate reports a message that no transport could send. Errors wrap +// ErrInvalidOutgoingMail and name only the field, never its value. +func (mail OutgoingMail) Validate() error { + if mail.To.IsZero() { + return invalidOutgoingMail("recipient must be set") + } + if strings.TrimSpace(mail.Subject) == "" { + return invalidOutgoingMail("subject must not be empty") + } + // A control character in the subject could inject header lines. + if strings.ContainsFunc(mail.Subject, isControlCharacter) { + return invalidOutgoingMail("subject must not contain control characters") + } + if strings.TrimSpace(mail.TextBody) == "" && strings.TrimSpace(mail.HTMLBody) == "" { + return invalidOutgoingMail("text or HTML body must not be empty") + } + if length := len(mail.IdempotencyKey); length == 0 || length > maxMailIdempotencyKeyLength { + return invalidOutgoingMail("idempotency key must have 1 to 256 characters") + } + for index := range len(mail.IdempotencyKey) { + if character := mail.IdempotencyKey[index]; character <= ' ' || character > '~' { + return invalidOutgoingMail("idempotency key must contain printable ASCII characters without spaces") + } + } + return nil +} + +func (mail OutgoingMail) String() string { return redactedOutgoingMail } + +func (mail OutgoingMail) GoString() string { return redactedOutgoingMail } + +// Format redacts every verb; without it %+v would print the fields. +func (mail OutgoingMail) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(redactedOutgoingMail)) +} + +func (mail OutgoingMail) LogValue() slog.Value { return slog.StringValue(redactedOutgoingMail) } + +func isControlCharacter(character rune) bool { + return character < ' ' || character == 0x7f +} + +func invalidOutgoingMail(reason string) error { + return fmt.Errorf("OutgoingMail.Validate - %s: %w", reason, ErrInvalidOutgoingMail) +} + +// SendResult is the outcome of one attempt that may have reached a provider. +type SendResult struct { + Outcome MailOutcome + + // ProviderMessageID is set only for MailOutcomeAccepted. + ProviderMessageID string + + // Rejection is set only for MailOutcomeRejected. + Rejection MailRejection + + // RetryAfter is the provider's requested wait for a rejected attempt, or + // zero when the provider gave none. + RetryAfter time.Duration +} + +// MailSender hands one message to the configured transport. +// +// Send makes exactly one attempt and never retries; retries, backoff, and +// deduplication belong to the delivery layer, which also records outcomes. +// A nil error comes with an Outcome of accepted, rejected, or unknown. A +// non-nil error means the message certainly did not leave the process: it +// wraps ErrMailChannelUnavailable when no transport is active, +// ErrInvalidOutgoingMail for an invalid message, or the context error when +// ctx ended before the request was sent. The returned SendResult is then +// zero and must be ignored. +// +// Errors and logs never include recipients, subjects, bodies, credentials, or +// raw provider responses. +type MailSender interface { + Send(ctx context.Context, mail OutgoingMail) (SendResult, error) +} diff --git a/backend/internal/port/outbound/mail_test.go b/backend/internal/port/outbound/mail_test.go new file mode 100644 index 0000000..9145097 --- /dev/null +++ b/backend/internal/port/outbound/mail_test.go @@ -0,0 +1,98 @@ +package outbound_test + +import ( + "bytes" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + testRecipient = "Private.Person@example.com" + testSubject = "Confirm your address" + testTextBody = "Open https://lincodex.example/verify?token=raw-token-value" + testHTMLBody = "Confirm" +) + +func validOutgoingMail(t *testing.T) outbound.OutgoingMail { + t.Helper() + recipient, err := domain.NewEmailAddress(testRecipient) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + return outbound.OutgoingMail{ + To: recipient, + Subject: testSubject, + TextBody: testTextBody, + HTMLBody: testHTMLBody, + IdempotencyKey: "email_verification/0190d3f4-0000-7000-8000-000000000001", + } +} + +func TestOutgoingMailValidateAcceptsOneBody(t *testing.T) { + textOnly := validOutgoingMail(t) + textOnly.HTMLBody = "" + htmlOnly := validOutgoingMail(t) + htmlOnly.TextBody = "" + longestKey := validOutgoingMail(t) + longestKey.IdempotencyKey = strings.Repeat("k", 256) + for name, mail := range map[string]outbound.OutgoingMail{"text only": textOnly, "HTML only": htmlOnly, "256-character key": longestKey} { + t.Run(name, func(t *testing.T) { + if err := mail.Validate(); err != nil { + t.Fatalf("Validate() error = %v", err) + } + }) + } +} + +func TestOutgoingMailValidateRejectsUnsendableMail(t *testing.T) { + tests := []struct { + name string + change func(*outbound.OutgoingMail) + }{ + {name: "missing recipient", change: func(mail *outbound.OutgoingMail) { mail.To = domain.EmailAddress{} }}, + {name: "blank subject", change: func(mail *outbound.OutgoingMail) { mail.Subject = " " }}, + {name: "subject header injection", change: func(mail *outbound.OutgoingMail) { mail.Subject = testSubject + "\r\nBcc: other@example.com" }}, + {name: "no body", change: func(mail *outbound.OutgoingMail) { mail.TextBody, mail.HTMLBody = " ", "" }}, + {name: "missing idempotency key", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = "" }}, + {name: "idempotency key too long", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = strings.Repeat("k", 257) }}, + {name: "idempotency key with space", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = "email verification" }}, + {name: "idempotency key non-ASCII", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = "письмо/1" }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + mail := validOutgoingMail(t) + test.change(&mail) + err := mail.Validate() + if !errors.Is(err, outbound.ErrInvalidOutgoingMail) { + t.Fatalf("Validate() error = %v, want ErrInvalidOutgoingMail", err) + } + if !strings.HasPrefix(err.Error(), "OutgoingMail.Validate - ") { + t.Fatalf("Validate() error = %q, want the OutgoingMail.Validate location", err) + } + for _, private := range []string{testRecipient, testSubject, "raw-token-value", "other@example.com"} { + if strings.Contains(err.Error(), private) { + t.Fatalf("Validate() error exposes message content: %v", err) + } + } + }) + } +} + +func TestOutgoingMailIsRedacted(t *testing.T) { + mail := validOutgoingMail(t) + wrapper := struct{ Mail outbound.OutgoingMail }{Mail: mail} + var logs bytes.Buffer + slog.New(slog.NewJSONHandler(&logs, nil)).Info("redaction", "mail", mail, slog.Group("nested", "mail", mail)) + formatted := fmt.Sprintf("%v %+v %#v %s %q %x %d %+v %#v", mail, mail, mail, mail, mail, mail, mail, wrapper, wrapper) + logs.String() + for _, private := range []string{"Private.Person", "private.person", testSubject, "raw-token-value", "Confirm"} { + if strings.Contains(formatted, private) { + t.Fatalf("formatted output exposes message content: %s", formatted) + } + } +} diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 96558e3..89945cf 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -187,6 +187,16 @@ services: SEAWEEDFS_REGION: us-east-1 SEAWEEDFS_TIMEOUT: 10s KAFKA_BROKERS: kafka:9092 + EMAIL_PROVIDER: ${EMAIL_PROVIDER:?Set EMAIL_PROVIDER to resend, smtp, or disabled in the root .env file} + EMAIL_FROM: ${EMAIL_FROM:?Set EMAIL_FROM in the root .env file} + EMAIL_TIMEOUT: ${EMAIL_TIMEOUT:-10s} + APP_PUBLIC_URL: ${APP_PUBLIC_URL:?Set APP_PUBLIC_URL in the root .env file} + RESEND_API_KEY: ${RESEND_API_KEY:-} + SMTP_HOST: ${SMTP_HOST:-} + SMTP_PORT: ${SMTP_PORT:-} + SMTP_USERNAME: ${SMTP_USERNAME:-} + SMTP_PASSWORD: ${SMTP_PASSWORD:-} + SMTP_TLS_MODE: ${SMTP_TLS_MODE:-} depends_on: postgres: condition: service_healthy diff --git a/deploy/scripts/smoke.sh b/deploy/scripts/smoke.sh index 093bcf4..459a17a 100644 --- a/deploy/scripts/smoke.sh +++ b/deploy/scripts/smoke.sh @@ -10,8 +10,11 @@ port=18080 network="${project}_default" started=0 +# The smoke stack sends no mail: it uses EMAIL_PROVIDER=disabled from +# .env.example and points mail links at its own loopback port. compose() { - APP_PROJECT="$project" APP_NETWORK="$app_network" APP_HTTP_PORT="$port" docker compose \ + APP_PROJECT="$project" APP_NETWORK="$app_network" APP_HTTP_PORT="$port" \ + APP_PUBLIC_URL="http://localhost:$port" docker compose \ --env-file "$env_file" \ -p "$project" \ -f "$compose_file" \ @@ -84,6 +87,11 @@ wait_for_readiness() { wait_for "http://127.0.0.1:$port/healthz" wait_for "http://127.0.0.1:$port/api/v1/healthz" +backend_logs=$(compose logs --no-color backend) +if [[ "$backend_logs" != *'mail transport selected'*'disabled'* ]]; then + printf '%s\n' 'Backend did not report EMAIL_PROVIDER=disabled at startup.' >&2 + exit 1 +fi wait_for_readiness status=$(curl --silent --show-error --output /dev/null --write-out '%{http_code}' \ "http://127.0.0.1:$port/api/v1/missing") @@ -122,4 +130,4 @@ fi curl --fail --silent --show-error "http://127.0.0.1:$port/api/v1/healthz" >/dev/null compose up -d --wait --wait-timeout 90 seaweedfs wait_for_readiness -printf '%s\n' 'Technical smoke passed: frontend, API routing, PostgreSQL, Redis, SeaweedFS, dependency recovery, and storage authentication.' +printf '%s\n' 'Technical smoke passed: frontend, API routing, PostgreSQL, Redis, SeaweedFS, dependency recovery, storage authentication, and the disabled mail transport.' diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 4800c18..a3d946c 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -77,6 +77,18 @@ The outbox uniqueness rule is a backstop, not concurrency control. Aggregate upd Planned relay contract (TASK-009): the relay selects unpublished rows (`published_at IS NULL`) ordered by `position` on every pass and never keeps an `occurred_at` or `position` watermark, because a row with a smaller position can become visible after a larger one commits. It publishes the events of one aggregate in `aggregate_version` order and then sets `published_at`. Also planned: retry bookkeeping (attempt count and last error, added by an additive migration), retention of published rows, topics, and idempotent consumers. Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool. +### Mail transport + +Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: the Resend transport (`mail/resend/`, the primary provider for the working stand, TASK-013) and an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP). Until they exist, `resend` and `smtp` fail startup after their settings are validated. Settings are described in [DEPLOY.md](DEPLOY.md#mail). + +`Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of: + +- `accepted`: the provider accepted the request and returned `ProviderMessageID`. This is not delivery or reading. +- `rejected`: the provider answered and refused; `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`, with an optional `RetryAfter`. +- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`). It is not a failure; a retry reuses the idempotency key. + +A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses. + ## Repository map and package purpose ```text @@ -110,7 +122,7 @@ backend/ domain/ flat package; DomainEvent, identity types usecase/health/ operational readiness usecase port/inbound/ readiness input boundary - port/outbound/ readiness, cache, object storage, transaction, outbox, and identity boundaries + port/outbound/ readiness, cache, object storage, transaction, outbox, identity, and mail boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -118,6 +130,7 @@ backend/ v1/ handwritten health endpoint router.go chi composition adapter/secondary/ + mail/disabled/ mail transport that sends nothing and reports the channel unavailable ml/api/ generated client from backend/codegen/ogen-ml.yml postgres/ pool, migrator, transactor, outbox writer, identity repositories, health check postgres/sqlc/ generated SQL adapter @@ -132,9 +145,9 @@ backend/ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`. -Product domain types and usecase modules, mail/FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. +Product domain types and usecase modules, the Resend, SMTP, and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, a Redis cache adapter, and a SeaweedFS S3 adapter. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. `backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 362a094..f4acea1 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -64,6 +64,28 @@ The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` boot down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop. +## Mail + +The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read. + +Current state: this build contains only the `disabled` transport. With `resend` or `smtp`, the backend validates that transport's settings and then exits with `EMAIL_PROVIDER=resend: mail transport is not available in this build` (or `EMAIL_PROVIDER=smtp: ...`); under Compose, `restart: unless-stopped` restarts the container repeatedly. The Resend transport comes in a later task; SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` therefore use `disabled`. Switch the working stand to `resend` only after the build contains the Resend transport. + +`disabled` sends nothing. Every send returns `ErrMailChannelUnavailable` without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains `mail transport selected` with `email_provider` and, for `disabled`, a `mail delivery is disabled` warning. + +| Variable | Default | Validation | +| --- | --- | --- | +| `EMAIL_PROVIDER` | none, required | `resend`, `smtp`, or `disabled`, case-insensitive | +| `EMAIL_FROM` | none, required | One mailbox: `no-reply@example.com` or `Lincodex `. Printable ASCII only. The address follows the account address rules: unquoted local part and a DNS domain with at least two labels, no IP literal. | +| `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt | +| `APP_PUBLIC_URL` | none, required | Public origin for links in mail: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. | +| `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. | +| `SMTP_HOST` | empty | Read only for `smtp`, where it is required. Hostname or IP address without a port. | +| `SMTP_PORT` | empty | Required for `smtp`. Integer from 1 to 65535. | +| `SMTP_USERNAME`, `SMTP_PASSWORD` | empty | Required for `smtp`; an anonymous relay is not supported. | +| `SMTP_TLS_MODE` | empty | Required for `smtp`. `starttls` (upgrade with STARTTLS, usually port 587) or `tls` (TLS from the start, usually port 465). Plaintext SMTP is not supported. | + +Compose passes these variables from the root `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider. + ## Separate ML Compose project ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index f90825c..ff97aa8 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -47,15 +47,16 @@ The repository contains a verifiable technical scaffold, not a product. Values b What exists now: -- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, and a 404 for an unknown API route; it does not start ML. +- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail. - Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, and sqlc-backed identity repositories for accounts, email tokens, and sessions; Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. +- Mail: the outbound `MailSender` port, the `disabled` transport, and the `EMAIL_PROVIDER` selection in bootstrap. Only `disabled` works in this build; `resend` and `smtp` fail startup after their settings are validated. Nothing sends mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has a home page, a generated API client, and MSW handlers. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka. - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. -Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table and the identity storage tables (`users`, `email_tokens`, `sessions`) and no other business schema; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). +Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table and the identity storage tables (`users`, `email_tokens`, `sessions`) and no other business schema; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). ## Install and work loop diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 03882c7..fa671be 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -40,7 +40,7 @@ Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub. -Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, and rejection of anonymous SeaweedFS bucket access. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It does not check contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application. +Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, and the backend startup log for `EMAIL_PROVIDER=disabled`. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application. ## Integration test bootstrap diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 5dce2b7..bdc3ba8 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -77,6 +77,18 @@ Usecase пишет через outbound-порты. `Transactor.WithinTransaction Запланированный контракт relay (TASK-009): на каждом проходе relay выбирает неопубликованные строки (`published_at IS NULL`) в порядке `position` и никогда не хранит watermark по `occurred_at` или `position`, потому что строка с меньшей позицией может стать видимой после фиксации строки с большей. События одного агрегата он публикует в порядке `aggregate_version` и затем заполняет `published_at`. Также запланированы учет повторов (счетчик попыток и последняя ошибка, добавятся аддитивной миграцией), хранение опубликованных строк, топики и идемпотентные потребители. Bootstrap пока не подключает transactor, потому что его не использует ни один продуктовый usecase; первая бизнес-транзакция подключит его вместе с общим пулом. +### Почтовый транспорт + +Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт Resend (`mail/resend/`, основной провайдер рабочего стенда, TASK-013) и транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP). Пока их нет, `resend` и `smtp` после проверки своих настроек останавливают запуск. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). + +`Send(ctx, OutgoingMail)` делает ровно одну попытку. `OutgoingMail` содержит получателя, тему, текстовое и HTML тело и ключ идемпотентности, который не меняется для одной логической доставки между повторами (от 1 до 256 печатных ASCII символов, предел Resend, без персональных данных); отправитель берется из `EMAIL_FROM`. При nil ошибке результат один из: + +- `accepted`: провайдер принял запрос и вернул `ProviderMessageID`. Это не доставка и не прочтение. +- `rejected`: провайдер ответил отказом; `Rejection` равен `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted` или `temporary`, возможно с `RetryAfter`. +- `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`). Это не ошибка доставки; повтор использует тот же ключ идемпотентности. + +Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. + ## Структура репозитория и назначение пакетов ```text @@ -110,7 +122,7 @@ backend/ domain/ плоский пакет; DomainEvent, типы identity usecase/health/ operational readiness usecase port/inbound/ inbound граница readiness - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox и identity + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity и почты adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -118,6 +130,7 @@ backend/ v1/ написанный вручную health endpoint router.go сборка chi router adapter/secondary/ + mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала ml/api/ generated client из backend/codegen/ogen-ml.yml postgres/ pool, migrator, transactor, запись outbox, репозитории identity, health check postgres/sqlc/ generated SQL adapter @@ -132,9 +145,9 @@ backend/ Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`. -`domain/`, продуктовые `usecase/`, адаптеры почты и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. +`domain/`, продуктовые `usecase/`, адаптеры Resend, SMTP и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, Redis cache adapter и S3-адаптер SeaweedFS. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, Redis cache adapter, S3-адаптер SeaweedFS и порт `MailSender` с транспортом `disabled`. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index a4b7709..f810b1f 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -66,6 +66,28 @@ Backend получает `KAFKA_BROKERS` - список адресов bootstrap down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова. +## Почта + +Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются. + +Текущее состояние: в этой сборке есть только транспорт `disabled`. С `resend` или `smtp` backend проверяет настройки этого транспорта и затем завершается с ошибкой `EMAIL_PROVIDER=resend: mail transport is not available in this build` (или `EMAIL_PROVIDER=smtp: ...`); в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. Транспорт Resend появится в следующей задаче, SMTP вне MVP. Поэтому `.env.example` и `make -C deploy smoke` используют `disabled`. Переключайте рабочий стенд на `resend` только после того, как сборка будет содержать транспорт Resend. + +`disabled` ничего не отправляет. Каждая отправка возвращает `ErrMailChannelUnavailable` без идентификатора сообщения провайдера и никогда не считается принятой или доставленной. Этот режим не подтверждает email, не отмечает аккаунт подтвержденным и не пропускает проверки аккаунта. В логе запуска есть `mail transport selected` с полем `email_provider`, а для `disabled` еще и предупреждение `mail delivery is disabled`. + +| Переменная | По умолчанию | Проверка | +| --- | --- | --- | +| `EMAIL_PROVIDER` | нет, обязательна | `resend`, `smtp` или `disabled`, без учета регистра | +| `EMAIL_FROM` | нет, обязательна | Один mailbox: `no-reply@example.com` или `Lincodex `. Только печатные ASCII символы. Адрес подчиняется правилам адресов аккаунтов: local part без кавычек и DNS-домен минимум из двух меток, без IP literal. | +| `EMAIL_TIMEOUT` | `10s` | Go duration от `1s` до `1m`; ограничивает одну попытку транспорта | +| `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. | +| `RESEND_API_KEY` | пусто | Читается только для `resend` и там обязательна. Печатные ASCII символы без пробелов. Префикс `re_` из примеров Resend не проверяется. | +| `SMTP_HOST` | пусто | Читается только для `smtp` и там обязательна. Имя хоста или IP адрес без порта. | +| `SMTP_PORT` | пусто | Обязательна для `smtp`. Целое число от 1 до 65535. | +| `SMTP_USERNAME`, `SMTP_PASSWORD` | пусто | Обязательны для `smtp`; анонимный relay не поддерживается. | +| `SMTP_TLS_MODE` | пусто | Обязательна для `smtp`. `starttls` (переход на TLS через STARTTLS, обычно порт 587) или `tls` (TLS с начала соединения, обычно порт 465). SMTP без шифрования не поддерживается. | + +Compose передает эти переменные из корневого `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера. + ## Отдельный ML Compose ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 88a3f35..f1ff49e 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -47,15 +47,16 @@ Frontend зависимости выбираются из актуальных s Что есть сейчас: -- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose и 404 для неизвестного API маршрута; ML он не запускает. +- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет. - Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox и репозитории identity на sqlc для аккаунтов, email-токенов и сессий; Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. +- Почта: outbound порт `MailSender`, транспорт `disabled` и выбор `EMAIL_PROVIDER` в bootstrap. В этой сборке работает только `disabled`; `resend` и `smtp` после проверки своих настроек останавливают запуск. Пока ничто не отправляет письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть домашняя страница, generated API client и MSW handlers. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness. - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox и таблицы хранения identity (`users`, `email_tokens`, `sessions`), другой бизнес-схемы нет; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox и таблицы хранения identity (`users`, `email_tokens`, `sessions`), другой бизнес-схемы нет; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index e1e86ea..b3c8bf2 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -40,7 +40,7 @@ make -C ml check-generated использует datamodel-code-generator --check API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. -Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не проверяет получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения. +Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения. ## Bootstrap интеграционных тестов