package config import ( "errors" "fmt" "net" "net/mail" "net/url" "regexp" "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 ( // defaultEmailAccount labels the only provider account of a stand that // never switched accounts. defaultEmailAccount = "default" 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 ) // emailAccountPattern matches domain.NewMailProviderAccount: a lowercase // label that cannot hold the mixed-case characters of an API key. var emailAccountPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`) // 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", "")) config.EmailAccount = strings.TrimSpace(valueOrDefault(lookup, "EMAIL_ACCOUNT", defaultEmailAccount)) // 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 } // The value is not echoed: an API key pasted here must not reach logs. if !emailAccountPattern.MatchString(config.EmailAccount) { return errors.New("Config.ValidateMail - EMAIL_ACCOUNT must be a label of 1 to 64 lowercase letters, digits, '.', '_', or '-' that starts with a letter or digit") } 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 }