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/locales/de/backfill.js b/frontend/src/lib/locales/de/backfill.js index 2cf8b572b..b0b4fa7f6 100644 --- a/frontend/src/lib/locales/de/backfill.js +++ b/frontend/src/lib/locales/de/backfill.js @@ -98,6 +98,7 @@ export default { "outboxStatus": "Status", "outboxTo": "An", "rateLimited": "Ratenbegrenzt", + "heldUnauthenticated": "Zurückgehalten: nicht authentifizierter Absender", "rateLimitedCount": "{count} Nachricht(en) durch das Absender-Ratenlimit zurückgehalten und warten auf erneute Einreihung.", "requeue": "Erneut einreihen und wiederholen", "requeueing": "Wird erneut eingereiht...", diff --git a/frontend/src/lib/locales/en/channels.js b/frontend/src/lib/locales/en/channels.js index 9ffd297cf..083aedf57 100644 --- a/frontend/src/lib/locales/en/channels.js +++ b/frontend/src/lib/locales/en/channels.js @@ -394,6 +394,7 @@ export default { next: 'Next', page: 'Page {page} of {total}', rateLimited: 'Rate limited', + heldUnauthenticated: 'Held: unauthenticated sender', rateLimitedCount: '{count} message(s) held back by the per-sender rate limit and waiting for requeue.', requeue: 'Requeue and retry', requeueing: 'Requeueing...', diff --git a/frontend/src/lib/locales/fa/channels.js b/frontend/src/lib/locales/fa/channels.js index 7f294f7e2..01092a209 100644 --- a/frontend/src/lib/locales/fa/channels.js +++ b/frontend/src/lib/locales/fa/channels.js @@ -362,6 +362,7 @@ export default { "next": "بعدی", "page": "صفحه {page} از {total}", "rateLimited": "نرخ محدود", + "heldUnauthenticated": "نگه‌داشته شد: فرستنده تأیید نشده", "rateLimitedCount": "{count} پیام به‌دلیل محدودیت نرخ هر فرستنده متوقف شده و در انتظار بازگردانی به صف است.", "requeue": "بازگردانی به صف و تلاش مجدد", "requeueing": "در حال بازگردانی به صف...", diff --git a/frontend/src/lib/locales/fr/backfill.js b/frontend/src/lib/locales/fr/backfill.js index ada5398b3..a0eef4600 100644 --- a/frontend/src/lib/locales/fr/backfill.js +++ b/frontend/src/lib/locales/fr/backfill.js @@ -126,6 +126,7 @@ export default { "outboxStatus": "Statut", "outboxTo": "À", "rateLimited": "Limité en débit", + "heldUnauthenticated": "Retenu : expéditeur non authentifié", "rateLimitedCount": "{count} message(s) retenue(s) par la limite de débit par expéditeur et en attente de remise en file.", "requeue": "Remettre en file et réessayer", "requeueing": "Remise en file...", diff --git a/frontend/src/lib/locales/nl/channels.js b/frontend/src/lib/locales/nl/channels.js index 438495099..78c8b3706 100644 --- a/frontend/src/lib/locales/nl/channels.js +++ b/frontend/src/lib/locales/nl/channels.js @@ -394,6 +394,7 @@ export default { next: 'Volgende', page: 'Pagina {page} van {total}', rateLimited: 'Limiet bereikt', + heldUnauthenticated: 'Tegenhouden: niet-geverifieerde afzender', rateLimitedCount: '{count} bericht(en) tegengehouden door de limiet per afzender en wachtend op herplaatsing.', requeue: 'Herplaatsen en opnieuw proberen', requeueing: 'Herplaatsen...', diff --git a/frontend/src/lib/locales/pl/channels.js b/frontend/src/lib/locales/pl/channels.js index 4d4157a51..12840ff4d 100644 --- a/frontend/src/lib/locales/pl/channels.js +++ b/frontend/src/lib/locales/pl/channels.js @@ -398,6 +398,7 @@ export default { next: 'Następna', page: 'Strona {page} z {total}', rateLimited: 'Limit tempa', + heldUnauthenticated: 'Wstrzymano: nieuwierzytelniony nadawca', rateLimitedCount: '{count} wiadomości wstrzymanych przez limit tempa na nadawcę i oczekujących na ponowne zakolejkowanie.', requeue: 'Zakolejkuj ponownie i spróbuj ponownie', requeueing: 'Ponowne kolejkuje...', diff --git a/frontend/src/lib/locales/ru/channels.js b/frontend/src/lib/locales/ru/channels.js index 098e224bc..4a5fdc72f 100644 --- a/frontend/src/lib/locales/ru/channels.js +++ b/frontend/src/lib/locales/ru/channels.js @@ -382,6 +382,7 @@ export default { next: 'Далее', page: 'Страница {page} из {total}', rateLimited: 'Превышен лимит', + heldUnauthenticated: 'Задержано: отправитель не аутентифицирован', rateLimitedCount: 'Сообщений, отложенных лимитом отправителя и ожидающих повторной постановки в очередь: {count}.', requeue: 'Вернуть в очередь и повторить', requeueing: 'Возврат в очередь…', diff --git a/frontend/src/lib/locales/zh-CN/backfill.js b/frontend/src/lib/locales/zh-CN/backfill.js index 685cf5033..13d1814b1 100644 --- a/frontend/src/lib/locales/zh-CN/backfill.js +++ b/frontend/src/lib/locales/zh-CN/backfill.js @@ -98,6 +98,7 @@ export default { "outboxStatus": "状态", "outboxTo": "收件人", "rateLimited": "已限流", + "heldUnauthenticated": "已暂扣:发件人未通过身份验证", "rateLimitedCount": "{count} 条消息因发件人速率限制被扣留,等待重新入队。", "requeue": "重新入队并重试", "requeueing": "正在重新入队...", diff --git a/frontend/src/lib/settings/diagnostics/EmailIntakeSection.svelte b/frontend/src/lib/settings/diagnostics/EmailIntakeSection.svelte index 2f5d6f4d6..33c373800 100644 --- a/frontend/src/lib/settings/diagnostics/EmailIntakeSection.svelte +++ b/frontend/src/lib/settings/diagnostics/EmailIntakeSection.svelte @@ -16,6 +16,7 @@ const CATEGORY_LABELS = { delivery_failure: 'Delivery failure', auto_reply: 'Auto-reply', + unauthenticated_sender: 'Unauthenticated sender', }; let window = $state('24h'); @@ -45,13 +46,14 @@ } function categoryVariant(category) { - return category === 'delivery_failure' ? 'danger' : 'neutral'; + if (category === 'delivery_failure') return 'danger'; + return category === 'unauthenticated_sender' ? 'warning' : 'neutral'; }
- {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..b68b25fc0 100644 --- a/internal/database/migrations.go +++ b/internal/database/migrations.go @@ -3727,6 +3727,65 @@ 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 ''; + `, + }, + { + // WI-2365: only a recipient-bound outbound Message-ID may authorize an + // email reply. key_generation marks rows issued under that scheme (>= 1); + // pre-upgrade rows default to 0 and never authorize. The marker lives on + // the tracking row too so it survives outbox pruning. contact_email/ + // contact_name keep an unverified inbound sender off the customer's + // portal identity until a reply key proves control of the address. + Version: "20261205_email_reply_keys", + Name: "Recipient-bound reply keys and unverified email contacts (WI-2365)", + CheckSQLite: "SELECT CASE WHEN (" + sqliteColumnCheck("email_reply_outbox", "key_generation") + + ") > 0 AND (" + sqliteColumnCheck("email_message_tracking", "key_generation") + + ") > 0 AND (" + sqliteColumnCheck("items", "contact_email") + + ") > 0 AND (" + sqliteIndexCheck("idx_email_reply_outbox_message_id") + ") > 0 THEN 1 ELSE 0 END", + CheckPostgres: "SELECT CASE WHEN (" + pgColumnCheck("email_reply_outbox", "key_generation") + + ") > 0 AND (" + pgColumnCheck("email_message_tracking", "key_generation") + + ") > 0 AND (" + pgColumnCheck("items", "contact_email") + + ") > 0 AND (" + pgIndexCheck("idx_email_reply_outbox_message_id") + ") > 0 THEN 1 ELSE 0 END", + SQLite: ` + ALTER TABLE email_reply_outbox ADD COLUMN key_generation INTEGER NOT NULL DEFAULT 0; + ALTER TABLE email_message_tracking ADD COLUMN key_generation INTEGER NOT NULL DEFAULT 0; + ALTER TABLE items ADD COLUMN contact_email TEXT; + ALTER TABLE items ADD COLUMN contact_name TEXT; + CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_message_id ON email_reply_outbox(message_id); + CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_item_created ON email_reply_outbox(item_id, created_at); + CREATE INDEX IF NOT EXISTS idx_email_message_tracking_key_generation ON email_message_tracking(key_generation); + `, + Postgres: ` + ALTER TABLE email_reply_outbox ADD COLUMN IF NOT EXISTS key_generation INTEGER NOT NULL DEFAULT 0; + ALTER TABLE email_message_tracking ADD COLUMN IF NOT EXISTS key_generation INTEGER NOT NULL DEFAULT 0; + ALTER TABLE items ADD COLUMN IF NOT EXISTS contact_email TEXT; + ALTER TABLE items ADD COLUMN IF NOT EXISTS contact_name TEXT; + CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_message_id ON email_reply_outbox(message_id); + CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_item_created ON email_reply_outbox(item_id, created_at); + CREATE INDEX IF NOT EXISTS idx_email_message_tracking_key_generation ON email_message_tracking(key_generation); + `, + }, } // domainEventClaimableIndexMigration adds the partial index the claim query diff --git a/internal/database/schema/email.sql b/internal/database/schema/email.sql index a74e3acd3..c928fbfd6 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', @@ -122,6 +125,11 @@ CREATE TABLE IF NOT EXISTS email_message_tracking ( subject TEXT, item_id INTEGER, comment_id INTEGER, + -- key_generation marks the reply-key scheme that issued an outbound + -- Message-ID: 1 is the recipient-bound scheme (WI-2365), 0 is a + -- pre-upgrade row. Only generation >= 1 authorizes a reply, and the marker + -- survives outbox pruning so a pruned key can never become valid again. + key_generation INTEGER NOT NULL DEFAULT 0, -- attachments_status records whether the email's attachments survived -- processing. NULL = no attachments / not yet computed. 'ok' = all stored. -- 'partial' = some stored, some dropped due to fatal write/insert errors @@ -142,11 +150,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, @@ -155,6 +170,7 @@ CREATE TABLE IF NOT EXISTS email_message_tracking ( CREATE INDEX IF NOT EXISTS idx_email_message_tracking_channel_id ON email_message_tracking(channel_id); CREATE INDEX IF NOT EXISTS idx_email_message_tracking_message_id ON email_message_tracking(message_id); +CREATE INDEX IF NOT EXISTS idx_email_message_tracking_key_generation ON email_message_tracking(key_generation); CREATE INDEX IF NOT EXISTS idx_email_message_tracking_in_reply_to ON email_message_tracking(in_reply_to); CREATE UNIQUE INDEX IF NOT EXISTS idx_email_message_tracking_dedup ON email_message_tracking(channel_id, dedup_key); CREATE INDEX IF NOT EXISTS idx_email_message_tracking_sender ON email_message_tracking(from_email); @@ -179,6 +195,8 @@ CREATE TABLE IF NOT EXISTS email_reply_outbox ( html_body TEXT NOT NULL, text_body TEXT NOT NULL, message_id TEXT NOT NULL, + -- key_generation: see email_message_tracking for the reply-key contract. + key_generation INTEGER NOT NULL DEFAULT 0, in_reply_to TEXT NOT NULL DEFAULT '', references_json TEXT NOT NULL DEFAULT '[]', from_email TEXT NOT NULL, @@ -207,6 +225,13 @@ CREATE TABLE IF NOT EXISTS email_reply_outbox ( CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_pending ON email_reply_outbox(delivered_at, next_attempt_at); +-- Reply-key lookup by Message-ID and thread assembly by item. Without these, +-- every inbound reply scans the retained outbox. +CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_message_id + ON email_reply_outbox(message_id); +CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_item_created + ON email_reply_outbox(item_id, created_at); + -- One outbound reply per comment recipient (WI-1136): the creator plus every -- external request participant gets their own row. CREATE UNIQUE INDEX IF NOT EXISTS uq_email_reply_outbox_comment_recipient diff --git a/internal/database/schema/email_postgres.sql b/internal/database/schema/email_postgres.sql index 206cc86b9..dce6fa66a 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', @@ -110,6 +112,8 @@ CREATE TABLE IF NOT EXISTS email_message_tracking ( subject TEXT, item_id INTEGER, comment_id INTEGER, + -- key_generation: see email.sql for the reply-key contract. + key_generation INTEGER NOT NULL DEFAULT 0, -- attachments_status: see email.sql for the column contract. attachments_status TEXT CHECK(attachments_status IN ('ok','partial','failed') OR attachments_status IS NULL), direction TEXT DEFAULT 'inbound' CHECK(direction IN ('inbound', 'outbound')), @@ -118,8 +122,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, @@ -128,6 +133,7 @@ CREATE TABLE IF NOT EXISTS email_message_tracking ( CREATE INDEX IF NOT EXISTS idx_email_message_tracking_channel_id ON email_message_tracking(channel_id); CREATE INDEX IF NOT EXISTS idx_email_message_tracking_message_id ON email_message_tracking(message_id); +CREATE INDEX IF NOT EXISTS idx_email_message_tracking_key_generation ON email_message_tracking(key_generation); CREATE INDEX IF NOT EXISTS idx_email_message_tracking_in_reply_to ON email_message_tracking(in_reply_to); CREATE UNIQUE INDEX IF NOT EXISTS idx_email_message_tracking_dedup ON email_message_tracking(channel_id, dedup_key); CREATE INDEX IF NOT EXISTS idx_email_message_tracking_sender ON email_message_tracking(from_email); @@ -150,6 +156,8 @@ CREATE TABLE IF NOT EXISTS email_reply_outbox ( html_body TEXT NOT NULL, text_body TEXT NOT NULL, message_id TEXT NOT NULL, + -- key_generation: see email.sql for the reply-key contract. + key_generation INTEGER NOT NULL DEFAULT 0, in_reply_to TEXT NOT NULL DEFAULT '', references_json TEXT NOT NULL DEFAULT '[]', from_email TEXT NOT NULL, @@ -176,6 +184,12 @@ CREATE TABLE IF NOT EXISTS email_reply_outbox ( CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_pending ON email_reply_outbox(delivered_at, next_attempt_at); +-- Reply-key lookup by Message-ID and thread assembly by item. +CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_message_id + ON email_reply_outbox(message_id); +CREATE INDEX IF NOT EXISTS idx_email_reply_outbox_item_created + ON email_reply_outbox(item_id, created_at); + -- One outbound reply per comment recipient (WI-1136). CREATE UNIQUE INDEX IF NOT EXISTS uq_email_reply_outbox_comment_recipient ON email_reply_outbox(comment_id, to_email) diff --git a/internal/database/schema/items.sql b/internal/database/schema/items.sql index 35540e1b4..429ccfed0 100644 --- a/internal/database/schema/items.sql +++ b/internal/database/schema/items.sql @@ -16,6 +16,12 @@ CREATE TABLE IF NOT EXISTS items ( creator_id INTEGER REFERENCES users(id) ON DELETE SET NULL, reporter_id INTEGER REFERENCES users(id) ON DELETE SET NULL, creator_portal_customer_id INTEGER REFERENCES portal_customers(id) ON DELETE SET NULL, + -- Unverified contact recorded for an inbound email before its sender proved + -- control of the address. Kept separate from creator_portal_customer_id so + -- a claimed From cannot make the item appear in a customer's portal or + -- organisation sharing (WI-2365). Cleared when the contact is verified. + contact_email TEXT, + contact_name TEXT, custom_field_values TEXT, virtual_field_data TEXT, calendar_data TEXT, diff --git a/internal/database/schema/items_postgres.sql b/internal/database/schema/items_postgres.sql index f49f0b3c6..562438bc3 100644 --- a/internal/database/schema/items_postgres.sql +++ b/internal/database/schema/items_postgres.sql @@ -16,6 +16,9 @@ CREATE TABLE IF NOT EXISTS items ( creator_id INTEGER, reporter_id INTEGER, creator_portal_customer_id INTEGER, + -- contact_email/contact_name: see items.sql for the unverified-contact contract. + contact_email TEXT, + contact_name TEXT, custom_field_values JSONB, virtual_field_data TEXT, calendar_data TEXT, 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..0fce4e1d9 100644 --- a/internal/email/processor.go +++ b/internal/email/processor.go @@ -152,17 +152,19 @@ func (p *Processor) ProcessEmailWithIntake( }, nil } - // 2. Find or create portal customer by email - customerID, err := p.findOrCreatePortalCustomer(ctx, email.From.Address, email.From.Name, channelID, config) - if err != nil { - p.releaseTrackingClaim(ctx, channelID, dedupKey) - return nil, fmt.Errorf("failed to find/create portal customer: %w", err) - } - - // 3. Check if this is a reply (find parent item by In-Reply-To/References). - // Matching is item-scoped on purpose: a reply quoting a portal ticket's - // Message-IDs lands on the email channel while the ticket lives on the - // portal channel (WI-1546). The participant guard is the security boundary. + // 1c. Record the receiving provider's authentication outcome for the admin + // diagnostics view. Intake does not gate on SPF/DKIM/DMARC (WI-2365): + // filtering belongs to the receiving provider, and the claimed From is + // never trusted as an identity regardless of the verdict. + p.recordSenderAuth(ctx, channelID, dedupKey, EvaluateSenderAuthentication(email, ResolveTrustedAuthServIDs(config))) + + // 1d. Authorize the reply before any customer or access side effect. A + // reply may append to an existing private request only when it references a + // Windshift-issued outbound Message-ID whose intended recipient is the + // claimed sender, and that sender is still authorized (WI-2365). A + // customer-generated inbound ID, a legacy thread reference, a missing + // header, or a prior unverified sender never authorizes, so those messages + // start a separate staff-visible request instead. var parentItemID *int if email.IsReply() { parentItemID = p.findParentItem(ctx, email) @@ -180,6 +182,23 @@ func (p *Processor) ProcessEmailWithIntake( return &ProcessingResult{Action: ActionRateLimited}, nil } + // 2. Only an authorized reply has proven the sender controls the address + // Windshift wrote to. Resolve them to a portal customer and restore access; + // a new request records an unverified contact on the item instead and never + // acquires a portal owner from the claimed From. + var customerID int + if parentItemID != nil { + customerID, err = p.findOrCreatePortalCustomer(ctx, email.From.Address, email.From.Name, channelID, config) + if err != nil { + p.releaseTrackingClaim(ctx, channelID, dedupKey) + return nil, fmt.Errorf("failed to find/create portal customer: %w", err) + } + if err := p.grantChannelAccess(ctx, customerID, channelID, email.From.Address, config); err != nil { + p.releaseTrackingClaim(ctx, channelID, dedupKey) + return nil, fmt.Errorf("grant customer access for authorized reply: %w", err) + } + } + // 4. Create item or add comment var result *ProcessingResult if parentItemID != nil { @@ -187,7 +206,7 @@ func (p *Processor) ProcessEmailWithIntake( result, err = p.addCommentFromReply(ctx, email, *parentItemID, customerID) } else { // This is a new conversation - create item - result, err = p.createItemFromEmail(ctx, email, channelID, config, customerID, intakeID) + result, err = p.createItemFromEmail(ctx, email, channelID, config, intakeID) } if err != nil { @@ -195,7 +214,10 @@ func (p *Processor) ProcessEmailWithIntake( return nil, err } - result.CustomerID = &customerID + if parentItemID != nil { + result.CustomerID = &customerID + p.linkVerifiedContact(ctx, *parentItemID, customerID, email.From.Address) + } // 5. Finalize tracking with the created item/comment ID. If this UPDATE // fails the item still exists and the preclaim row continues to block @@ -370,13 +392,30 @@ func (p *Processor) markSystemMailSkipped(ctx context.Context, channelID int, de } } +// 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. It is diagnostic only: intake no longer gates on the +// verdict (WI-2365). 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()) + } +} + // findOrCreatePortalCustomer resolves the sender to a portal customer by -// email, creating one on first contact, and grants channel access. +// email, creating one on first contact. It records a contact address only: +// portal access is granted separately, and only after an authorized reply has +// proven the sender controls the address Windshift wrote to (WI-2365). func (p *Processor) findOrCreatePortalCustomer( ctx context.Context, email, name string, - channelID int, - config *models.ChannelConfig, + _ int, + _ *models.ChannelConfig, ) (int, error) { email = strings.ToLower(strings.TrimSpace(email)) name = strings.TrimSpace(name) @@ -396,10 +435,6 @@ func (p *Processor) findOrCreatePortalCustomer( if created { slog.Info("created portal customer from email", "customer_id", customerID, "email", email) } - - if err := p.grantChannelAccess(ctx, customerID, channelID, email, config); err != nil { - return 0, err - } return customerID, nil } @@ -500,90 +535,183 @@ func (p *Processor) connectedPortalAdmitsEmail(ctx context.Context, portalChanne return true } -// findParentItem looks up the original item from In-Reply-To or References headers. -// -// Matching is item-scoped across channels: Message-IDs are globally unique, -// and a conversation must survive its customer switching channels (portal -// ticket, reply by email). Channel scoping would permanently silo the -// customer's reply on the intake channel (WI-1547). +// findAuthorizedReplyParent returns the item a reply is allowed to append to. // -// Thread-hijack defense: the In-Reply-To / References headers are entirely -// attacker-controlled. If we trusted them naively, anyone who leaks or guesses -// a Message-ID used anywhere could post a "reply" onto that item from a new -// email address, exposing private conversations to a third party. The -// participant guard is the security boundary: we match only when the sender is -// demonstrably part of the item's conversation — a prior participant on its -// tracked thread (any channel) or the original creator via the portal-customer -// linkage. -func (p *Processor) findParentItem(ctx context.Context, email *ParsedEmail) *int { - threadIDs := email.GetThreadIDs() +// Authorization is a Windshift-issued, recipient-bound outbound Message-ID: +// the reply must reference it through In-Reply-To/References, and the claimed +// sender must be its intended recipient and still be the item's creator or an +// active external participant. Those headers are attacker-controlled, so an +// inbound (customer-generated) ID, a legacy thread reference, a missing +// header, or a prior unverified sender never authorizes: those replies start a +// separate staff-visible request instead of touching the private conversation +// (WI-2365). +func (p *Processor) findAuthorizedReplyParent(ctx context.Context, email *ParsedEmail) (int, bool) { senderEmail := normalizedEmail(email.From.Address) - - for _, messageID := range threadIDs { - var itemID int + if senderEmail == "" { + return 0, false + } + for _, messageID := range email.GetThreadIDs() { canonicalID := canonicalMessageID(messageID) - bareID := bareMessageID(messageID) if canonicalID == "" { continue } - err := p.db.QueryRowContext(ctx, ` - SELECT item_id FROM email_message_tracking - WHERE message_id IN (?, ?) AND item_id IS NOT NULL - `, canonicalID, bareID).Scan(&itemID) - if err != nil { - continue + itemID, recipient, ok := p.lookupReplyKey(ctx, canonicalID) + if ok { + if normalizedEmail(recipient) != senderEmail { + slog.Warn("ignoring reply: reply key belongs to another recipient", + "item_id", itemID, + "message_id", messageID, + "sender", senderEmail, + ) + continue + } + if !p.senderIsThreadParticipant(ctx, itemID, senderEmail) { + slog.Warn("ignoring reply: sender is no longer authorized", + "item_id", itemID, + "message_id", messageID, + "sender", senderEmail, + ) + continue + } + slog.Debug("found authorized reply parent", "message_id", messageID, "item_id", itemID) + return itemID, true } - if !p.senderIsThreadParticipant(ctx, itemID, senderEmail) { - slog.Warn("ignoring reply: sender is not a known thread participant", - "item_id", itemID, - "message_id", messageID, - "sender", senderEmail, - ) - continue + // Pre-upgrade outbound IDs carry no recipient. They are tolerated only + // on the existing ticket they were recorded on; a new ticket has no such + // row and therefore must present an exact reply key. + if itemID, ok := p.lookupLegacyReplyItem(ctx, canonicalID); ok { + if !p.senderIsThreadParticipant(ctx, itemID, senderEmail) { + slog.Warn("ignoring legacy reply: sender is not authorized", + "item_id", itemID, + "message_id", messageID, + "sender", senderEmail, + ) + continue + } + slog.Debug("found authorized legacy reply parent", "message_id", messageID, "item_id", itemID) + return itemID, true } - slog.Debug("found parent item for reply", "message_id", messageID, "item_id", itemID) - return &itemID } + return 0, false +} - return nil +// ReplyKeyValidity bounds how long a Windshift-issued outbound Message-ID may +// authorize a reply. Outbox rows are retained longer (90 days) for audit. +const ReplyKeyValidity = 30 * 24 * time.Hour + +// lookupReplyKey resolves a Message-ID to the request and intended recipient of +// a Windshift-issued outbound delivery. The durable reply outbox persists item, +// recipient and Message-ID together, so it is the sole source of reply keys: an +// inbound (customer-generated) Message-ID is never found here (WI-2365). +func (p *Processor) lookupReplyKey(ctx context.Context, canonicalID string) (itemID int, recipient string, ok bool) { + bareID := bareMessageID(canonicalID) + err := p.db.QueryRowContext(ctx, ` + SELECT item_id, to_email FROM email_reply_outbox + WHERE message_id IN (?, ?) AND item_id IS NOT NULL AND to_email <> '' + AND key_generation >= 1 + AND COALESCE(delivered_at, created_at) >= ? + ORDER BY id DESC + LIMIT 1 + `, canonicalID, bareID, time.Now().Add(-ReplyKeyValidity)).Scan(&itemID, &recipient) + if err != nil { + if !errors.Is(err, sql.ErrNoRows) { + slog.Warn("failed to look up reply key", "message_id", canonicalID, "error", err) + } + return 0, "", false + } + return itemID, recipient, true } -// senderIsThreadParticipant reports whether senderEmail is allowed to post -// onto the given item via an email reply. The checks are item-scoped: the -// original creator, a current external request participant (WI-1136, including -// a re-added one), or a prior sender on the thread. An explicit participant -// removal revokes the implicit thread-membership grant so removing someone is -// not undone by an old reply in their mailbox. The anchor rows minted for -// portal tickets carry from_email=” so they can never satisfy the -// prior-participant clause implicitly. -func (p *Processor) senderIsThreadParticipant(ctx context.Context, itemID int, senderEmail string) bool { +// lookupLegacyReplyItem resolves a pre-WI-2365 outbound Message-ID to the +// ticket it was recorded on. Those rows are generation 0 and carry no +// recipient, so they are tolerated only on a ticket that has never issued a +// recipient-bound key; synthetic anchors (from_email = ”) never authorize. +func (p *Processor) lookupLegacyReplyItem(ctx context.Context, canonicalID string) (int, bool) { + bareID := bareMessageID(canonicalID) + var itemID int + err := p.db.QueryRowContext(ctx, ` + SELECT t.item_id FROM email_message_tracking t + WHERE t.message_id IN (?, ?) AND t.direction = 'outbound' AND t.item_id IS NOT NULL + AND t.key_generation = 0 AND t.from_email <> '' + AND NOT EXISTS ( + SELECT 1 FROM email_reply_outbox o + WHERE o.item_id = t.item_id AND o.key_generation >= 1 + ) + ORDER BY t.id DESC + LIMIT 1 + `, canonicalID, bareID).Scan(&itemID) + if err != nil { + if !errors.Is(err, sql.ErrNoRows) { + slog.Warn("failed to look up legacy reply id", "message_id", canonicalID, "error", err) + } + return 0, false + } + return itemID, true +} + +// senderStillAuthorized reports whether senderEmail may post onto the item now +// that a reply key named them. The item creator and current external +// participants are authorized; an explicit removal revokes the grant, and a +// prior sender on the thread is not an identity (WI-2365). +func (p *Processor) senderStillAuthorized(_ context.Context, itemID int, senderEmail string) bool { if senderEmail == "" { return false } + // Unverified contact recorded on the item: the reply key's recipient match + // already proved control of the address, so the contact may append. + var contactEmail sql.NullString + if err := p.db.QueryRow(`SELECT contact_email FROM items WHERE id = ?`, itemID).Scan(&contactEmail); err == nil { + if contactEmail.Valid && normalizedEmail(contactEmail.String) == senderEmail { + return true + } + } // Original creator via portal customer. if creatorEmail, err := repository.NewItemRepository(p.db).GetPortalCustomerEmailForItem(itemID); err == nil { if normalizedEmail(creatorEmail) == senderEmail { return true } } - // Explicit external request participant, including a re-added one. - participants := repository.NewItemParticipantRepository(p.db) - if isParticipant, err := participants.IsParticipantEmail(itemID, senderEmail); err == nil && isParticipant { + // Current external request participant. A re-added participant counts; + // an explicit removal leaves no participant row, so it fails closed. + if isParticipant, err := repository.NewItemParticipantRepository(p.db).IsParticipantEmail(itemID, senderEmail); err == nil && isParticipant { return true } - // An explicit removal revokes implicit thread membership. - if removed, err := participants.WasParticipantRemoved(itemID, senderEmail); err == nil && removed { - return false + return false +} + +// linkVerifiedContact promotes an unverified item contact to the portal owner +// once a reply key proves the sender controls the address. It only acts when +// the item has no owner and the contact matches the verified sender, so a +// reply key can never reassign someone else's request. +func (p *Processor) linkVerifiedContact(ctx context.Context, itemID, customerID int, senderEmail string) { + if customerID <= 0 || senderEmail == "" { + return } - // Prior participant on this item's thread (inbound or outbound, any channel). - var priorCount int - if err := p.db.QueryRowContext(ctx, ` - SELECT COUNT(*) FROM email_message_tracking - WHERE item_id = ? AND LOWER(from_email) = ? - `, itemID, senderEmail).Scan(&priorCount); err == nil && priorCount > 0 { - return true + if _, err := p.db.ExecWriteContext(ctx, ` + UPDATE items + SET creator_portal_customer_id = ?, contact_email = NULL, contact_name = NULL, updated_at = CURRENT_TIMESTAMP + WHERE id = ? AND creator_portal_customer_id IS NULL AND LOWER(contact_email) = ? + `, customerID, itemID, normalizedEmail(senderEmail)); err != nil { + slog.Warn("failed to link verified email contact to portal customer", + "item_id", itemID, "customer_id", customerID, "error", err) } - return false +} + +// findParentItem resolves the item an email reply is authorized to append to, +// or nil when the reply must start a separate request. It is the entry point +// for the recipient-bound reply-key lookup; see findAuthorizedReplyParent for +// the authorization contract. +func (p *Processor) findParentItem(ctx context.Context, email *ParsedEmail) *int { + if itemID, ok := p.findAuthorizedReplyParent(ctx, email); ok { + return &itemID + } + return nil +} + +// senderIsThreadParticipant reports whether senderEmail may still reply onto +// the item once a reply key has named them; see senderStillAuthorized. +func (p *Processor) senderIsThreadParticipant(ctx context.Context, itemID int, senderEmail string) bool { + return p.senderStillAuthorized(ctx, itemID, senderEmail) } // normalizedEmail lowercases and trims, matching how the processor stores and @@ -598,7 +726,6 @@ func (p *Processor) createItemFromEmail( email *ParsedEmail, channelID int, config *models.ChannelConfig, - customerID int, intakeID *int, ) (*ProcessingResult, error) { workspaceID, itemTypeID, requestTypeID, err := p.resolveEmailIntakeTarget(config) @@ -629,18 +756,21 @@ func (p *Processor) createItemFromEmail( // Build item parameters. Leave StatusID nil so services.CreateItem resolves // it from the workspace workflow. PriorityID is supplied only when the // channel explicitly configured a workspace-valid override; otherwise the - // shared service resolves the workspace default. + // shared service resolves the workspace default. The sender is recorded as + // an unverified contact, not a portal owner: the claimed From must not make + // the request appear in a customer's portal or organisation sharing (WI-2365). params := services.ItemCreationParams{ - WorkspaceID: workspaceID, - Title: sanitize.PlainTextField.Sanitize(email.GetSubjectForItem()), - Description: sanitize.Comment.Sanitize(email.bodyMarkdown(false)), - ItemTypeID: itemTypeID, - PriorityID: config.EmailDefaultPriorityID, - RequestTypeID: requestTypeID, - IntakeID: intakeID, - CreatorPortalCustomerID: &customerID, - ChannelID: &channelID, - EventMetadata: itemevents.PortalCustomer(customerID, "email"), + WorkspaceID: workspaceID, + Title: sanitize.PlainTextField.Sanitize(email.GetSubjectForItem()), + Description: sanitize.Comment.Sanitize(email.bodyMarkdown(false)), + ItemTypeID: itemTypeID, + PriorityID: config.EmailDefaultPriorityID, + RequestTypeID: requestTypeID, + IntakeID: intakeID, + ContactEmail: email.From.Address, + ContactName: email.From.Name, + ChannelID: &channelID, + EventMetadata: itemevents.System("email"), } // Create the item via the shared service entry point. diff --git a/internal/email/sender_auth.go b/internal/email/sender_auth.go new file mode 100644 index 000000000..3aa35c822 --- /dev/null +++ b/internal/email/sender_auth.go @@ -0,0 +1,699 @@ +package email + +import ( + "strings" + + "golang.org/x/net/publicsuffix" + + "windshift/internal/models" +) + +// Sender authentication evaluation is diagnostic only (WI-2365): intake never +// holds or drops mail on the SPF/DKIM/DMARC verdict, and the claimed From is +// never an identity. The result is recorded on the tracking row for the admin +// diagnostics view. Authorization to append to a private conversation comes +// from a recipient-bound outbound Message-ID instead. + +// 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/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/item.go b/internal/models/item.go index cc531cb08..987b1c86a 100644 --- a/internal/models/item.go +++ b/internal/models/item.go @@ -41,6 +41,11 @@ type Item struct { CreatorID *int `json:"creator_id,omitempty"` // Internal user who created this item ReporterID *int `json:"reporter_id,omitempty"` // User who reported this item (from Jira import) CreatorPortalCustomerID *int `json:"creator_portal_customer_id,omitempty"` // Portal customer who created this item (for portal submissions) + // ContactEmail/ContactName record an unverified inbound email sender until a + // reply key proves they control the address (WI-2365). They are not a portal + // identity: the item is not listed in any customer's portal. + ContactEmail string `json:"contact_email,omitempty"` + ContactName string `json:"contact_name,omitempty"` // Portal submission tracking fields (immutable once set) ChannelID *int `json:"channel_id,omitempty"` // Portal/channel this request was submitted through RequestTypeID *int `json:"request_type_id,omitempty"` // Request type used for submission diff --git a/internal/models/portal.go b/internal/models/portal.go index d92e9372a..d2baa531f 100644 --- a/internal/models/portal.go +++ b/internal/models/portal.go @@ -165,6 +165,12 @@ 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"` + // 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. The result is recorded for diagnostics only; intake never + // gates on it (WI-2365). + 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/item_repository.go b/internal/repository/item_repository.go index 6393dd00d..d0bddcdc0 100644 --- a/internal/repository/item_repository.go +++ b/internal/repository/item_repository.go @@ -42,7 +42,7 @@ func (r *ItemRepository) GetDetailPanelAvailability(workspaceID, itemID int) (sc const itemBaseColumns = `id, workspace_id, workspace_item_number, item_type_id, title, description, status_id, priority_id, due_date, start_date, end_date, is_task, iteration_id, project_id, inherit_project, - time_project_id, assignee_id, creator_id, creator_portal_customer_id, custom_field_values, parent_id, related_work_item_id, + time_project_id, assignee_id, creator_id, creator_portal_customer_id, contact_email, contact_name, custom_field_values, parent_id, related_work_item_id, story_points, estimate_minutes, frac_index, created_at, updated_at, channel_id` func scanItemBase(scanner interface { @@ -52,6 +52,7 @@ func scanItemBase(scanner interface { var customFieldValuesJSON sql.NullString var itemTypeID, parentID, statusID, iterationID, projectID, priorityID sql.NullInt64 var timeProjectID, assigneeID, creatorID, creatorPortalCustomerID, relatedWorkItemID sql.NullInt64 + var contactEmail, contactName sql.NullString var dueDate, startDate, endDate sql.NullTime var storyPoints sql.NullFloat64 var estimateMinutes sql.NullInt64 @@ -61,7 +62,7 @@ func scanItemBase(scanner interface { err := scanner.Scan( &item.ID, &item.WorkspaceID, &item.WorkspaceItemNumber, &itemTypeID, &item.Title, &item.Description, &statusID, &priorityID, &dueDate, &startDate, &endDate, &item.IsTask, &iterationID, - &projectID, &item.InheritProject, &timeProjectID, &assigneeID, &creatorID, &creatorPortalCustomerID, &customFieldValuesJSON, &parentID, + &projectID, &item.InheritProject, &timeProjectID, &assigneeID, &creatorID, &creatorPortalCustomerID, &contactEmail, &contactName, &customFieldValuesJSON, &parentID, &relatedWorkItemID, &storyPoints, &estimateMinutes, &fracIndex, &item.CreatedAt, &item.UpdatedAt, &channelID, ) if err != nil { @@ -78,6 +79,8 @@ func scanItemBase(scanner interface { assignNullableInt(&item.AssigneeID, assigneeID) assignNullableInt(&item.CreatorID, creatorID) assignNullableInt(&item.CreatorPortalCustomerID, creatorPortalCustomerID) + assignNullableString(&item.ContactEmail, contactEmail) + assignNullableString(&item.ContactName, contactName) assignNullableInt(&item.RelatedWorkItemID, relatedWorkItemID) assignNullableInt(&item.ChannelID, channelID) assignNullableTime(&item.DueDate, dueDate) @@ -325,7 +328,7 @@ const itemDetailsSelectBody = ` i.project_id, i.inherit_project, i.time_project_id, i.assignee_id, i.creator_id, i.custom_field_values, i.virtual_field_data, i.parent_id, i.story_points, i.estimate_minutes, i.frac_index, i.created_at, i.updated_at, - i.creator_portal_customer_id, i.channel_id, i.request_type_id, + i.creator_portal_customer_id, i.contact_email, i.contact_name, i.channel_id, i.request_type_id, w.name as workspace_name, w.key as workspace_key, w.active as workspace_active, iter.name as iteration_name, proj.name as project_name, @@ -385,6 +388,7 @@ func scanItemDetailsRow(scanner rowScanner) (models.Item, bool, error) { var relatedWorkItemTitle, relatedWorkItemWorkspaceKey sql.NullString var relatedWorkItemWorkspaceID, relatedWorkItemNumber sql.NullInt64 var creatorPortalCustomerID, channelID, requestTypeID sql.NullInt64 + var contactEmail, contactName sql.NullString var teamID, incidentID sql.NullInt64 var teamName, teamColor, teamAvatar sql.NullString var creatorPortalCustomerName, creatorPortalCustomerEmail sql.NullString @@ -400,7 +404,7 @@ func scanItemDetailsRow(scanner rowScanner) (models.Item, bool, error) { &projectID, &item.InheritProject, &timeProjectID, &assigneeID, &creatorID, &customFieldValuesJSON, &virtualFieldDataJSON, &parentID, &storyPoints, &estimateMinutes, &item.FracIndex, &item.CreatedAt, &item.UpdatedAt, - &creatorPortalCustomerID, &channelID, &requestTypeID, + &creatorPortalCustomerID, &contactEmail, &contactName, &channelID, &requestTypeID, &item.WorkspaceName, &item.WorkspaceKey, &workspaceActive, &iterationName, &projectName, &timeProjectName, &parentTitle, &parentWorkspaceItemNumber, &assigneeName, &assigneeEmail, &assigneeAvatar, &creatorName, &creatorEmail, @@ -437,6 +441,8 @@ func scanItemDetailsRow(scanner rowScanner) (models.Item, bool, error) { assignNullableInt(&item.CreatorID, creatorID) assignNullableInt(&item.CreatorPortalCustomerID, creatorPortalCustomerID) + assignNullableString(&item.ContactEmail, contactEmail) + assignNullableString(&item.ContactName, contactName) assignNullableInt(&item.ChannelID, channelID) assignNullableInt(&item.RequestTypeID, requestTypeID) assignNullableInt(&item.TeamID, teamID) @@ -1114,14 +1120,16 @@ func (r *ItemRepository) Create(tx database.Tx, item *models.Item) (int, error) INSERT INTO items ( workspace_id, workspace_item_number, item_type_id, title, description, status_id, priority_id, is_task, iteration_id, project_id, inherit_project, time_project_id, assignee_id, team_id, reporter_id, creator_id, creator_portal_customer_id, + contact_email, contact_name, channel_id, request_type_id, intake_id, portal_org_shared, due_date, start_date, end_date, related_work_item_id, story_points, estimate_minutes, custom_field_values, virtual_field_data, parent_id, frac_index, created_at, updated_at, last_active_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id `, item.WorkspaceID, item.WorkspaceItemNumber, item.ItemTypeID, item.Title, item.Description, item.StatusID, item.PriorityID, item.IsTask, item.IterationID, item.ProjectID, item.InheritProject, item.TimeProjectID, item.AssigneeID, item.TeamID, item.ReporterID, item.CreatorID, item.CreatorPortalCustomerID, + item.ContactEmail, item.ContactName, item.ChannelID, item.RequestTypeID, item.IntakeID, item.PortalOrgShared, item.DueDate, item.StartDate, item.EndDate, item.RelatedWorkItemID, item.StoryPoints, item.EstimateMinutes, customFieldValuesJSON, virtualFieldDataJSON, item.ParentID, diff --git a/internal/scheduler/email_scheduler.go b/internal/scheduler/email_scheduler.go index 600e1d914..f8d017b16 100644 --- a/internal/scheduler/email_scheduler.go +++ b/internal/scheduler/email_scheduler.go @@ -595,9 +595,10 @@ func (es *EmailScheduler) pollIntake( if msg.UID > maxUID { maxUID = msg.UID } - if rateLimited { + switch { + case rateLimited: rateLimitedCount++ - } else { + default: processedCount++ } } diff --git a/internal/services/email_reply_service.go b/internal/services/email_reply_service.go index f6a972333..ebaa04a03 100644 --- a/internal/services/email_reply_service.go +++ b/internal/services/email_reply_service.go @@ -2,7 +2,7 @@ package services import ( "context" - "crypto/sha256" + "crypto/rand" "database/sql" "encoding/hex" "encoding/json" @@ -10,6 +10,7 @@ import ( "fmt" "log/slog" "os" + "sort" "strings" "sync" "time" @@ -99,8 +100,8 @@ func (s *EmailReplyService) handleCommentCreated(params HandleCommentParams, del return fmt.Errorf("failed to query item for email reply: %w", err) } - // Skip if item has no channel or no portal customer creator - if item.ChannelID == nil || item.CreatorPortalCustomerID == nil { + // Skip if item has no channel or no addressable requester. + if item.ChannelID == nil { return nil } @@ -117,18 +118,24 @@ func (s *EmailReplyService) handleCommentCreated(params HandleCommentParams, del // Portal/form-originated tickets thread from the anchor minted at // submission; the ensure covers pre-upgrade tickets (created before the // anchor existed) and repairs a failed best-effort mint. It is a no-op for - // email channels and for items that already have their anchor. + // email channels and for items that already have their anchor. An + // unverified email contact has no anchor: the inbound message is the root. maybeRecordPortalThreadAnchor(s.db, int64(params.ItemID), item.ChannelID, item.CreatorPortalCustomerID, item.Title) - // Recipients: the creator plus every external request participant + // Recipients: the verified creator, or the item's unverified contact until a + // reply key proves the address, plus every external request participant // (WI-1136). Each gets its own outbox row so replies attribute per // recipient, and the intake participant guard accepts them as repliers. var customerEmail, customerName string - err = s.db.QueryRow("SELECT email, name FROM portal_customers WHERE id = ?", *item.CreatorPortalCustomerID).Scan(&customerEmail, &customerName) + if item.CreatorPortalCustomerID != nil { + err = s.db.QueryRow("SELECT email, name FROM portal_customers WHERE id = ?", *item.CreatorPortalCustomerID).Scan(&customerEmail, &customerName) + } else { + customerEmail, customerName = item.ContactEmail, item.ContactName + } if err != nil || customerEmail == "" { - slog.Debug("no email for portal customer, skipping reply", - slog.String("component", "email_reply_service"), - slog.Int("customer_id", *item.CreatorPortalCustomerID), + slog.Debug("no addressable requester for item, skipping reply", + "component", "email_reply_service", + slog.Int("item_id", params.ItemID), ) return nil } @@ -144,33 +151,13 @@ func (s *EmailReplyService) handleCommentCreated(params HandleCommentParams, del recipients = append(recipients, emailRecipient{Email: participant.CustomerEmail, Name: participant.CustomerName}) } - // Build threading headers from email_message_tracking - type trackingRecord struct { - MessageID string - Subject sql.NullString - } - rows, err := s.db.Query(` - SELECT message_id, subject FROM email_message_tracking - WHERE item_id = ? - ORDER BY processed_at ASC - `, params.ItemID) + // Load the item's recorded thread. Threading headers are built per + // recipient below: another recipient's reply key is never copied into + // References or In-Reply-To (WI-2365). + records, err := s.loadItemThread(params.ItemID) if err != nil { return fmt.Errorf("failed to query email tracking: %w", err) } - defer rows.Close() - - var records []trackingRecord - for rows.Next() { - var rec trackingRecord - if err = rows.Scan(&rec.MessageID, &rec.Subject); err != nil { - continue - } - records = append(records, rec) - } - if err := rows.Err(); err != nil { - return fmt.Errorf("failed to iterate email tracking: %w", err) - } - if len(records) == 0 { // No email tracking records — can't thread, skip slog.Debug("no email tracking records for item, skipping reply", @@ -180,18 +167,6 @@ func (s *EmailReplyService) handleCommentCreated(params HandleCommentParams, del return nil } - // References: all Message-IDs chronologically (item-scoped — the thread - // follows the conversation across channels). - var references []string - for _, rec := range records { - if rec.MessageID != "" { - references = append(references, rec.MessageID) - } - } - - // In-Reply-To: most recent Message-ID - inReplyTo := records[len(records)-1].MessageID - // Subject: Re: {original subject} from first tracking record originalSubject := item.Title if records[0].Subject.Valid && records[0].Subject.String != "" { @@ -218,10 +193,6 @@ func (s *EmailReplyService) handleCommentCreated(params HandleCommentParams, del itemKey := fmt.Sprintf("%s-%d", item.WorkspaceKey, item.WorkspaceItemNumber) portalURL := s.portalRequestURL(params.ItemID) - referencesJSON, err := json.Marshal(references) - if err != nil { - return fmt.Errorf("encode email references: %w", err) - } // Route replies back to the monitored intake mailbox, not the SMTP sender. // Persisted per row so a retry is stable if the channel config changes. replyToEmail, replyToName := s.resolveReplyToAddress(params.ItemID, *item.ChannelID) @@ -246,15 +217,31 @@ func (s *EmailReplyService) handleCommentCreated(params HandleCommentParams, del if err != nil { return fmt.Errorf("failed to render portal reply email: %w", err) } - messageID := recipientMessageID(params.CommentID, recipient.Email, smtpDomain) + // Recipient-specific threading keeps the reply key scoped to this + // recipient: another participant's outbound Message-ID is never copied + // into References or In-Reply-To. An item whose original mail had no + // Message-ID still gets its reply: the minted Message-ID below is the + // reply key, and empty threading headers must not silently drop the + // customer's reply. + inReplyTo, references := threadHeadersForRecipient(records, recipient.Email) + referencesJSON, err := json.Marshal(references) + if err != nil { + return fmt.Errorf("encode email references: %w", err) + } + // A cryptographically random, per-recipient Message-ID is the reply key. + // It is persisted on the outbox row so a retry reuses the same ID. + messageID, err := newReplyMessageID("ws-comment", params.CommentID, smtpDomain) + if err != nil { + return fmt.Errorf("mint reply Message-ID: %w", err) + } var outboxID int err = s.db.QueryRow(` INSERT INTO email_reply_outbox ( comment_id, channel_id, item_id, to_email, to_name, subject, - html_body, text_body, message_id, in_reply_to, references_json, + html_body, text_body, message_id, key_generation, in_reply_to, references_json, from_email, from_name, reply_to_email, reply_to_name, next_attempt_at, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) ON CONFLICT(comment_id, to_email) WHERE comment_id IS NOT NULL DO NOTHING RETURNING id `, params.CommentID, *item.ChannelID, params.ItemID, recipient.Email, recipient.Name, @@ -380,11 +367,109 @@ type emailRecipient struct { Name string } -// recipientMessageID derives a deterministic, per-recipient Message-ID so each -// outbox row and tracking entry is distinct and idempotent across retries. -func recipientMessageID(commentID int, email, domain string) string { - sum := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(email)))) - return fmt.Sprintf("", commentID, hex.EncodeToString(sum[:6]), domain) +// newReplyMessageID mints a cryptographically random Message-ID for one +// outbound delivery. It is generated once and persisted with the outbox row, +// so a retry reuses the same ID rather than minting a second reply key. The +// prefix and scope id keep the value recognizable in logs; the random suffix +// makes it unguessable. +func newReplyMessageID(prefix string, scopeID int, domain string) (string, error) { + var entropy [16]byte + if _, err := rand.Read(entropy[:]); err != nil { + return "", fmt.Errorf("generate reply Message-ID entropy: %w", err) + } + return fmt.Sprintf("<%s-%d-%s@%s>", prefix, scopeID, hex.EncodeToString(entropy[:]), domain), nil +} + +// emailThreadRecord is one message recorded on an item's conversation. +// ToEmail is the intended recipient of an outbound row and empty for inbound +// rows and synthetic thread anchors. +type emailThreadRecord struct { + MessageID string + Subject sql.NullString + Direction string + ToEmail string + At time.Time +} + +// loadItemThread loads the item's conversation for building recipient-specific +// threading headers. Inbound messages and synthetic anchors come from +// email_message_tracking; delivered reply keys come from email_reply_outbox, +// which alone records the intended recipient (WI-2365). The two sources are +// merged chronologically so the parent chosen below is the most recent message, +// not whichever source was appended last. +func (s *EmailReplyService) loadItemThread(itemID int) ([]emailThreadRecord, error) { + var records []emailThreadRecord + rows, err := s.db.Query(` + SELECT message_id, subject, direction, '', processed_at FROM email_message_tracking + WHERE item_id = ? + AND (direction = 'inbound' OR (direction = 'outbound' AND comment_id IS NULL AND from_email = '')) + ORDER BY processed_at ASC, id ASC + `, itemID) + if err != nil { + return nil, fmt.Errorf("query email tracking: %w", err) + } + for rows.Next() { + var rec emailThreadRecord + if err := rows.Scan(&rec.MessageID, &rec.Subject, &rec.Direction, &rec.ToEmail, &rec.At); err != nil { + continue + } + records = append(records, rec) + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return nil, fmt.Errorf("iterate email tracking: %w", err) + } + if err := rows.Close(); err != nil { + return nil, fmt.Errorf("close email tracking rows: %w", err) + } + + // Only delivered, non-discarded, recipient-bound keys belong in the thread: + // a pending or discarded row was never sent, and a generation-0 row is a + // pre-upgrade ID that must not be exposed. + keyRows, err := s.db.Query(` + SELECT message_id, subject, to_email, delivered_at FROM email_reply_outbox + WHERE item_id = ? AND message_id <> '' AND to_email <> '' + AND delivered_at IS NOT NULL AND discarded_at IS NULL AND key_generation >= 1 + ORDER BY delivered_at ASC, id ASC + `, itemID) + if err != nil { + return nil, fmt.Errorf("query email reply keys: %w", err) + } + defer keyRows.Close() + for keyRows.Next() { + var rec emailThreadRecord + if err := keyRows.Scan(&rec.MessageID, &rec.Subject, &rec.ToEmail, &rec.At); err != nil { + continue + } + rec.Direction = "outbound" + records = append(records, rec) + } + if err := keyRows.Err(); err != nil { + return nil, fmt.Errorf("iterate email reply keys: %w", err) + } + sort.SliceStable(records, func(i, j int) bool { return records[i].At.Before(records[j].At) }) + return records, nil +} + +// threadHeadersForRecipient builds the In-Reply-To and References for one +// recipient. The conversation root, inbound messages, and the recipient's own +// prior reply keys form the chain; another recipient's reply key is never +// copied into the headers (WI-2365). Returns empty headers when the item has +// no recorded thread. +func threadHeadersForRecipient(records []emailThreadRecord, recipient string) (inReplyTo string, references []string) { + for _, rec := range records { + if rec.MessageID == "" { + continue + } + // An outbound row with a recipient is a reply key owned by that + // recipient. Never expose it to anyone else. + if rec.Direction == "outbound" && rec.ToEmail != "" && !strings.EqualFold(rec.ToEmail, recipient) { + continue + } + references = append(references, rec.MessageID) + inReplyTo = rec.MessageID + } + return inReplyTo, references } type emailReplyOutboxRow struct { @@ -483,35 +568,25 @@ func (s *EmailReplyService) sendItemNotice(item *models.Item, toEmail, toName, s return false, "no_email", nil } - // Thread against the item's recorded Message-IDs (item-scoped); without - // a thread there is nothing to reply into, so the notice would start an - // orphaned thread. - var inReplyTo string - var references []string - var originalSubject sql.NullString - rows, err := s.db.Query(` - SELECT message_id, subject FROM email_message_tracking - WHERE item_id = ? - ORDER BY processed_at ASC - `, item.ID) + // Thread against the item's recorded messages, scoped to this recipient: + // another participant's reply key is never copied into References or + // In-Reply-To. Without a thread there is nothing to reply into, so the + // notice would start an orphaned conversation. + records, err := s.loadItemThread(item.ID) if err != nil { return false, "", fmt.Errorf("query email tracking for customer notice: %w", err) } - defer rows.Close() - for rows.Next() { - var messageID string - if scanErr := rows.Scan(&messageID, &originalSubject); scanErr != nil { - continue - } - references = append(references, messageID) - inReplyTo = messageID - } - if err := rows.Err(); err != nil { - return false, "", fmt.Errorf("iterate email tracking for customer notice: %w", err) - } - if len(references) == 0 { + if len(records) == 0 { return false, "no_thread", nil } + inReplyTo, references := threadHeadersForRecipient(records, toEmail) + var originalSubject sql.NullString + for _, rec := range records { + if rec.Subject.Valid && rec.Subject.String != "" { + originalSubject = rec.Subject + break + } + } emailSubject := item.Title if originalSubject.Valid && originalSubject.String != "" { @@ -550,8 +625,35 @@ func (s *EmailReplyService) sendItemNotice(item *models.Item, toEmail, toName, s } smtpDomain := s.getSMTPDomain() - messageID := fmt.Sprintf("", item.ID, time.Now().UnixNano(), smtpDomain) + messageID, err := newReplyMessageID("ws-notice", item.ID, smtpDomain) + if err != nil { + return false, "", fmt.Errorf("mint notice Message-ID: %w", err) + } replyToEmail, replyToName := s.resolveReplyToAddress(item.ID, *item.ChannelID) + referencesJSON, err := json.Marshal(references) + if err != nil { + referencesJSON = []byte("[]") + } + + // Persist the reply key before crossing the SMTP boundary. If the send + // succeeds but the process dies before recording the key, the customer + // holds a Message-ID Windshift never learned. A persistence failure must + // therefore fail the notice instead of sending an unroutable key. + if _, err := s.db.ExecWrite(` + INSERT INTO email_reply_outbox ( + kind, channel_id, item_id, to_email, to_name, subject, + html_body, text_body, message_id, key_generation, in_reply_to, references_json, + from_email, from_name, reply_to_email, reply_to_name, + next_attempt_at, delivered_at, created_at, updated_at + ) VALUES ('notice', ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, + CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + ON CONFLICT DO NOTHING + `, *item.ChannelID, item.ID, toEmail, toName, emailSubject, + htmlBody, textBody, messageID, inReplyTo, string(referencesJSON), + s.getSMTPFromEmail(), authorName, replyToEmail, replyToName); err != nil { + return false, "", fmt.Errorf("persist customer notice reply key: %w", err) + } + if err := s.smtpSender.SendThreadedEmail(smtp.ThreadedEmailParams{ ToEmail: toEmail, ToName: toName, @@ -567,14 +669,13 @@ func (s *EmailReplyService) sendItemNotice(item *models.Item, toEmail, toName, s return false, "", fmt.Errorf("send customer notice: %w", err) } - // Record the notice's own Message-ID so a reply that carries only - // In-Reply-To (no References) still resolves to this item instead of - // starting a new ticket. Best-effort: the mail is already sent. + // Audit record after a successful send: the notice's Message-ID and thread + // placement for the channel email log. Best-effort. if _, err := s.db.ExecWrite(` INSERT INTO email_message_tracking ( channel_id, message_id, dedup_key, in_reply_to, from_email, from_name, subject, - item_id, comment_id, direction, processed_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, 'outbound', CURRENT_TIMESTAMP) + item_id, comment_id, key_generation, direction, processed_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, 1, 'outbound', CURRENT_TIMESTAMP) ON CONFLICT(channel_id, dedup_key) DO NOTHING `, *item.ChannelID, messageID, messageID, inReplyTo, s.getSMTPFromEmail(), authorName, emailSubject, item.ID); err != nil { slog.Warn("failed to record customer notice in email tracking; replies may not thread", @@ -598,16 +699,6 @@ func (s *EmailReplyService) EnqueueIntakeConfirmation(itemID, customerID int) er if !s.smtpSender.IsSMTPConfigured() { return nil } - var customerEmail, customerName string - if err := s.db.QueryRow(`SELECT email, COALESCE(name, '') FROM portal_customers WHERE id = ?`, customerID).Scan(&customerEmail, &customerName); err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil - } - return fmt.Errorf("load portal customer for intake confirmation: %w", err) - } - if customerEmail == "" { - return nil - } item, err := repository.NewItemRepository(s.db).FindByIDWithDetails(itemID) if err != nil { if errors.Is(err, repository.ErrNotFound) { @@ -618,6 +709,22 @@ func (s *EmailReplyService) EnqueueIntakeConfirmation(itemID, customerID int) er if item.ChannelID == nil { return nil } + // A receipt goes to the verified portal customer when there is one, or to + // the item's unverified contact address until a reply key verifies it. + var customerEmail, customerName string + if customerID > 0 { + if err := s.db.QueryRow(`SELECT email, COALESCE(name, '') FROM portal_customers WHERE id = ?`, customerID).Scan(&customerEmail, &customerName); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil + } + return fmt.Errorf("load portal customer for intake confirmation: %w", err) + } + } else { + customerEmail, customerName = item.ContactEmail, item.ContactName + } + if customerEmail == "" { + return nil + } if customerName == "" { customerName = "there" } @@ -638,17 +745,20 @@ func (s *EmailReplyService) EnqueueIntakeConfirmation(itemID, customerID int) er return fmt.Errorf("render intake confirmation email: %w", err) } - messageID := fmt.Sprintf("", itemID, time.Now().UnixNano(), s.getSMTPDomain()) + messageID, err := newReplyMessageID("ws-confirm", itemID, s.getSMTPDomain()) + if err != nil { + return fmt.Errorf("mint intake confirmation Message-ID: %w", err) + } replyToEmail, replyToName := s.resolveReplyToAddress(itemID, *item.ChannelID) // The per-item confirmation unique index makes re-processing the same email // a no-op, so a duplicate receipt is never queued. if _, err := s.db.ExecWrite(` INSERT INTO email_reply_outbox ( kind, channel_id, item_id, to_email, to_name, subject, - html_body, text_body, message_id, in_reply_to, references_json, + html_body, text_body, message_id, key_generation, in_reply_to, references_json, from_email, from_name, reply_to_email, reply_to_name, next_attempt_at, created_at, updated_at - ) VALUES ('intake_confirmation', ?, ?, ?, ?, ?, ?, ?, ?, '', '[]', ?, ?, ?, ?, + ) VALUES ('intake_confirmation', ?, ?, ?, ?, ?, ?, ?, ?, 1, '', '[]', ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) ON CONFLICT DO NOTHING `, *item.ChannelID, itemID, customerEmail, customerName, subject, @@ -770,8 +880,10 @@ func (s *EmailReplyService) ProcessPendingReplies(ctx context.Context, limit int delivered++ } } - // Delivered rows are retained briefly for idempotence/audit, then pruned. - cutoff := time.Now().Add(-30 * 24 * time.Hour) + // Delivered rows stay as reply keys for 90 days even though a key is only + // honored for 30 (see email.ReplyKeyValidity): the extra window keeps the + // row available for audit and diagnostics before it is pruned. + cutoff := time.Now().Add(-90 * 24 * time.Hour) if _, err := s.db.ExecWrite(`DELETE FROM email_reply_outbox WHERE delivered_at IS NOT NULL AND delivered_at < ?`, cutoff); err != nil { slog.Warn("failed to prune delivered email reply outbox rows", "error", err) } @@ -839,11 +951,13 @@ func (s *EmailReplyService) deliverPendingReply(ctx context.Context, outboxID in // Tracking is best-effort after delivery. Do not retry SMTP merely because // this audit/threading insert failed; that would duplicate customer mail. + // key_generation marks the row as a recipient-bound reply key so it survives + // outbox pruning without ever being mistaken for a pre-upgrade ID. if _, err := s.db.ExecWrite(` INSERT INTO email_message_tracking ( channel_id, message_id, dedup_key, in_reply_to, from_email, from_name, subject, - item_id, comment_id, direction, processed_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'outbound', CURRENT_TIMESTAMP) + item_id, comment_id, key_generation, direction, processed_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 'outbound', CURRENT_TIMESTAMP) ON CONFLICT(channel_id, dedup_key) DO NOTHING `, row.ChannelID, row.MessageID, row.MessageID, row.InReplyTo, row.FromEmail, row.FromName, row.Subject, row.ItemID, row.CommentID); err != nil { diff --git a/internal/services/item_creation.go b/internal/services/item_creation.go index 4c61505d6..ce981d7fd 100644 --- a/internal/services/item_creation.go +++ b/internal/services/item_creation.go @@ -388,6 +388,7 @@ func (c *itemCreation) eventItem(itemID, itemNumber int) (*models.Item, error) { StatusID: c.statusID, PriorityID: c.priorityID, IsTask: p.IsTask, AssigneeID: p.AssigneeID, TeamID: p.TeamID, ReporterID: p.ReporterID, CreatorID: p.CreatorID, CreatorPortalCustomerID: p.CreatorPortalCustomerID, ChannelID: p.ChannelID, + ContactEmail: p.ContactEmail, ContactName: p.ContactName, RequestTypeID: p.RequestTypeID, IntakeID: p.IntakeID, PortalOrgShared: p.PortalOrgShared, ParentID: p.ParentID, IterationID: p.IterationID, ProjectID: p.ProjectID, InheritProject: p.InheritProject, TimeProjectID: p.TimeProjectID, diff --git a/internal/services/items.go b/internal/services/items.go index 4aec0a502..d8f2fd711 100644 --- a/internal/services/items.go +++ b/internal/services/items.go @@ -108,18 +108,22 @@ type ItemCreationParams struct { ReporterID *int // Reporter/submitter of the item CreatorID *int CreatorPortalCustomerID *int - ChannelID *int // Portal-specific: track portal/channel - RequestTypeID *int // Portal-specific: track request type - IntakeID *int // Email-specific: intake that created this item (WI-1644) - PortalOrgShared bool // Portal-specific: creator shared the request with their organisation (WI-1139) - DueDate *time.Time // Due date for the item - StartDate *time.Time // Start date for the item - EndDate *time.Time // End date for the item - RelatedWorkItemID *int // For personal tasks: related work item - StoryPoints *float64 // Story points for velocity tracking - EstimateMinutes *int // Time estimate in minutes (compared against logged worklog time) - CustomFieldValuesJSON string // JSON string of custom field values - VirtualFieldDataJSON string // JSON string of request-type virtual values + // ContactEmail/ContactName carry an unverified inbound email sender that is + // not yet a portal identity (WI-2365). + ContactEmail string + ContactName string + ChannelID *int // Portal-specific: track portal/channel + RequestTypeID *int // Portal-specific: track request type + IntakeID *int // Email-specific: intake that created this item (WI-1644) + PortalOrgShared bool // Portal-specific: creator shared the request with their organisation (WI-1139) + DueDate *time.Time // Due date for the item + StartDate *time.Time // Start date for the item + EndDate *time.Time // End date for the item + RelatedWorkItemID *int // For personal tasks: related work item + StoryPoints *float64 // Story points for velocity tracking + EstimateMinutes *int // Time estimate in minutes (compared against logged worklog time) + CustomFieldValuesJSON string // JSON string of custom field values + VirtualFieldDataJSON string // JSON string of request-type virtual values // CreatedAt / UpdatedAt override the default `time.Now()` timestamps. Used // by the Jira importer to preserve the original issue chronology so audit // views, reports, and "recent" filters reflect Jira's history rather than