diff --git a/frontend/src/lib/dialogs/ChannelConfigModal.svelte b/frontend/src/lib/dialogs/ChannelConfigModal.svelte index 3d25fda00..1fa4c9926 100644 --- a/frontend/src/lib/dialogs/ChannelConfigModal.svelte +++ b/frontend/src/lib/dialogs/ChannelConfigModal.svelte @@ -114,6 +114,8 @@ item_type_id: null, mailbox: 'INBOX', processing_disposition: 'mark_read', + sender_authentication: '', + trusted_authserv_ids: '', rate_limit_per_hour: null, enabled: false }); @@ -240,6 +242,10 @@ : config.email_mark_as_read === false ? 'leave' : 'mark_read'), + // Strict is the backend default for an empty value; normalize a + // stored "strict" so the select always has a matching option. + sender_authentication: config.email_sender_authentication === 'off' ? 'off' : '', + trusted_authserv_ids: (config.email_trusted_authserv_ids || []).join(', '), rate_limit_per_hour: config.email_rate_limit_per_hour ?? null, enabled: channel.status === 'enabled' }; diff --git a/frontend/src/lib/dialogs/EmailLogModal.svelte b/frontend/src/lib/dialogs/EmailLogModal.svelte index 53084e54d..c27f57b63 100644 --- a/frontend/src/lib/dialogs/EmailLogModal.svelte +++ b/frontend/src/lib/dialogs/EmailLogModal.svelte @@ -438,6 +438,19 @@ {t('channel.emailLog.rateLimited')} + {:else if msg.skipped_reason} + + + + {msg.skipped_reason === 'unauthenticated_sender' + ? t('channel.emailLog.heldUnauthenticated') + : msg.skipped_reason} + {:else if msg.item_id} {@const href = getItemHref(msg)} diff --git a/frontend/src/lib/features/channels/ChannelEmailConfig.svelte b/frontend/src/lib/features/channels/ChannelEmailConfig.svelte index 23dfcabfb..1e7830201 100644 --- a/frontend/src/lib/features/channels/ChannelEmailConfig.svelte +++ b/frontend/src/lib/features/channels/ChannelEmailConfig.svelte @@ -39,6 +39,8 @@ item_type_id: null, mailbox: 'INBOX', processing_disposition: 'mark_read', + sender_authentication: '', + trusted_authserv_ids: '', rate_limit_per_hour: null, enabled: false }), @@ -146,7 +148,15 @@ // limit) and per-intake disposition overrides live on intakes. const baseConfig = { email_auth_method: formData.auth_method, - email_processing_disposition: formData.processing_disposition || 'mark_read' + email_processing_disposition: formData.processing_disposition || 'mark_read', + // Empty means strict on the backend; send the explicit value the admin chose. + email_sender_authentication: formData.sender_authentication || '', + email_trusted_authserv_ids: formData.trusted_authserv_ids + ? formData.trusted_authserv_ids + .split(',') + .map((host) => host.trim()) + .filter(Boolean) + : undefined }; if (formData.auth_method === 'oauth') { @@ -430,6 +440,34 @@ {t('channel.dispositionHelp')} + +
+ + {t('channel.senderAuthHelp')} + {#if formData.sender_authentication !== 'off'} +
+ + {t('channel.trustedAuthServersHelp')} +
+ {/if} +
+ diff --git a/frontend/src/lib/features/channels/ChannelIntakesSection.svelte b/frontend/src/lib/features/channels/ChannelIntakesSection.svelte index f76da3d69..f13607ac8 100644 --- a/frontend/src/lib/features/channels/ChannelIntakesSection.svelte +++ b/frontend/src/lib/features/channels/ChannelIntakesSection.svelte @@ -65,6 +65,7 @@ item_type_id: null, rate_limit_per_hour: '', processing_disposition: '', + sender_authentication: '', send_confirmation: false, import_existing_mail: false, status: 'enabled' @@ -100,6 +101,9 @@ if (editing.status === 'needs_attention') { editing.status = 'disabled'; } + // sender_authentication is loaded verbatim so an explicit "strict" is not + // silently turned into "inherit" on an unrelated edit; inherit and strict + // differ whenever the mailbox default is "off". loadItemTypesForWorkspace(editing.workspace_id); } @@ -144,6 +148,7 @@ ? null : Number(editing.rate_limit_per_hour), processing_disposition: editing.processing_disposition || '', + sender_authentication: editing.sender_authentication || '', send_confirmation: !!editing.send_confirmation, import_existing_mail: !!editing.import_existing_mail, status: editing.status || 'enabled' @@ -381,6 +386,22 @@ /> +
+ + {t('channel.senderAuthIntakeHelp')} +
+
- {total} skipped message{total === 1 ? '' : 's'} + {total} held or skipped message{total === 1 ? '' : 's'}
Not created as work items; recorded for diagnostics only. @@ -92,7 +94,7 @@ {#if !view.loading && !view.error && total === 0}

- No system-generated mail was skipped in this window. + No held or skipped mail in this window.

{:else if !view.error} @@ -132,6 +134,11 @@ {categoryLabel(message.category)} + {#if message.sender_auth} +
+ {message.sender_auth} +
+ {/if} {#if message.from_name} diff --git a/internal/database/migrations.go b/internal/database/migrations.go index 2ce3b769c..3ea5bdd77 100644 --- a/internal/database/migrations.go +++ b/internal/database/migrations.go @@ -3727,6 +3727,29 @@ END $$; CREATE UNIQUE INDEX IF NOT EXISTS uq_priorities_single_default ON priorities(is_default) WHERE is_default = true; `, }, + { + // WI-2362: inbound mail authenticated its From address only through the + // attacker-controlled header. sender_auth records the SPF/DKIM/DMARC + // outcome on each tracking row, and intakes.sender_authentication lets an + // operator relax the default strict policy per intake. Empty + // sender_authentication means strict, so existing intakes need no backfill; + // operators whose provider does not add authentication headers must set it + // to 'off' explicitly. + Version: "20261204_email_sender_authentication", + Name: "Record inbound sender authentication and per-intake policy (WI-2362)", + CheckSQLite: "SELECT CASE WHEN (" + sqliteColumnCheck("email_message_tracking", "sender_auth") + + ") > 0 AND (" + sqliteColumnCheck("intakes", "sender_authentication") + ") > 0 THEN 1 ELSE 0 END", + CheckPostgres: "SELECT CASE WHEN (" + pgColumnCheck("email_message_tracking", "sender_auth") + + ") > 0 AND (" + pgColumnCheck("intakes", "sender_authentication") + ") > 0 THEN 1 ELSE 0 END", + SQLite: ` + ALTER TABLE email_message_tracking ADD COLUMN sender_auth TEXT; + ALTER TABLE intakes ADD COLUMN sender_authentication TEXT NOT NULL DEFAULT ''; + `, + Postgres: ` + ALTER TABLE email_message_tracking ADD COLUMN IF NOT EXISTS sender_auth TEXT; + ALTER TABLE intakes ADD COLUMN IF NOT EXISTS sender_authentication TEXT NOT NULL DEFAULT ''; + `, + }, } // domainEventClaimableIndexMigration adds the partial index the claim query diff --git a/internal/database/schema/email.sql b/internal/database/schema/email.sql index a74e3acd3..fa3e46c1b 100644 --- a/internal/database/schema/email.sql +++ b/internal/database/schema/email.sql @@ -51,6 +51,9 @@ CREATE TABLE IF NOT EXISTS intakes ( item_type_id INTEGER, -- item type created for the routing workspace rate_limit_per_hour INTEGER, processing_disposition TEXT NOT NULL DEFAULT '', + -- sender_authentication overrides the mailbox's inbound sender + -- authentication policy for this intake. Empty inherits the mailbox default. + sender_authentication TEXT NOT NULL DEFAULT '', send_confirmation BOOLEAN NOT NULL DEFAULT false, import_existing_mail BOOLEAN NOT NULL DEFAULT false, status TEXT NOT NULL DEFAULT 'enabled', @@ -142,11 +145,18 @@ CREATE TABLE IF NOT EXISTS email_message_tracking ( -- reprocessing the same email. It is only cleared when the channel is -- deleted and cascades the tracking rows. completed_at DATETIME, - -- skipped_reason records machine-generated mail (bounces, auto-replies) - -- that intake deliberately did not turn into a ticket. The value is a - -- SystemMailCategory; NULL for mail that was processed normally. Surfaced - -- by the admin email-intake diagnostics view. + -- skipped_reason records mail intake deliberately did not turn into a + -- ticket: machine-generated mail (bounces, auto-replies) and, under a + -- strict sender-authentication policy, mail whose From address could not + -- be authenticated. The value is a SystemMailCategory or + -- 'unauthenticated_sender'; NULL for mail that was processed normally. + -- Surfaced by the admin email-intake diagnostics view. skipped_reason TEXT, + -- sender_auth records the outcome of evaluating the message's SPF, DKIM, + -- and DMARC results against the From domain, e.g. 'dmarc=pass', 'spf=fail', + -- or 'none'. NULL for rows written before the check existed. Surfaced by + -- the channel email log and admin diagnostics. + sender_auth TEXT, processed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE, FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE SET NULL, diff --git a/internal/database/schema/email_postgres.sql b/internal/database/schema/email_postgres.sql index 206cc86b9..83002a74d 100644 --- a/internal/database/schema/email_postgres.sql +++ b/internal/database/schema/email_postgres.sql @@ -49,6 +49,8 @@ CREATE TABLE IF NOT EXISTS intakes ( item_type_id INTEGER, rate_limit_per_hour INTEGER, processing_disposition TEXT NOT NULL DEFAULT '', + -- sender_authentication: see email.sql for the column contract. + sender_authentication TEXT NOT NULL DEFAULT '', send_confirmation BOOLEAN NOT NULL DEFAULT false, import_existing_mail BOOLEAN NOT NULL DEFAULT false, status TEXT NOT NULL DEFAULT 'enabled', @@ -118,8 +120,9 @@ CREATE TABLE IF NOT EXISTS email_message_tracking ( uid_validity BIGINT NOT NULL DEFAULT 0, rate_limited_at TIMESTAMPTZ, completed_at TIMESTAMPTZ, - -- skipped_reason: see email.sql for the column contract. + -- skipped_reason/sender_auth: see email.sql for the column contract. skipped_reason TEXT, + sender_auth TEXT, processed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE, FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE SET NULL, diff --git a/internal/email/parser.go b/internal/email/parser.go index 448cb780a..7b28de6e8 100644 --- a/internal/email/parser.go +++ b/internal/email/parser.go @@ -7,6 +7,7 @@ import ( "log/slog" "mime" "net/mail" + "net/textproto" "regexp" "strings" @@ -123,6 +124,7 @@ func (p *Parser) Parse(msg *FetchedMessage) *ParsedEmail { for key, values := range headers.Header { parsed.RawHeaders[key] = values } + parsed.HeaderOrder = parseHeaderOrder(msg.Raw) } } @@ -147,6 +149,42 @@ func (p *Parser) Parse(msg *FetchedMessage) *ParsedEmail { return parsed } +// parseHeaderOrder records the header field names of a raw message in order, +// including duplicates. Continuation lines (leading space or tab) are folded +// into the preceding field. Parsing stops at the blank line that ends the +// header block. +func parseHeaderOrder(raw []byte) []string { + var order []string + // Walk line by line with IndexByte rather than bytes.Split so a large body + // is never split into a slice of lines just to read the header block. + for len(raw) > 0 { + line := raw + if newline := bytes.IndexByte(raw, '\n'); newline >= 0 { + line = raw[:newline] + raw = raw[newline+1:] + } else { + raw = nil + } + line = bytes.TrimRight(line, "\r") + if len(line) == 0 { + break // end of the header block + } + if line[0] == ' ' || line[0] == '\t' { + continue // folded continuation of the previous field + } + colon := bytes.IndexByte(line, ':') + if colon <= 0 { + continue + } + name := textproto.CanonicalMIMEHeaderKey(string(line[:colon])) + if name == "" { + continue + } + order = append(order, name) + } + return order +} + // parseBody parses the email body, extracting text content and attachments func (p *Parser) parseBody(r io.Reader, parsed *ParsedEmail) error { entity, err := goMessage.Read(r) diff --git a/internal/email/processor.go b/internal/email/processor.go index 67924b14d..883ede823 100644 --- a/internal/email/processor.go +++ b/internal/email/processor.go @@ -127,6 +127,13 @@ func (p *Processor) ProcessEmailWithIntake( return nil, fmt.Errorf("failed to claim tracking row: %w", err) } if claim == trackingClaimCompleted { + // A message held by a strict sender-authentication policy must stay held + // on redelivery: the scheduler preserves held mail rather than applying + // the delete/mark-read disposition. + if p.trackingRowHeldForAuth(ctx, channelID, dedupKey) { + slog.Debug("email already held for sender authentication", "message_id", email.MessageID, "dedup_key", dedupKey) + return &ProcessingResult{Action: ActionHeldForAuth, SkipReason: skipReasonUnauthenticatedSender}, nil + } slog.Debug("email already processed", "message_id", email.MessageID, "dedup_key", dedupKey) return &ProcessingResult{Action: ActionAlreadyExists}, nil } @@ -152,6 +159,25 @@ func (p *Processor) ProcessEmailWithIntake( }, nil } + // 1c. Sender authentication. The From header is attacker-controlled, so a + // strict policy holds mail whose From domain did not pass an aligned SPF, + // DKIM, or DMARC check instead of attributing it to a portal customer or an + // existing thread (WI-2362). The message is recorded on the tracking row so + // the admin diagnostics view can show what was held and why. + authResult := EvaluateSenderAuthentication(email, ResolveTrustedAuthServIDs(config)) + if policy := ResolveSenderAuthPolicy(config.EmailSenderAuthentication); policy == SenderAuthStrict && !authResult.Verified { + p.markSenderAuthHeld(ctx, channelID, dedupKey, authResult) + slog.Warn("held inbound email: sender not authenticated", + "channel_id", channelID, + "message_id", email.MessageID, + "from", email.From.Address, + "auth", authResult.Summary(), + "detail", authResult.Detail, + ) + return &ProcessingResult{Action: ActionHeldForAuth, SkipReason: skipReasonUnauthenticatedSender}, nil + } + p.recordSenderAuth(ctx, channelID, dedupKey, authResult) + // 2. Find or create portal customer by email customerID, err := p.findOrCreatePortalCustomer(ctx, email.From.Address, email.From.Name, channelID, config) if err != nil { @@ -370,6 +396,54 @@ func (p *Processor) markSystemMailSkipped(ctx context.Context, channelID int, de } } +// skipReasonUnauthenticatedSender is persisted in +// email_message_tracking.skipped_reason when a strict sender-authentication +// policy held mail whose From address could not be authenticated. It is +// rendered by the admin email-intake diagnostics view. +const skipReasonUnauthenticatedSender = "unauthenticated_sender" + +// recordSenderAuth stamps the authentication outcome on the claimed tracking +// row so the channel email log and admin diagnostics can show how the sender +// was authenticated. Best effort: a failure here never changes ingestion. +func (p *Processor) recordSenderAuth(ctx context.Context, channelID int, dedupKey string, auth SenderAuthResult) { + if _, err := p.db.ExecWriteContext(ctx, ` + UPDATE email_message_tracking + SET sender_auth = ? + WHERE channel_id = ? AND dedup_key = ? + `, auth.Summary(), channelID, dedupKey); err != nil { + slog.Warn("failed to record sender authentication", + "error", err, "channel_id", channelID, "dedup_key", dedupKey, "auth", auth.Summary()) + } +} + +// trackingRowHeldForAuth reports whether a completed tracking row was held by +// the sender-authentication policy rather than turned into an item or comment. +func (p *Processor) trackingRowHeldForAuth(ctx context.Context, channelID int, dedupKey string) bool { + var reason sql.NullString + if err := p.db.QueryRowContext(ctx, ` + SELECT skipped_reason FROM email_message_tracking + WHERE channel_id = ? AND dedup_key = ? + `, channelID, dedupKey).Scan(&reason); err != nil { + return false + } + return reason.Valid && reason.String == skipReasonUnauthenticatedSender +} + +// markSenderAuthHeld finalizes the claimed tracking row for mail a strict +// policy refused to attribute to the From address. completed_at keeps the +// message deduplicated (the item and comment refs stay NULL) and skipped_reason +// is the admin diagnostics hook. +func (p *Processor) markSenderAuthHeld(ctx context.Context, channelID int, dedupKey string, auth SenderAuthResult) { + if _, err := p.db.ExecWriteContext(ctx, ` + UPDATE email_message_tracking + SET sender_auth = ?, skipped_reason = ?, completed_at = CURRENT_TIMESTAMP + WHERE channel_id = ? AND dedup_key = ? AND completed_at IS NULL + `, auth.Summary(), skipReasonUnauthenticatedSender, channelID, dedupKey); err != nil { + slog.Warn("failed to mark unauthenticated email held", + "error", err, "channel_id", channelID, "dedup_key", dedupKey, "auth", auth.Summary()) + } +} + // findOrCreatePortalCustomer resolves the sender to a portal customer by // email, creating one on first contact, and grants channel access. func (p *Processor) findOrCreatePortalCustomer( diff --git a/internal/email/sender_auth.go b/internal/email/sender_auth.go new file mode 100644 index 000000000..f6de529bf --- /dev/null +++ b/internal/email/sender_auth.go @@ -0,0 +1,731 @@ +package email + +import ( + "strings" + + "golang.org/x/net/publicsuffix" + + "windshift/internal/models" +) + +// SenderAuthPolicy controls whether the From address of inbound mail must be +// backed by a passing, aligned SPF, DKIM, or DMARC result before intake trusts +// it. The From header is entirely attacker-controlled; without this check +// anyone who can deliver a message can claim to be a known customer and either +// join a private thread or create a request in their name (WI-2362). +type SenderAuthPolicy string + +const ( + // SenderAuthStrict holds mail whose From domain is not authenticated. It is + // the default for any channel or intake that does not configure a policy, + // so a missing or misspelled value can never silently disable the check. + SenderAuthStrict SenderAuthPolicy = "strict" + // SenderAuthOff trusts the From header the way intake did before sender + // authentication existed. Intended for mailbox providers that do not add + // Authentication-Results / Received-SPF headers. + SenderAuthOff SenderAuthPolicy = "off" +) + +// ResolveSenderAuthPolicy returns the effective policy. Anything other than an +// explicit "off" resolves to strict. +func ResolveSenderAuthPolicy(value string) SenderAuthPolicy { + if strings.EqualFold(strings.TrimSpace(value), string(SenderAuthOff)) { + return SenderAuthOff + } + return SenderAuthStrict +} + +// IsValidSenderAuthPolicy reports whether value is a recognized policy or the +// empty default sentinel. +func IsValidSenderAuthPolicy(value string) bool { + switch strings.ToLower(strings.TrimSpace(value)) { + case "", string(SenderAuthStrict), string(SenderAuthOff): + return true + default: + return false + } +} + +// ResolveTrustedAuthServIDs returns the receiver hosts whose +// Authentication-Results and Received-SPF headers are trusted for a mailbox. +// These are the mailbox-specific receiver boundary: the final delivery agent +// prepends its own result above its Received header, so a result is trusted +// only when it sits above a Received hop from one of these hosts. +// +// Operators can list the hosts explicitly. Otherwise they are derived from the +// provider and the configured mail host. An empty result means no boundary can +// be established; strict mode then holds everything rather than trusting an +// arbitrary header. +func ResolveTrustedAuthServIDs(config *models.ChannelConfig) []string { + if config == nil { + return nil + } + var trusted []string + trusted = append(trusted, config.EmailTrustedAuthServIDs...) + + switch strings.ToLower(strings.TrimSpace(config.EmailOAuthProviderType)) { + case models.EmailProviderTypeGoogle: + trusted = append(trusted, "mx.google.com") + case models.EmailProviderTypeMicrosoft: + trusted = append(trusted, "mx.microsoft.com", "outbound.protection.outlook.com") + } + + imapHost := strings.ToLower(strings.TrimSpace(config.IMAPHost)) + switch { + case strings.Contains(imapHost, "gmail"): + trusted = append(trusted, "mx.google.com") + case strings.Contains(imapHost, "outlook"), strings.Contains(imapHost, "office365"): + trusted = append(trusted, "mx.microsoft.com", "outbound.protection.outlook.com") + } + if imapHost != "" { + trusted = append(trusted, imapHost) + if org := organizationalDomain(imapHost); org != "" { + trusted = append(trusted, org) + } + } + + // The monitored address's domain is the last resort: a self-hosted mailbox + // is usually served by a host in the same organizational domain. + if address := firstNonEmpty(config.EmailOAuthMailbox, config.EmailOAuthEmail, config.IMAPUsername); address != "" { + if domain := emailDomain(address); domain != "" { + trusted = append(trusted, domain) + if org := organizationalDomain(domain); org != "" { + trusted = append(trusted, org) + } + } + } + return normalizeTrustedHosts(trusted) +} + +// SenderAuthMethod identifies the mechanism a result came from. +type SenderAuthMethod string + +const ( + SenderAuthMethodSPF SenderAuthMethod = "spf" + SenderAuthMethodDKIM SenderAuthMethod = "dkim" + SenderAuthMethodDMARC SenderAuthMethod = "dmarc" +) + +// SenderAuthResult is the outcome of evaluating a message's authentication +// headers against its From domain. +type SenderAuthResult struct { + // Verified is true when a passing, aligned result was found. + Verified bool + // Method is the mechanism that produced the result. + Method SenderAuthMethod + // Outcome is the raw result token ("pass", "fail", "softfail", "none", ...). + Outcome string + // Detail is a short, operator-facing explanation of the decision. + Detail string +} + +// Summary returns the compact, persisted form of the result, e.g. "dmarc=pass". +func (r SenderAuthResult) Summary() string { + if r.Method == "" { + return "none" + } + if r.Outcome == "" { + return string(r.Method) + } + return string(r.Method) + "=" + r.Outcome +} + +// EvaluateSenderAuthentication inspects the receiving MTA's +// Authentication-Results (falling back to Received-SPF) and reports whether +// the From domain is authenticated by an aligned SPF, DKIM, or DMARC pass. +// +// Only results that appear above a trusted receiver hop are considered, and an +// Authentication-Results header is trusted only when its authserv-id is one of +// trustedReceivers. Both conditions are required: the position rejects a +// result injected below the receiving MTA's Received header, and the +// authserv-id rejects an upstream MTA's result that happens to sit above the +// boundary. When no trusted receiver hop exists the message is treated as +// unauthenticated. +func EvaluateSenderAuthentication(message *ParsedEmail, trustedReceivers []string) SenderAuthResult { + if message == nil { + return SenderAuthResult{Outcome: "none", Detail: "no message"} + } + fromDomain := emailDomain(message.From.Address) + if fromDomain == "" { + return SenderAuthResult{Outcome: "none", Detail: "sender address has no domain"} + } + + boundary := trustedReceiverBoundary(message, trustedReceivers) + if boundary < 0 { + return SenderAuthResult{ + Outcome: "none", + Detail: "no trusted receiver boundary for " + fromDomain, + } + } + + var fallback *SenderAuthResult + for _, raw := range headerValuesAbove(message, "Authentication-Results", boundary) { + result, verified := evaluateAuthenticationResults(raw, fromDomain, trustedReceivers) + if verified { + return result + } + if fallback == nil { + remembered := result + fallback = &remembered + } + } + for _, raw := range headerValuesAbove(message, "Received-SPF", boundary) { + result, verified := evaluateReceivedSPF(raw, fromDomain) + if verified { + return result + } + if fallback == nil { + remembered := result + fallback = &remembered + } + } + if fallback != nil { + return *fallback + } + return SenderAuthResult{ + Outcome: "none", + Detail: "no SPF, DKIM, or DMARC result for " + fromDomain, + } +} + +// authMethod is one method=result clause from an Authentication-Results header. +type authMethod struct { + name string + result string + props map[string]string +} + +// evaluateAuthenticationResults parses one Authentication-Results value and +// reports whether it carries an aligned pass. The bool is true only for a +// verified result; the returned result describes the outcome either way. +func evaluateAuthenticationResults(value, fromDomain string, trustedReceivers []string) (SenderAuthResult, bool) { + authservID, methods := parseAuthenticationResults(value) + if len(methods) == 0 { + return SenderAuthResult{Outcome: "none", Detail: "no SPF, DKIM, or DMARC clause"}, false + } + if !authServIDTrusted(authservID, trustedReceivers) { + return SenderAuthResult{ + Outcome: "untrusted", + Detail: "result from untrusted authentication server " + authservID, + }, false + } + + // DMARC first: a pass already encodes alignment between the From domain and + // a passing SPF or DKIM signature. When the receiver records header.from, + // still confirm it matches the actual From domain. + for _, method := range methods { + if method.name != "dmarc" || method.result != "pass" { + continue + } + if claimed := emailDomain(method.props["header.from"]); claimed != "" && !strings.EqualFold(claimed, fromDomain) { + continue + } + return SenderAuthResult{ + Verified: true, + Method: SenderAuthMethodDMARC, + Outcome: "pass", + Detail: "dmarc=pass aligned with " + fromDomain, + }, true + } + + // DKIM: the signing domain must share the From domain's organizational + // domain under DMARC relaxed alignment. + for _, method := range methods { + if method.name != "dkim" || method.result != "pass" { + continue + } + domain := dkimSigningDomain(method.props) + if domain != "" && organizationalDomainsAligned(fromDomain, domain) { + return SenderAuthResult{ + Verified: true, + Method: SenderAuthMethodDKIM, + Outcome: "pass", + Detail: "dkim=pass signed by " + domain, + }, true + } + } + + // SPF: the envelope (MAIL FROM) domain must share the From domain's + // organizational domain under DMARC relaxed alignment. + for _, method := range methods { + if method.name != "spf" || method.result != "pass" { + continue + } + domain := emailDomain(method.props["smtp.mailfrom"]) + if domain != "" && organizationalDomainsAligned(fromDomain, domain) { + return SenderAuthResult{ + Verified: true, + Method: SenderAuthMethodSPF, + Outcome: "pass", + Detail: "spf=pass for " + domain, + }, true + } + } + + return summarizeAuthenticationResults(methods), false +} + +// parseAuthenticationResults returns the authserv-id and the method clauses of +// an Authentication-Results value. Parsing respects RFC 8601: clauses are +// separated by semicolons outside quoted strings and comments, and a method is +// accepted only as the first token of a clause, so a quoted diagnostic or +// property value can never be read as a verdict. +func parseAuthenticationResults(value string) (string, []authMethod) { + clauses := splitAuthResultsClauses(value) + if len(clauses) == 0 { + return "", nil + } + authservID := strings.ToLower(firstToken(clauses[0])) + var out []authMethod + for _, clause := range clauses[1:] { + tokens := tokenizeAuthClause(clause) + if len(tokens) == 0 { + continue + } + name, rawValue, ok := strings.Cut(tokens[0], "=") + if !ok { + continue + } + name = strings.ToLower(strings.TrimSpace(name)) + if name != "spf" && name != "dkim" && name != "dmarc" { + continue + } + method := authMethod{ + name: name, + result: strings.ToLower(trimQuoted(rawValue)), + props: map[string]string{}, + } + for _, token := range tokens[1:] { + prop, propValue, ok := strings.Cut(token, "=") + if !ok { + continue + } + method.props[strings.ToLower(strings.TrimSpace(prop))] = trimQuoted(propValue) + } + out = append(out, method) + } + return authservID, out +} + +// splitAuthResultsClauses splits on semicolons that are outside quoted strings +// and parenthesized comments. +func splitAuthResultsClauses(value string) []string { + var clauses []string + var current strings.Builder + depth := 0 + inQuote := false + for i := 0; i < len(value); i++ { + c := value[i] + switch { + case inQuote: + current.WriteByte(c) + switch { + case c == '\\' && i+1 < len(value): + i++ + current.WriteByte(value[i]) + case c == '"': + inQuote = false + } + case depth > 0: + current.WriteByte(c) + switch { + case c == '\\' && i+1 < len(value): + i++ + current.WriteByte(value[i]) + case c == '(': + depth++ + case c == ')': + depth-- + } + case c == '"': + inQuote = true + current.WriteByte(c) + case c == '(': + depth++ + current.WriteByte(c) + case c == ';': + clauses = append(clauses, current.String()) + current.Reset() + default: + current.WriteByte(c) + } + } + clauses = append(clauses, current.String()) + return clauses +} + +// tokenizeAuthClause splits a clause into whitespace-separated tokens, +// preserving quoted strings and skipping parenthesized comments. +func tokenizeAuthClause(clause string) []string { + var tokens []string + var current strings.Builder + depth := 0 + inQuote := false + flush := func() { + if current.Len() > 0 { + tokens = append(tokens, current.String()) + current.Reset() + } + } + for i := 0; i < len(clause); i++ { + c := clause[i] + switch { + case inQuote: + current.WriteByte(c) + switch { + case c == '\\' && i+1 < len(clause): + i++ + current.WriteByte(clause[i]) + case c == '"': + inQuote = false + } + case depth > 0: + switch { + case c == '\\' && i+1 < len(clause): + i++ + case c == '(': + depth++ + case c == ')': + depth-- + } + case c == '"': + inQuote = true + current.WriteByte(c) + case c == '(': + flush() + depth++ + case c == ' ' || c == '\t' || c == '\r' || c == '\n': + flush() + default: + current.WriteByte(c) + } + } + flush() + return tokens +} + +// summarizeAuthenticationResults picks the most relevant observed outcome for +// operator display when nothing verified. DMARC is preferred, then DKIM, then +// SPF, because it best explains why a message was held. +func summarizeAuthenticationResults(methods []authMethod) SenderAuthResult { + for _, name := range []string{"dmarc", "dkim", "spf"} { + for _, method := range methods { + if method.name == name { + return SenderAuthResult{ + Method: SenderAuthMethod(name), + Outcome: method.result, + Detail: name + "=" + method.result, + } + } + } + } + return SenderAuthResult{Outcome: "none", Detail: "no SPF, DKIM, or DMARC result"} +} + +// evaluateReceivedSPF parses a Received-SPF value. It only contributes an SPF +// outcome: the header carries no DKIM or DMARC information. A pass without an +// envelope-from was evaluated against HELO, which authenticates the sending +// host rather than the envelope sender, so it cannot establish the From domain. +func evaluateReceivedSPF(value, fromDomain string) (SenderAuthResult, bool) { + cleaned := stripAuthenticationComments(value) + fields := strings.Fields(cleaned) + if len(fields) == 0 { + return SenderAuthResult{Method: SenderAuthMethodSPF, Outcome: "none", Detail: "empty Received-SPF"}, false + } + result := strings.ToLower(strings.TrimSuffix(fields[0], ":")) + envelopeFrom := trimQuoted(receivedSPFProperty(cleaned, "envelope-from")) + if envelopeFrom == "" { + return SenderAuthResult{ + Method: SenderAuthMethodSPF, + Outcome: result, + Detail: "received-spf=" + result + " has no envelope-from (HELO identity is not the sender)", + }, false + } + if result != "pass" { + return SenderAuthResult{ + Method: SenderAuthMethodSPF, + Outcome: result, + Detail: "received-spf=" + result, + }, false + } + domain := emailDomain(envelopeFrom) + if domain != "" && organizationalDomainsAligned(fromDomain, domain) { + return SenderAuthResult{ + Verified: true, + Method: SenderAuthMethodSPF, + Outcome: "pass", + Detail: "received-spf=pass for " + domain, + }, true + } + return SenderAuthResult{ + Method: SenderAuthMethodSPF, + Outcome: "pass", + Detail: "received-spf=pass but not aligned with " + fromDomain, + }, false +} + +// stripAuthenticationComments removes parenthesized comments, which may +// contain spaces, semicolons, and tokens that look like method properties. +func stripAuthenticationComments(value string) string { + var b strings.Builder + b.Grow(len(value)) + depth := 0 + inQuote := false + for i := 0; i < len(value); i++ { + c := value[i] + switch { + case inQuote: + b.WriteByte(c) + switch { + case c == '\\' && i+1 < len(value): + i++ + b.WriteByte(value[i]) + case c == '"': + inQuote = false + } + case depth > 0: + switch { + case c == '\\' && i+1 < len(value): + i++ + case c == '(': + depth++ + case c == ')': + depth-- + } + case c == '"': + inQuote = true + b.WriteByte(c) + case c == '(': + depth++ + default: + b.WriteByte(c) + } + } + return b.String() +} + +// receivedSPFProperty returns a named property from a Received-SPF value. +func receivedSPFProperty(value, key string) string { + for _, clause := range strings.Split(value, ";") { + name, rawValue, ok := strings.Cut(clause, "=") + if !ok { + continue + } + if strings.EqualFold(strings.TrimSpace(name), key) { + return strings.TrimSpace(rawValue) + } + } + return "" +} + +// dkimSigningDomain returns the DKIM signing domain from header.d, falling +// back to the AUID in header.i. +func dkimSigningDomain(props map[string]string) string { + if domain := emailDomain(props["header.d"]); domain != "" { + return domain + } + return emailDomain(props["header.i"]) +} + +// emailDomain extracts the lowercased domain from an address, a bare domain, +// or a DMARC header.from value. It returns "" for a null or malformed value. +func emailDomain(address string) string { + address = strings.TrimSpace(address) + address = strings.Trim(address, "<>\"") + if address == "" { + return "" + } + if open := strings.LastIndex(address, "<"); open >= 0 { + if closeIdx := strings.Index(address[open:], ">"); closeIdx > 0 { + address = address[open+1 : open+closeIdx] + } + } + if at := strings.LastIndex(address, "@"); at >= 0 { + address = address[at+1:] + } + address = strings.Trim(strings.TrimSpace(address), ".") + return strings.ToLower(address) +} + +// organizationalDomain returns the registrable domain of a host using the +// public suffix list, falling back to the host itself for IP literals, single +// labels, and unknown suffixes. +func organizationalDomain(host string) string { + host = normalizeHost(host) + if host == "" { + return "" + } + if org, err := publicsuffix.EffectiveTLDPlusOne(host); err == nil { + return org + } + return host +} + +// organizationalDomainsAligned reports whether two domains share an +// organizational domain, which is DMARC relaxed alignment. +func organizationalDomainsAligned(fromDomain, authenticatedDomain string) bool { + fromOrg := organizationalDomain(fromDomain) + authOrg := organizationalDomain(authenticatedDomain) + return fromOrg != "" && fromOrg == authOrg +} + +// trustedReceiverBoundary returns the position of the first Received header +// whose from/by host is a trusted receiver, or -1 when none exists. A result +// is trusted only when it appears before this position. +func trustedReceiverBoundary(message *ParsedEmail, trustedReceivers []string) int { + if len(message.HeaderOrder) == 0 || len(trustedReceivers) == 0 { + return -1 + } + received := headerValues(message, "Received") + seen := 0 + for i, key := range message.HeaderOrder { + if !strings.EqualFold(key, "Received") { + continue + } + if seen < len(received) && receivedFromTrustedHost(received[seen], trustedReceivers) { + return i + } + seen++ + } + return -1 +} + +// headerValuesAbove returns the values of a header that appear before the +// boundary position in the recorded header order. +func headerValuesAbove(message *ParsedEmail, name string, boundary int) []string { + values := headerValues(message, name) + if len(values) == 0 { + return nil + } + var out []string + seen := 0 + for i, key := range message.HeaderOrder { + if i >= boundary { + break + } + if strings.EqualFold(key, name) { + if seen < len(values) { + out = append(out, values[seen]) + } + seen++ + } + } + return out +} + +// receivedFromTrustedHost reports whether a Received header's from/by host is a +// trusted receiver. +func receivedFromTrustedHost(value string, trustedReceivers []string) bool { + for _, host := range receivedHosts(value) { + for _, trusted := range trustedReceivers { + if hostMatches(host, trusted) { + return true + } + } + } + return false +} + +// receivedHosts extracts the from/by hosts from a Received header. +func receivedHosts(value string) []string { + fields := strings.Fields(value) + var hosts []string + for i, field := range fields { + switch strings.ToLower(strings.TrimSuffix(field, ":")) { + case "from", "by": + if i+1 >= len(fields) { + continue + } + if host := normalizeHost(fields[i+1]); host != "" { + hosts = append(hosts, host) + } + } + } + return hosts +} + +// authServIDTrusted reports whether an Authentication-Results authserv-id is a +// trusted receiver. +func authServIDTrusted(authservID string, trustedReceivers []string) bool { + authservID = normalizeHost(authservID) + if authservID == "" { + return false + } + for _, trusted := range trustedReceivers { + if hostMatches(authservID, trusted) { + return true + } + } + return false +} + +// hostMatches reports whether host equals trusted or is a subdomain of it. +func hostMatches(host, trusted string) bool { + host = normalizeHost(host) + trusted = normalizeHost(trusted) + if host == "" || trusted == "" { + return false + } + return host == trusted || strings.HasSuffix(host, "."+trusted) +} + +// normalizeHost lowercases a host and strips brackets, quotes, and a trailing +// dot. +func normalizeHost(host string) string { + host = strings.TrimSpace(host) + host = strings.Trim(host, "[]()<>\"") + host = strings.TrimSuffix(host, ".") + return strings.ToLower(host) +} + +// normalizeTrustedHosts lowercases and de-duplicates a trusted host list. +func normalizeTrustedHosts(hosts []string) []string { + var out []string + seen := map[string]bool{} + for _, host := range hosts { + host = normalizeHost(host) + if host == "" || seen[host] { + continue + } + seen[host] = true + out = append(out, host) + } + return out +} + +// headerValues returns the values of a header, looked up case-insensitively +// because RawHeaders may come from either IMAP or raw RFC 5322 parsing. +func headerValues(message *ParsedEmail, name string) []string { + if message == nil { + return nil + } + for key, values := range message.RawHeaders { + if strings.EqualFold(key, name) { + return values + } + } + return nil +} + +// firstToken returns the first whitespace-delimited token of a string. +func firstToken(value string) string { + for _, field := range strings.Fields(value) { + return field + } + return "" +} + +// trimQuoted removes surrounding double quotes and whitespace from a value. +func trimQuoted(value string) string { + return strings.Trim(strings.TrimSpace(value), `"`) +} + +// firstNonEmpty returns the first non-empty string. +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return value + } + } + return "" +} diff --git a/internal/email/types.go b/internal/email/types.go index 5082b0341..6063645e1 100644 --- a/internal/email/types.go +++ b/internal/email/types.go @@ -36,6 +36,12 @@ type ParsedEmail struct { HTMLBody string Attachments []Attachment RawHeaders map[string][]string + // HeaderOrder lists the message's header field names in the order they + // appear, duplicates included. It lets sender authentication trust only + // Authentication-Results headers added above the receiving MTA's Received + // header rather than one injected by the sender. Empty when the message was + // not parsed from raw bytes. + HeaderOrder []string } // EmailAddress represents an email address with optional display name @@ -87,6 +93,11 @@ const ( // a new ticket. The tracking row is marked rate_limited_at and the // original mail is left in the mailbox for operator requeue. ActionRateLimited ProcessingAction = "rate_limited" + // ActionHeldForAuth means a strict sender-authentication policy held the + // message: the From address could not be authenticated. The original mail + // is left in the mailbox so an operator can review it after correcting the + // policy or the mailbox configuration. + ActionHeldForAuth ProcessingAction = "held_for_auth" ) // Provider defines the interface for email providers (Microsoft, Google, Generic) diff --git a/internal/email/validation.go b/internal/email/validation.go index 3ebaea464..d58b02e5d 100644 --- a/internal/email/validation.go +++ b/internal/email/validation.go @@ -36,6 +36,9 @@ func ValidateConfigForEnable(channel *models.Channel, config *models.ChannelConf if !IsValidEmailDisposition(config.EmailProcessingDisposition) { return fmt.Errorf("%w: email_processing_disposition must be leave, mark_read, or delete", ErrConfigNotReady) } + if !IsValidSenderAuthPolicy(config.EmailSenderAuthentication) { + return fmt.Errorf("%w: email_sender_authentication must be strict or off", ErrConfigNotReady) + } switch strings.ToLower(config.EmailAuthMethod) { case "oauth": diff --git a/internal/handlers/channel_intakes.go b/internal/handlers/channel_intakes.go index 7f3481a8f..d9c5dc139 100644 --- a/internal/handlers/channel_intakes.go +++ b/internal/handlers/channel_intakes.go @@ -22,6 +22,7 @@ type intakeRequest struct { ItemTypeID *int `json:"item_type_id"` RateLimitPerHour *int `json:"rate_limit_per_hour"` ProcessingDisposition string `json:"processing_disposition"` + SenderAuthentication string `json:"sender_authentication"` SendConfirmation bool `json:"send_confirmation"` ImportExistingMail bool `json:"import_existing_mail"` Status string `json:"status"` @@ -146,6 +147,9 @@ func (h *ChannelHandler) validateIntakeRequest(ctx context.Context, actorID, mai if req.RateLimitPerHour != nil && *req.RateLimitPerHour < 0 { return nil, fmt.Errorf("%w: rate_limit_per_hour must be 0 (unlimited) or a positive number", errIntakeInvalid) } + if !email.IsValidSenderAuthPolicy(req.SenderAuthentication) { + return nil, fmt.Errorf("%w: sender_authentication must be strict or off", errIntakeInvalid) + } status := req.Status if status == "" { status = models.IntakeStatusEnabled @@ -191,6 +195,7 @@ func (h *ChannelHandler) validateIntakeRequest(ctx context.Context, actorID, mai ItemTypeID: req.ItemTypeID, RateLimitPerHour: req.RateLimitPerHour, ProcessingDisposition: req.ProcessingDisposition, + SenderAuthentication: req.SenderAuthentication, SendConfirmation: req.SendConfirmation, ImportExistingMail: req.ImportExistingMail, Status: status, diff --git a/internal/handlers/channels.go b/internal/handlers/channels.go index 81e7ee7b4..dfe54969e 100644 --- a/internal/handlers/channels.go +++ b/internal/handlers/channels.go @@ -2020,6 +2020,8 @@ func (h *ChannelHandler) GetEmailLog(w http.ResponseWriter, r *http.Request) { RateLimitedAt *time.Time `json:"rate_limited_at,omitempty"` WorkspaceKey string `json:"workspace_key,omitempty"` WorkspaceItemNumber int `json:"workspace_item_number,omitempty"` + SenderAuth string `json:"sender_auth,omitempty"` + SkippedReason string `json:"skipped_reason,omitempty"` Redacted bool `json:"redacted,omitempty"` } @@ -2053,6 +2055,8 @@ func (h *ChannelHandler) GetEmailLog(w http.ResponseWriter, r *http.Request) { RateLimitedAt: m.RateLimitedAt, WorkspaceKey: m.WorkspaceKey, WorkspaceItemNumber: m.WorkspaceItemNumber, + SenderAuth: m.SenderAuth, + SkippedReason: m.SkippedReason, } // Redact sender/subject PII for rows whose target workspace the channel // manager can't view. Channel-management permission alone is not enough diff --git a/internal/models/intake.go b/internal/models/intake.go index 962420895..5a26e31ad 100644 --- a/internal/models/intake.go +++ b/internal/models/intake.go @@ -32,6 +32,10 @@ type Intake struct { ItemTypeID *int `json:"item_type_id,omitempty"` RateLimitPerHour *int `json:"rate_limit_per_hour,omitempty"` ProcessingDisposition string `json:"processing_disposition,omitempty"` + // SenderAuthentication overrides the mailbox's inbound sender-authentication + // policy for this intake. Empty inherits the mailbox default; see + // ChannelConfig.EmailSenderAuthentication. + SenderAuthentication string `json:"sender_authentication,omitempty"` // SendConfirmation emails the sender a receipt when this intake creates a // new item. Off by default. SendConfirmation bool `json:"send_confirmation"` diff --git a/internal/models/portal.go b/internal/models/portal.go index d92e9372a..9e0a271b7 100644 --- a/internal/models/portal.go +++ b/internal/models/portal.go @@ -165,6 +165,17 @@ type ChannelConfig struct { // (DefaultEmailRateLimitPerHour), 0 = unlimited, n = n. Replies to // existing threads are never rate-limited. EmailRateLimitPerHour *int `json:"email_rate_limit_per_hour,omitempty"` + // EmailSenderAuthentication is the mailbox default policy for trusting the + // inbound From address. "strict" (the default when empty) holds mail whose + // From domain does not pass an aligned SPF, DKIM, or DMARC check; "off" + // disables the check for providers that do not add authentication headers. + EmailSenderAuthentication string `json:"email_sender_authentication,omitempty"` + // EmailTrustedAuthServIDs lists the authentication servers (authserv-id) + // whose Authentication-Results / Received-SPF headers this mailbox trusts. + // They are the receiver boundary that proves a result was added by the + // delivering MTA. Empty derives the hosts from the provider and mail host; + // when nothing can be derived, strict mode holds every message. + EmailTrustedAuthServIDs []string `json:"email_trusted_authserv_ids,omitempty"` // Portal Configuration PortalSlug string `json:"portal_slug,omitempty"` // URL-friendly identifier (e.g., "support-portal") diff --git a/internal/repository/channel_repository.go b/internal/repository/channel_repository.go index f268b476c..f3bbcdbc6 100644 --- a/internal/repository/channel_repository.go +++ b/internal/repository/channel_repository.go @@ -1094,6 +1094,13 @@ type EmailMessageRow struct { WorkspaceID *int WorkspaceItemNumber int WorkspaceKey string + // SenderAuth is the SPF/DKIM/DMARC outcome recorded for the message, e.g. + // "dmarc=pass" or "none". Empty for rows written before the check existed. + SenderAuth string + // SkippedReason is set when intake deliberately did not turn the message + // into an item or comment, e.g. "unauthenticated_sender". Empty for mail + // that was processed normally. + SkippedReason string } // CountEmailMessages returns the number of email_message_tracking rows for a @@ -1127,7 +1134,7 @@ func (r *ChannelRepository) ListEmailMessages(ctx context.Context, channelID int queryArgs = append(queryArgs, pageSize, offset) rows, err := r.db.QueryContext(ctx, - "SELECT emt.id, emt.from_email, emt.from_name, COALESCE(emt.subject, ''), emt.item_id, emt.comment_id, emt.processed_at, emt.rate_limited_at, i.workspace_item_number, i.workspace_id, w.key as workspace_key "+ + "SELECT emt.id, emt.from_email, emt.from_name, COALESCE(emt.subject, ''), emt.item_id, emt.comment_id, emt.processed_at, emt.rate_limited_at, COALESCE(emt.sender_auth, ''), COALESCE(emt.skipped_reason, ''), i.workspace_item_number, i.workspace_id, w.key as workspace_key "+ "FROM email_message_tracking emt "+ "LEFT JOIN items i ON emt.item_id = i.id "+ "LEFT JOIN workspaces w ON i.workspace_id = w.id "+ @@ -1146,7 +1153,7 @@ func (r *ChannelRepository) ListEmailMessages(ctx context.Context, channelID int var itemID, commentID, workspaceID, workspaceItemNumber sql.NullInt64 var fromName, workspaceKey sql.NullString var rateLimitedAt sql.NullTime - if err := rows.Scan(&msg.ID, &msg.FromEmail, &fromName, &msg.Subject, &itemID, &commentID, &msg.ProcessedAt, &rateLimitedAt, &workspaceItemNumber, &workspaceID, &workspaceKey); err != nil { + if err := rows.Scan(&msg.ID, &msg.FromEmail, &fromName, &msg.Subject, &itemID, &commentID, &msg.ProcessedAt, &rateLimitedAt, &msg.SenderAuth, &msg.SkippedReason, &workspaceItemNumber, &workspaceID, &workspaceKey); err != nil { return nil, fmt.Errorf("scan email_message_tracking row: %w", err) } if fromName.Valid { @@ -1195,6 +1202,7 @@ func emailMessageWhere(channelID int, search string) (whereClause string, args [ // CountRateLimitedEmails returns how many tracking rows for a channel were // declined by per-sender flood protection and are awaiting operator requeue. +// Sender-authentication holds are a separate outcome and are not counted here. func (r *ChannelRepository) CountRateLimitedEmails(ctx context.Context, channelID int) (int, error) { var total int if err := r.db.QueryRowContext(ctx, @@ -1206,17 +1214,22 @@ func (r *ChannelRepository) CountRateLimitedEmails(ctx context.Context, channelI return total, nil } -// SystemMailRow is a machine-generated inbound message that intake -// deliberately did not turn into a ticket (bounce or auto-reply). +// SystemMailRow is an inbound message intake deliberately did not turn into a +// ticket: machine-generated mail (bounce or auto-reply) or, under a strict +// sender-authentication policy, mail whose From address could not be +// authenticated. type SystemMailRow struct { - ID int `json:"id"` - ChannelID int `json:"channel_id"` - ChannelName string `json:"channel_name"` - IntakeID *int `json:"intake_id,omitempty"` - FromEmail string `json:"from_email"` - FromName string `json:"from_name"` - Subject string `json:"subject"` - Category string `json:"category"` + ID int `json:"id"` + ChannelID int `json:"channel_id"` + ChannelName string `json:"channel_name"` + IntakeID *int `json:"intake_id,omitempty"` + FromEmail string `json:"from_email"` + FromName string `json:"from_name"` + Subject string `json:"subject"` + Category string `json:"category"` + // SenderAuth is the SPF/DKIM/DMARC outcome that led to the skip, when the + // skip was a sender-authentication hold. + SenderAuth string `json:"sender_auth,omitempty"` ProcessedAt time.Time `json:"processed_at"` } @@ -1236,7 +1249,7 @@ func (r *ChannelRepository) ListSystemMail(ctx context.Context, since time.Time, rows, err := r.db.QueryContext(ctx, ` SELECT emt.id, emt.channel_id, c.name, emt.intake_id, emt.from_email, COALESCE(emt.from_name, ''), COALESCE(emt.subject, ''), - emt.skipped_reason, emt.processed_at + emt.skipped_reason, COALESCE(emt.sender_auth, ''), emt.processed_at FROM email_message_tracking emt JOIN channels c ON c.id = emt.channel_id WHERE emt.skipped_reason IS NOT NULL AND emt.processed_at >= ? @@ -1253,7 +1266,7 @@ func (r *ChannelRepository) ListSystemMail(ctx context.Context, since time.Time, var row SystemMailRow var intakeID sql.NullInt64 if err := rows.Scan(&row.ID, &row.ChannelID, &row.ChannelName, &intakeID, &row.FromEmail, - &row.FromName, &row.Subject, &row.Category, &row.ProcessedAt); err != nil { + &row.FromName, &row.Subject, &row.Category, &row.SenderAuth, &row.ProcessedAt); err != nil { return nil, fmt.Errorf("scan skipped system mail row: %w", err) } if intakeID.Valid { diff --git a/internal/repository/intake_repository.go b/internal/repository/intake_repository.go index 54ad10102..87bda73ad 100644 --- a/internal/repository/intake_repository.go +++ b/internal/repository/intake_repository.go @@ -25,7 +25,7 @@ func NewIntakeRepository(db database.Database) *IntakeRepository { const intakeSelectColumns = ` i.id, i.mailbox_id, i.folder, i.workspace_id, i.portal_channel_id, i.request_type_id, i.item_type_id, i.rate_limit_per_hour, - i.processing_disposition, i.send_confirmation, i.import_existing_mail, i.status, i.status_reason, i.created_at, i.updated_at, + i.processing_disposition, i.sender_authentication, i.send_confirmation, i.import_existing_mail, i.status, i.status_reason, i.created_at, i.updated_at, COALESCE(c.name, '') AS mailbox_name, COALESCE(s.last_uid, 0), COALESCE(s.uid_validity, 0), s.updated_at, COALESCE(( @@ -47,7 +47,7 @@ func scanIntake(scanner interface { if err := scanner.Scan( &in.ID, &in.MailboxID, &in.Folder, &in.WorkspaceID, &portalChannelID, &requestTypeID, &itemTypeID, &rateLimit, - &in.ProcessingDisposition, &in.SendConfirmation, &in.ImportExistingMail, &in.Status, &in.StatusReason, &in.CreatedAt, &in.UpdatedAt, + &in.ProcessingDisposition, &in.SenderAuthentication, &in.SendConfirmation, &in.ImportExistingMail, &in.Status, &in.StatusReason, &in.CreatedAt, &in.UpdatedAt, &in.MailboxName, &in.LastUID, &in.UIDValidity, &lastPolledAt, &in.RateLimitedCount, ); err != nil { @@ -246,10 +246,10 @@ func (r *IntakeRepository) Create(ctx context.Context, in *models.Intake) (int, err := r.db.QueryRowContext(ctx, ` INSERT INTO intakes ( mailbox_id, folder, workspace_id, portal_channel_id, request_type_id, item_type_id, - rate_limit_per_hour, processing_disposition, send_confirmation, import_existing_mail, status, status_reason, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id + rate_limit_per_hour, processing_disposition, sender_authentication, send_confirmation, import_existing_mail, status, status_reason, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id `, in.MailboxID, folder, in.WorkspaceID, in.PortalChannelID, in.RequestTypeID, in.ItemTypeID, - in.RateLimitPerHour, in.ProcessingDisposition, in.SendConfirmation, in.ImportExistingMail, status, in.StatusReason, now, now).Scan(&id) + in.RateLimitPerHour, in.ProcessingDisposition, in.SenderAuthentication, in.SendConfirmation, in.ImportExistingMail, status, in.StatusReason, now, now).Scan(&id) if err != nil { if database.IsUniqueConstraintError(err) { return 0, ErrDuplicateEntry @@ -268,10 +268,10 @@ func (r *IntakeRepository) Update(ctx context.Context, in *models.Intake) error res, err := r.db.ExecWriteContext(ctx, ` UPDATE intakes SET folder = ?, workspace_id = ?, portal_channel_id = ?, request_type_id = ?, item_type_id = ?, - rate_limit_per_hour = ?, processing_disposition = ?, send_confirmation = ?, import_existing_mail = ?, status = ?, status_reason = ?, updated_at = ? + rate_limit_per_hour = ?, processing_disposition = ?, sender_authentication = ?, send_confirmation = ?, import_existing_mail = ?, status = ?, status_reason = ?, updated_at = ? WHERE id = ? `, folder, in.WorkspaceID, in.PortalChannelID, in.RequestTypeID, in.ItemTypeID, - in.RateLimitPerHour, in.ProcessingDisposition, in.SendConfirmation, in.ImportExistingMail, in.Status, in.StatusReason, time.Now(), in.ID) + in.RateLimitPerHour, in.ProcessingDisposition, in.SenderAuthentication, in.SendConfirmation, in.ImportExistingMail, in.Status, in.StatusReason, time.Now(), in.ID) if err != nil { if database.IsUniqueConstraintError(err) { return ErrDuplicateEntry diff --git a/internal/scheduler/email_scheduler.go b/internal/scheduler/email_scheduler.go index 600e1d914..0d0eac38c 100644 --- a/internal/scheduler/email_scheduler.go +++ b/internal/scheduler/email_scheduler.go @@ -432,6 +432,7 @@ func legacyIntakeFromConfig(config *models.ChannelConfig) *models.Intake { ItemTypeID: config.EmailItemTypeID, RateLimitPerHour: config.EmailRateLimitPerHour, ProcessingDisposition: config.EmailProcessingDisposition, + SenderAuthentication: config.EmailSenderAuthentication, Status: models.IntakeStatusEnabled, } } @@ -463,6 +464,11 @@ func (es *EmailScheduler) pollIntake( if intake.ProcessingDisposition != "" { effective.EmailProcessingDisposition = intake.ProcessingDisposition } + // Likewise an empty sender-authentication policy inherits the mailbox + // default, whose own empty value is strict. + if intake.SenderAuthentication != "" { + effective.EmailSenderAuthentication = intake.SenderAuthentication + } mailbox := intake.Folder if mailbox == "" { @@ -518,6 +524,7 @@ func (es *EmailScheduler) pollIntake( maxUID := sinceUID processedCount := 0 rateLimitedCount := 0 + heldCount := 0 errorCount := 0 var lastBatchError string var offenderUID uint32 @@ -575,11 +582,15 @@ func (es *EmailScheduler) pollIntake( // Rate-limited mail is left untouched in the mailbox (unread, not // deleted) so an operator can requeue it; the watermark still advances - // past it so one flooding sender cannot wedge the intake. Deduplicated - // mail still gets the configured disposition: an earlier run may have - // created the ticket but expired before marking or deleting it. + // past it so one flooding sender cannot wedge the intake. Mail held by a + // strict sender-authentication policy is preserved the same way: it may + // be the only copy of a legitimate message, and deleting it would make + // the hold unrecoverable. Deduplicated mail still gets the configured + // disposition: an earlier run may have created the ticket but expired + // before marking or deleting it. rateLimited := result.Action == email.ActionRateLimited - if !rateLimited { + held := result.Action == email.ActionHeldForAuth + if !rateLimited && !held { switch disposition { case models.EmailDispositionMarkRead: if markErr := client.MarkAsRead(msg.UID); markErr != nil { @@ -595,9 +606,12 @@ func (es *EmailScheduler) pollIntake( if msg.UID > maxUID { maxUID = msg.UID } - if rateLimited { + switch { + case rateLimited: rateLimitedCount++ - } else { + case held: + heldCount++ + default: processedCount++ } } @@ -637,6 +651,7 @@ func (es *EmailScheduler) pollIntake( "intake_id", intake.ID, "processed", processedCount, "rate_limited", rateLimitedCount, + "held_for_auth", heldCount, "errors", errorCount, )