- {total} skipped message{total === 1 ? '' : 's'}
+ {total} held or skipped message{total === 1 ? '' : 's'}
Not created as work items; recorded for diagnostics only.
@@ -92,7 +94,7 @@
{#if !view.loading && !view.error && total === 0}
- No system-generated mail was skipped in this window.
+ No held or skipped mail in this window.
{:else if !view.error}
@@ -132,6 +134,11 @@
{categoryLabel(message.category)}
+ {#if message.sender_auth}
+
+ {message.sender_auth}
+
+ {/if}
{#if message.from_name}
diff --git a/internal/database/migrations.go b/internal/database/migrations.go
index 2ce3b769c..3ea5bdd77 100644
--- a/internal/database/migrations.go
+++ b/internal/database/migrations.go
@@ -3727,6 +3727,29 @@ END $$;
CREATE UNIQUE INDEX IF NOT EXISTS uq_priorities_single_default ON priorities(is_default) WHERE is_default = true;
`,
},
+ {
+ // WI-2362: inbound mail authenticated its From address only through the
+ // attacker-controlled header. sender_auth records the SPF/DKIM/DMARC
+ // outcome on each tracking row, and intakes.sender_authentication lets an
+ // operator relax the default strict policy per intake. Empty
+ // sender_authentication means strict, so existing intakes need no backfill;
+ // operators whose provider does not add authentication headers must set it
+ // to 'off' explicitly.
+ Version: "20261204_email_sender_authentication",
+ Name: "Record inbound sender authentication and per-intake policy (WI-2362)",
+ CheckSQLite: "SELECT CASE WHEN (" + sqliteColumnCheck("email_message_tracking", "sender_auth") +
+ ") > 0 AND (" + sqliteColumnCheck("intakes", "sender_authentication") + ") > 0 THEN 1 ELSE 0 END",
+ CheckPostgres: "SELECT CASE WHEN (" + pgColumnCheck("email_message_tracking", "sender_auth") +
+ ") > 0 AND (" + pgColumnCheck("intakes", "sender_authentication") + ") > 0 THEN 1 ELSE 0 END",
+ SQLite: `
+ ALTER TABLE email_message_tracking ADD COLUMN sender_auth TEXT;
+ ALTER TABLE intakes ADD COLUMN sender_authentication TEXT NOT NULL DEFAULT '';
+ `,
+ Postgres: `
+ ALTER TABLE email_message_tracking ADD COLUMN IF NOT EXISTS sender_auth TEXT;
+ ALTER TABLE intakes ADD COLUMN IF NOT EXISTS sender_authentication TEXT NOT NULL DEFAULT '';
+ `,
+ },
}
// domainEventClaimableIndexMigration adds the partial index the claim query
diff --git a/internal/database/schema/email.sql b/internal/database/schema/email.sql
index a74e3acd3..fa3e46c1b 100644
--- a/internal/database/schema/email.sql
+++ b/internal/database/schema/email.sql
@@ -51,6 +51,9 @@ CREATE TABLE IF NOT EXISTS intakes (
item_type_id INTEGER, -- item type created for the routing workspace
rate_limit_per_hour INTEGER,
processing_disposition TEXT NOT NULL DEFAULT '',
+ -- sender_authentication overrides the mailbox's inbound sender
+ -- authentication policy for this intake. Empty inherits the mailbox default.
+ sender_authentication TEXT NOT NULL DEFAULT '',
send_confirmation BOOLEAN NOT NULL DEFAULT false,
import_existing_mail BOOLEAN NOT NULL DEFAULT false,
status TEXT NOT NULL DEFAULT 'enabled',
@@ -142,11 +145,18 @@ CREATE TABLE IF NOT EXISTS email_message_tracking (
-- reprocessing the same email. It is only cleared when the channel is
-- deleted and cascades the tracking rows.
completed_at DATETIME,
- -- skipped_reason records machine-generated mail (bounces, auto-replies)
- -- that intake deliberately did not turn into a ticket. The value is a
- -- SystemMailCategory; NULL for mail that was processed normally. Surfaced
- -- by the admin email-intake diagnostics view.
+ -- skipped_reason records mail intake deliberately did not turn into a
+ -- ticket: machine-generated mail (bounces, auto-replies) and, under a
+ -- strict sender-authentication policy, mail whose From address could not
+ -- be authenticated. The value is a SystemMailCategory or
+ -- 'unauthenticated_sender'; NULL for mail that was processed normally.
+ -- Surfaced by the admin email-intake diagnostics view.
skipped_reason TEXT,
+ -- sender_auth records the outcome of evaluating the message's SPF, DKIM,
+ -- and DMARC results against the From domain, e.g. 'dmarc=pass', 'spf=fail',
+ -- or 'none'. NULL for rows written before the check existed. Surfaced by
+ -- the channel email log and admin diagnostics.
+ sender_auth TEXT,
processed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE SET NULL,
diff --git a/internal/database/schema/email_postgres.sql b/internal/database/schema/email_postgres.sql
index 206cc86b9..83002a74d 100644
--- a/internal/database/schema/email_postgres.sql
+++ b/internal/database/schema/email_postgres.sql
@@ -49,6 +49,8 @@ CREATE TABLE IF NOT EXISTS intakes (
item_type_id INTEGER,
rate_limit_per_hour INTEGER,
processing_disposition TEXT NOT NULL DEFAULT '',
+ -- sender_authentication: see email.sql for the column contract.
+ sender_authentication TEXT NOT NULL DEFAULT '',
send_confirmation BOOLEAN NOT NULL DEFAULT false,
import_existing_mail BOOLEAN NOT NULL DEFAULT false,
status TEXT NOT NULL DEFAULT 'enabled',
@@ -118,8 +120,9 @@ CREATE TABLE IF NOT EXISTS email_message_tracking (
uid_validity BIGINT NOT NULL DEFAULT 0,
rate_limited_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ,
- -- skipped_reason: see email.sql for the column contract.
+ -- skipped_reason/sender_auth: see email.sql for the column contract.
skipped_reason TEXT,
+ sender_auth TEXT,
processed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE SET NULL,
diff --git a/internal/email/parser.go b/internal/email/parser.go
index 448cb780a..e27892680 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,33 @@ 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
+ for _, line := range bytes.Split(raw, []byte("\n")) {
+ 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..4cdd00d71 100644
--- a/internal/email/processor.go
+++ b/internal/email/processor.go
@@ -152,6 +152,25 @@ func (p *Processor) ProcessEmailWithIntake(
}, nil
}
+ // 1c. Sender authentication. The From header is attacker-controlled, so a
+ // strict policy holds mail whose From domain did not pass an aligned SPF,
+ // DKIM, or DMARC check instead of attributing it to a portal customer or an
+ // existing thread (WI-2362). The message is recorded on the tracking row so
+ // the admin diagnostics view can show what was held and why.
+ authResult := EvaluateSenderAuthentication(email)
+ if policy := ResolveSenderAuthPolicy(config.EmailSenderAuthentication); policy == SenderAuthStrict && !authResult.Verified {
+ p.markSenderAuthHeld(ctx, channelID, dedupKey, authResult)
+ slog.Warn("held inbound email: sender not authenticated",
+ "channel_id", channelID,
+ "message_id", email.MessageID,
+ "from", email.From.Address,
+ "auth", authResult.Summary(),
+ "detail", authResult.Detail,
+ )
+ return &ProcessingResult{Action: ActionSkipped, SkipReason: skipReasonUnauthenticatedSender}, nil
+ }
+ p.recordSenderAuth(ctx, channelID, dedupKey, authResult)
+
// 2. Find or create portal customer by email
customerID, err := p.findOrCreatePortalCustomer(ctx, email.From.Address, email.From.Name, channelID, config)
if err != nil {
@@ -370,6 +389,41 @@ func (p *Processor) markSystemMailSkipped(ctx context.Context, channelID int, de
}
}
+// skipReasonUnauthenticatedSender is persisted in
+// email_message_tracking.skipped_reason when a strict sender-authentication
+// policy held mail whose From address could not be authenticated. It is
+// rendered by the admin email-intake diagnostics view.
+const skipReasonUnauthenticatedSender = "unauthenticated_sender"
+
+// recordSenderAuth stamps the authentication outcome on the claimed tracking
+// row so the channel email log and admin diagnostics can show how the sender
+// was authenticated. Best effort: a failure here never changes ingestion.
+func (p *Processor) recordSenderAuth(ctx context.Context, channelID int, dedupKey string, auth SenderAuthResult) {
+ if _, err := p.db.ExecWriteContext(ctx, `
+ UPDATE email_message_tracking
+ SET sender_auth = ?
+ WHERE channel_id = ? AND dedup_key = ?
+ `, auth.Summary(), channelID, dedupKey); err != nil {
+ slog.Warn("failed to record sender authentication",
+ "error", err, "channel_id", channelID, "dedup_key", dedupKey, "auth", auth.Summary())
+ }
+}
+
+// markSenderAuthHeld finalizes the claimed tracking row for mail a strict
+// policy refused to attribute to the From address. completed_at keeps the
+// message deduplicated (the item and comment refs stay NULL) and skipped_reason
+// is the admin diagnostics hook.
+func (p *Processor) markSenderAuthHeld(ctx context.Context, channelID int, dedupKey string, auth SenderAuthResult) {
+ if _, err := p.db.ExecWriteContext(ctx, `
+ UPDATE email_message_tracking
+ SET sender_auth = ?, skipped_reason = ?, completed_at = CURRENT_TIMESTAMP
+ WHERE channel_id = ? AND dedup_key = ? AND completed_at IS NULL
+ `, auth.Summary(), skipReasonUnauthenticatedSender, channelID, dedupKey); err != nil {
+ slog.Warn("failed to mark unauthenticated email held",
+ "error", err, "channel_id", channelID, "dedup_key", dedupKey, "auth", auth.Summary())
+ }
+}
+
// findOrCreatePortalCustomer resolves the sender to a portal customer by
// email, creating one on first contact, and grants channel access.
func (p *Processor) findOrCreatePortalCustomer(
diff --git a/internal/email/sender_auth.go b/internal/email/sender_auth.go
new file mode 100644
index 000000000..89981aff2
--- /dev/null
+++ b/internal/email/sender_auth.go
@@ -0,0 +1,395 @@
+package email
+
+import "strings"
+
+// SenderAuthPolicy controls whether the From address of inbound mail must be
+// backed by a passing, aligned SPF, DKIM, or DMARC result before intake trusts
+// it. The From header is entirely attacker-controlled; without this check
+// anyone who can deliver a message can claim to be a known customer and either
+// join a private thread or create a request in their name (WI-2362).
+type SenderAuthPolicy string
+
+const (
+ // SenderAuthStrict holds mail whose From domain is not authenticated. It is
+ // the default for any channel or intake that does not configure a policy,
+ // so a missing or misspelled value can never silently disable the check.
+ SenderAuthStrict SenderAuthPolicy = "strict"
+ // SenderAuthOff trusts the From header the way intake did before sender
+ // authentication existed. Intended for mailbox providers that do not add
+ // Authentication-Results / Received-SPF headers.
+ SenderAuthOff SenderAuthPolicy = "off"
+)
+
+// ResolveSenderAuthPolicy returns the effective policy. Anything other than an
+// explicit "off" resolves to strict.
+func ResolveSenderAuthPolicy(value string) SenderAuthPolicy {
+ if strings.EqualFold(strings.TrimSpace(value), string(SenderAuthOff)) {
+ return SenderAuthOff
+ }
+ return SenderAuthStrict
+}
+
+// IsValidSenderAuthPolicy reports whether value is a recognized policy or the
+// empty default sentinel.
+func IsValidSenderAuthPolicy(value string) bool {
+ switch strings.ToLower(strings.TrimSpace(value)) {
+ case "", string(SenderAuthStrict), string(SenderAuthOff):
+ return true
+ default:
+ return false
+ }
+}
+
+// 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 headers that precede the first Received header are trusted: the final
+// receiving MTA prepends its own Authentication-Results above the Received
+// header it adds, so an Authentication-Results injected by the sender sits
+// below a Received header and is ignored. When the message was not parsed from
+// raw bytes (HeaderOrder is empty) the topmost header is used.
+func EvaluateSenderAuthentication(message *ParsedEmail) 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"}
+ }
+
+ var fallback *SenderAuthResult
+ for _, raw := range trustedHeaderValues(message, "Authentication-Results") {
+ result, verified := evaluateAuthenticationResults(raw, fromDomain)
+ if verified {
+ return result
+ }
+ if fallback == nil {
+ remembered := result
+ fallback = &remembered
+ }
+ }
+ for _, raw := range trustedHeaderValues(message, "Received-SPF") {
+ 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) (SenderAuthResult, bool) {
+ methods := parseAuthenticationResults(value)
+
+ // 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 From domain.
+ for _, method := range methods {
+ if method.name != "dmarc" || method.result != "pass" {
+ continue
+ }
+ if claimed := emailDomain(method.props["header.from"]); claimed != "" && !domainsAligned(fromDomain, claimed) {
+ continue
+ }
+ return SenderAuthResult{
+ Verified: true,
+ Method: SenderAuthMethodDMARC,
+ Outcome: "pass",
+ Detail: "dmarc=pass aligned with " + fromDomain,
+ }, true
+ }
+
+ // DKIM: the signing domain must align with the From domain.
+ for _, method := range methods {
+ if method.name != "dkim" || method.result != "pass" {
+ continue
+ }
+ domain := dkimSigningDomain(method.props)
+ if domain != "" && domainsAligned(fromDomain, domain) {
+ return SenderAuthResult{
+ Verified: true,
+ Method: SenderAuthMethodDKIM,
+ Outcome: "pass",
+ Detail: "dkim=pass signed by " + domain,
+ }, true
+ }
+ }
+
+ // SPF: the envelope (MAIL FROM) domain must align with the From domain.
+ for _, method := range methods {
+ if method.name != "spf" || method.result != "pass" {
+ continue
+ }
+ domain := emailDomain(method.props["smtp.mailfrom"])
+ if domain != "" && domainsAligned(fromDomain, domain) {
+ return SenderAuthResult{
+ Verified: true,
+ Method: SenderAuthMethodSPF,
+ Outcome: "pass",
+ Detail: "spf=pass for " + domain,
+ }, true
+ }
+ }
+
+ return summarizeAuthenticationResults(methods), false
+}
+
+// parseAuthenticationResults tokenizes an Authentication-Results value into
+// method clauses. The first semicolon-delimited segment is the authserv-id and
+// is skipped. Parenthesized comments are removed first so a comment can never
+// masquerade as a property.
+func parseAuthenticationResults(value string) []authMethod {
+ clauses := strings.Split(stripAuthenticationComments(value), ";")
+ var out []authMethod
+ for i, clause := range clauses {
+ if i == 0 {
+ continue // authserv-id
+ }
+ var current *authMethod
+ for _, field := range strings.Fields(clause) {
+ name, rawValue, ok := strings.Cut(field, "=")
+ if !ok {
+ continue
+ }
+ name = strings.ToLower(strings.TrimSpace(name))
+ rawValue = strings.Trim(strings.TrimSpace(rawValue), `"`)
+ switch name {
+ case "spf", "dkim", "dmarc":
+ out = append(out, authMethod{
+ name: name,
+ result: strings.ToLower(rawValue),
+ props: map[string]string{},
+ })
+ current = &out[len(out)-1]
+ default:
+ if current != nil && name != "" {
+ current.props[name] = rawValue
+ }
+ }
+ }
+ }
+ return out
+}
+
+// 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.
+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], ":"))
+ if result != "pass" {
+ return SenderAuthResult{
+ Method: SenderAuthMethodSPF,
+ Outcome: result,
+ Detail: "received-spf=" + result,
+ }, false
+ }
+ domain := emailDomain(receivedSPFProperty(cleaned, "envelope-from"))
+ if domain != "" && domainsAligned(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
+ for _, r := range value {
+ switch r {
+ case '(':
+ depth++
+ case ')':
+ if depth > 0 {
+ depth--
+ }
+ default:
+ if depth == 0 {
+ b.WriteRune(r)
+ }
+ }
+ }
+ 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.Trim(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)
+}
+
+// domainsAligned reports whether the authenticated domain aligns with the From
+// domain under DMARC relaxed alignment: identical, or one is a parent of the
+// other on a label boundary.
+func domainsAligned(fromDomain, authenticatedDomain string) bool {
+ fromDomain = strings.ToLower(strings.TrimSpace(fromDomain))
+ authenticatedDomain = strings.ToLower(strings.TrimSpace(authenticatedDomain))
+ if fromDomain == "" || authenticatedDomain == "" {
+ return false
+ }
+ if fromDomain == authenticatedDomain {
+ return true
+ }
+ return strings.HasSuffix(fromDomain, "."+authenticatedDomain) ||
+ strings.HasSuffix(authenticatedDomain, "."+fromDomain)
+}
+
+// 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
+}
+
+// trustedHeaderValues returns the values of name that appear before the first
+// Received header. When the message has no recorded header order (constructed
+// in tests or by an older parser) every value is returned.
+func trustedHeaderValues(message *ParsedEmail, name string) []string {
+ values := headerValues(message, name)
+ if len(values) == 0 || len(message.HeaderOrder) == 0 {
+ return values
+ }
+ var trusted []string
+ seen := 0
+ for _, key := range message.HeaderOrder {
+ if strings.EqualFold(key, "Received") {
+ return trusted
+ }
+ if strings.EqualFold(key, name) {
+ if seen < len(values) {
+ trusted = append(trusted, values[seen])
+ }
+ seen++
+ }
+ }
+ return trusted
+}
diff --git a/internal/email/types.go b/internal/email/types.go
index 5082b0341..49e4b258f 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
diff --git a/internal/email/validation.go b/internal/email/validation.go
index 3ebaea464..d58b02e5d 100644
--- a/internal/email/validation.go
+++ b/internal/email/validation.go
@@ -36,6 +36,9 @@ func ValidateConfigForEnable(channel *models.Channel, config *models.ChannelConf
if !IsValidEmailDisposition(config.EmailProcessingDisposition) {
return fmt.Errorf("%w: email_processing_disposition must be leave, mark_read, or delete", ErrConfigNotReady)
}
+ if !IsValidSenderAuthPolicy(config.EmailSenderAuthentication) {
+ return fmt.Errorf("%w: email_sender_authentication must be strict or off", ErrConfigNotReady)
+ }
switch strings.ToLower(config.EmailAuthMethod) {
case "oauth":
diff --git a/internal/handlers/channel_intakes.go b/internal/handlers/channel_intakes.go
index 7f3481a8f..d9c5dc139 100644
--- a/internal/handlers/channel_intakes.go
+++ b/internal/handlers/channel_intakes.go
@@ -22,6 +22,7 @@ type intakeRequest struct {
ItemTypeID *int `json:"item_type_id"`
RateLimitPerHour *int `json:"rate_limit_per_hour"`
ProcessingDisposition string `json:"processing_disposition"`
+ SenderAuthentication string `json:"sender_authentication"`
SendConfirmation bool `json:"send_confirmation"`
ImportExistingMail bool `json:"import_existing_mail"`
Status string `json:"status"`
@@ -146,6 +147,9 @@ func (h *ChannelHandler) validateIntakeRequest(ctx context.Context, actorID, mai
if req.RateLimitPerHour != nil && *req.RateLimitPerHour < 0 {
return nil, fmt.Errorf("%w: rate_limit_per_hour must be 0 (unlimited) or a positive number", errIntakeInvalid)
}
+ if !email.IsValidSenderAuthPolicy(req.SenderAuthentication) {
+ return nil, fmt.Errorf("%w: sender_authentication must be strict or off", errIntakeInvalid)
+ }
status := req.Status
if status == "" {
status = models.IntakeStatusEnabled
@@ -191,6 +195,7 @@ func (h *ChannelHandler) validateIntakeRequest(ctx context.Context, actorID, mai
ItemTypeID: req.ItemTypeID,
RateLimitPerHour: req.RateLimitPerHour,
ProcessingDisposition: req.ProcessingDisposition,
+ SenderAuthentication: req.SenderAuthentication,
SendConfirmation: req.SendConfirmation,
ImportExistingMail: req.ImportExistingMail,
Status: status,
diff --git a/internal/handlers/channels.go b/internal/handlers/channels.go
index 81e7ee7b4..dbd3ed280 100644
--- a/internal/handlers/channels.go
+++ b/internal/handlers/channels.go
@@ -2020,6 +2020,7 @@ 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"`
Redacted bool `json:"redacted,omitempty"`
}
@@ -2053,6 +2054,7 @@ func (h *ChannelHandler) GetEmailLog(w http.ResponseWriter, r *http.Request) {
RateLimitedAt: m.RateLimitedAt,
WorkspaceKey: m.WorkspaceKey,
WorkspaceItemNumber: m.WorkspaceItemNumber,
+ SenderAuth: m.SenderAuth,
}
// Redact sender/subject PII for rows whose target workspace the channel
// manager can't view. Channel-management permission alone is not enough
diff --git a/internal/models/intake.go b/internal/models/intake.go
index 962420895..5a26e31ad 100644
--- a/internal/models/intake.go
+++ b/internal/models/intake.go
@@ -32,6 +32,10 @@ type Intake struct {
ItemTypeID *int `json:"item_type_id,omitempty"`
RateLimitPerHour *int `json:"rate_limit_per_hour,omitempty"`
ProcessingDisposition string `json:"processing_disposition,omitempty"`
+ // SenderAuthentication overrides the mailbox's inbound sender-authentication
+ // policy for this intake. Empty inherits the mailbox default; see
+ // ChannelConfig.EmailSenderAuthentication.
+ SenderAuthentication string `json:"sender_authentication,omitempty"`
// SendConfirmation emails the sender a receipt when this intake creates a
// new item. Off by default.
SendConfirmation bool `json:"send_confirmation"`
diff --git a/internal/models/portal.go b/internal/models/portal.go
index d92e9372a..3785b8ea2 100644
--- a/internal/models/portal.go
+++ b/internal/models/portal.go
@@ -165,6 +165,11 @@ type ChannelConfig struct {
// (DefaultEmailRateLimitPerHour), 0 = unlimited, n = n. Replies to
// existing threads are never rate-limited.
EmailRateLimitPerHour *int `json:"email_rate_limit_per_hour,omitempty"`
+ // EmailSenderAuthentication is the mailbox default policy for trusting the
+ // inbound From address. "strict" (the default when empty) holds mail whose
+ // From domain does not pass an aligned SPF, DKIM, or DMARC check; "off"
+ // disables the check for providers that do not add authentication headers.
+ EmailSenderAuthentication string `json:"email_sender_authentication,omitempty"`
// 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..fa85c6c83 100644
--- a/internal/repository/channel_repository.go
+++ b/internal/repository/channel_repository.go
@@ -1094,6 +1094,9 @@ 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
}
// CountEmailMessages returns the number of email_message_tracking rows for a
@@ -1127,7 +1130,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, ''), 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 +1149,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, &workspaceItemNumber, &workspaceID, &workspaceKey); err != nil {
return nil, fmt.Errorf("scan email_message_tracking row: %w", err)
}
if fromName.Valid {
@@ -1195,6 +1198,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 +1210,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 +1245,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 +1262,7 @@ func (r *ChannelRepository) ListSystemMail(ctx context.Context, since time.Time,
var row SystemMailRow
var intakeID sql.NullInt64
if err := rows.Scan(&row.ID, &row.ChannelID, &row.ChannelName, &intakeID, &row.FromEmail,
- &row.FromName, &row.Subject, &row.Category, &row.ProcessedAt); err != nil {
+ &row.FromName, &row.Subject, &row.Category, &row.SenderAuth, &row.ProcessedAt); err != nil {
return nil, fmt.Errorf("scan skipped system mail row: %w", err)
}
if intakeID.Valid {
diff --git a/internal/repository/intake_repository.go b/internal/repository/intake_repository.go
index 54ad10102..87bda73ad 100644
--- a/internal/repository/intake_repository.go
+++ b/internal/repository/intake_repository.go
@@ -25,7 +25,7 @@ func NewIntakeRepository(db database.Database) *IntakeRepository {
const intakeSelectColumns = `
i.id, i.mailbox_id, i.folder, i.workspace_id, i.portal_channel_id,
i.request_type_id, i.item_type_id, i.rate_limit_per_hour,
- i.processing_disposition, i.send_confirmation, i.import_existing_mail, i.status, i.status_reason, i.created_at, i.updated_at,
+ i.processing_disposition, i.sender_authentication, i.send_confirmation, i.import_existing_mail, i.status, i.status_reason, i.created_at, i.updated_at,
COALESCE(c.name, '') AS mailbox_name,
COALESCE(s.last_uid, 0), COALESCE(s.uid_validity, 0), s.updated_at,
COALESCE((
@@ -47,7 +47,7 @@ func scanIntake(scanner interface {
if err := scanner.Scan(
&in.ID, &in.MailboxID, &in.Folder, &in.WorkspaceID, &portalChannelID,
&requestTypeID, &itemTypeID, &rateLimit,
- &in.ProcessingDisposition, &in.SendConfirmation, &in.ImportExistingMail, &in.Status, &in.StatusReason, &in.CreatedAt, &in.UpdatedAt,
+ &in.ProcessingDisposition, &in.SenderAuthentication, &in.SendConfirmation, &in.ImportExistingMail, &in.Status, &in.StatusReason, &in.CreatedAt, &in.UpdatedAt,
&in.MailboxName,
&in.LastUID, &in.UIDValidity, &lastPolledAt, &in.RateLimitedCount,
); err != nil {
@@ -246,10 +246,10 @@ func (r *IntakeRepository) Create(ctx context.Context, in *models.Intake) (int,
err := r.db.QueryRowContext(ctx, `
INSERT INTO intakes (
mailbox_id, folder, workspace_id, portal_channel_id, request_type_id, item_type_id,
- rate_limit_per_hour, processing_disposition, send_confirmation, import_existing_mail, status, status_reason, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id
+ rate_limit_per_hour, processing_disposition, sender_authentication, send_confirmation, import_existing_mail, status, status_reason, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id
`, in.MailboxID, folder, in.WorkspaceID, in.PortalChannelID, in.RequestTypeID, in.ItemTypeID,
- in.RateLimitPerHour, in.ProcessingDisposition, in.SendConfirmation, in.ImportExistingMail, status, in.StatusReason, now, now).Scan(&id)
+ in.RateLimitPerHour, in.ProcessingDisposition, in.SenderAuthentication, in.SendConfirmation, in.ImportExistingMail, status, in.StatusReason, now, now).Scan(&id)
if err != nil {
if database.IsUniqueConstraintError(err) {
return 0, ErrDuplicateEntry
@@ -268,10 +268,10 @@ func (r *IntakeRepository) Update(ctx context.Context, in *models.Intake) error
res, err := r.db.ExecWriteContext(ctx, `
UPDATE intakes SET
folder = ?, workspace_id = ?, portal_channel_id = ?, request_type_id = ?, item_type_id = ?,
- rate_limit_per_hour = ?, processing_disposition = ?, send_confirmation = ?, import_existing_mail = ?, status = ?, status_reason = ?, updated_at = ?
+ rate_limit_per_hour = ?, processing_disposition = ?, sender_authentication = ?, send_confirmation = ?, import_existing_mail = ?, status = ?, status_reason = ?, updated_at = ?
WHERE id = ?
`, folder, in.WorkspaceID, in.PortalChannelID, in.RequestTypeID, in.ItemTypeID,
- in.RateLimitPerHour, in.ProcessingDisposition, in.SendConfirmation, in.ImportExistingMail, in.Status, in.StatusReason, time.Now(), in.ID)
+ in.RateLimitPerHour, in.ProcessingDisposition, in.SenderAuthentication, in.SendConfirmation, in.ImportExistingMail, in.Status, in.StatusReason, time.Now(), in.ID)
if err != nil {
if database.IsUniqueConstraintError(err) {
return ErrDuplicateEntry
diff --git a/internal/scheduler/email_scheduler.go b/internal/scheduler/email_scheduler.go
index 600e1d914..d3c924b66 100644
--- a/internal/scheduler/email_scheduler.go
+++ b/internal/scheduler/email_scheduler.go
@@ -432,6 +432,7 @@ func legacyIntakeFromConfig(config *models.ChannelConfig) *models.Intake {
ItemTypeID: config.EmailItemTypeID,
RateLimitPerHour: config.EmailRateLimitPerHour,
ProcessingDisposition: config.EmailProcessingDisposition,
+ SenderAuthentication: config.EmailSenderAuthentication,
Status: models.IntakeStatusEnabled,
}
}
@@ -463,6 +464,11 @@ func (es *EmailScheduler) pollIntake(
if intake.ProcessingDisposition != "" {
effective.EmailProcessingDisposition = intake.ProcessingDisposition
}
+ // Likewise an empty sender-authentication policy inherits the mailbox
+ // default, whose own empty value is strict.
+ if intake.SenderAuthentication != "" {
+ effective.EmailSenderAuthentication = intake.SenderAuthentication
+ }
mailbox := intake.Folder
if mailbox == "" {
From 57b9b7a33718973b974234a787dfb065aec8ec3c Mon Sep 17 00:00:00 2001
From: Stefan Ernst <24554551+stefan-ernst@users.noreply.github.com>
Date: Tue, 24 Nov 2026 16:13:16 +0100
Subject: [PATCH 2/5] fix(email): address sender-authentication review findings
(WI-2362)
- Trust only results above a mailbox-specific receiver boundary: the first
Received hop whose host matches the mailbox's trusted authserv-ids
(explicit config, provider defaults, or the mail host). A result from an
untrusted authserv-id is rejected, and a message with no trusted hop fails
closed instead of trusting an arbitrary header. An internal delivery hop
above a genuine result no longer discards it.
- Parse Authentication-Results per RFC 8601: clauses split outside quoted
strings and comments, and a method is accepted only as the first token of
a clause, so a quoted diagnostic can never be read as a verdict.
- Reject Received-SPF passes without an envelope-from; a HELO pass
authenticates the sending host, not the sender.
- Use organizational-domain comparison for SPF and DKIM alignment, and
compare a DMARC header.from to the actual From domain directly, so
sibling subdomains under one organizational domain align.
- Give authentication holds a distinct action: the scheduler leaves the
original in the mailbox (never delete or mark read) and reports the hold,
including on a deduplicated retry.
- Preserve an explicit per-intake strict override when editing an intake;
it is no longer collapsed into inherit.
- Return and display skipped_reason in the channel email log so a held
message is identified instead of showing a raw spf=pass summary.
- Read header order line by line instead of splitting the whole body.
---
.../src/lib/dialogs/ChannelConfigModal.svelte | 2 +
frontend/src/lib/dialogs/EmailLogModal.svelte | 13 +
.../channels/ChannelEmailConfig.svelte | 22 +-
.../channels/ChannelIntakesSection.svelte | 8 +-
frontend/src/lib/locales/de/backfill.js | 4 +
frontend/src/lib/locales/en/channels.js | 5 +
frontend/src/lib/locales/fa/channels.js | 4 +
frontend/src/lib/locales/fr/backfill.js | 4 +
frontend/src/lib/locales/nl/channels.js | 4 +
frontend/src/lib/locales/pl/channels.js | 4 +
frontend/src/lib/locales/ru/channels.js | 4 +
frontend/src/lib/locales/zh-CN/backfill.js | 4 +
internal/email/parser.go | 11 +-
internal/email/processor.go | 24 +-
internal/email/sender_auth.go | 512 +++++++++++++++---
internal/email/types.go | 5 +
internal/handlers/channels.go | 2 +
internal/models/portal.go | 6 +
internal/repository/channel_repository.go | 8 +-
internal/scheduler/email_scheduler.go | 21 +-
20 files changed, 562 insertions(+), 105 deletions(-)
diff --git a/frontend/src/lib/dialogs/ChannelConfigModal.svelte b/frontend/src/lib/dialogs/ChannelConfigModal.svelte
index 72b4803d2..1fa4c9926 100644
--- a/frontend/src/lib/dialogs/ChannelConfigModal.svelte
+++ b/frontend/src/lib/dialogs/ChannelConfigModal.svelte
@@ -115,6 +115,7 @@
mailbox: 'INBOX',
processing_disposition: 'mark_read',
sender_authentication: '',
+ trusted_authserv_ids: '',
rate_limit_per_hour: null,
enabled: false
});
@@ -244,6 +245,7 @@
// Strict is the backend default for an empty value; normalize a
// stored "strict" so the select always has a matching option.
sender_authentication: config.email_sender_authentication === 'off' ? 'off' : '',
+ trusted_authserv_ids: (config.email_trusted_authserv_ids || []).join(', '),
rate_limit_per_hour: config.email_rate_limit_per_hour ?? null,
enabled: channel.status === 'enabled'
};
diff --git a/frontend/src/lib/dialogs/EmailLogModal.svelte b/frontend/src/lib/dialogs/EmailLogModal.svelte
index 53084e54d..c27f57b63 100644
--- a/frontend/src/lib/dialogs/EmailLogModal.svelte
+++ b/frontend/src/lib/dialogs/EmailLogModal.svelte
@@ -438,6 +438,19 @@
{t('channel.emailLog.rateLimited')}
+ {:else if msg.skipped_reason}
+
+
+
+ {msg.skipped_reason === 'unauthenticated_sender'
+ ? t('channel.emailLog.heldUnauthenticated')
+ : msg.skipped_reason}
+
{:else if msg.item_id}
{@const href = getItemHref(msg)}
diff --git a/frontend/src/lib/features/channels/ChannelEmailConfig.svelte b/frontend/src/lib/features/channels/ChannelEmailConfig.svelte
index cec111229..1e7830201 100644
--- a/frontend/src/lib/features/channels/ChannelEmailConfig.svelte
+++ b/frontend/src/lib/features/channels/ChannelEmailConfig.svelte
@@ -40,6 +40,7 @@
mailbox: 'INBOX',
processing_disposition: 'mark_read',
sender_authentication: '',
+ trusted_authserv_ids: '',
rate_limit_per_hour: null,
enabled: false
}),
@@ -149,7 +150,13 @@
email_auth_method: formData.auth_method,
email_processing_disposition: formData.processing_disposition || 'mark_read',
// Empty means strict on the backend; send the explicit value the admin chose.
- email_sender_authentication: formData.sender_authentication || ''
+ email_sender_authentication: formData.sender_authentication || '',
+ email_trusted_authserv_ids: formData.trusted_authserv_ids
+ ? formData.trusted_authserv_ids
+ .split(',')
+ .map((host) => host.trim())
+ .filter(Boolean)
+ : undefined
};
if (formData.auth_method === 'oauth') {
@@ -446,6 +453,19 @@
bind:value={formData.sender_authentication}
/>
{t('channel.senderAuthHelp')}
+ {#if formData.sender_authentication !== 'off'}
+
+
+ {t('channel.trustedAuthServersHelp')}
+
+ {/if}
-
-
- {t('channel.senderAuthHelp')}
- {#if formData.sender_authentication !== 'off'}
-
-
- {t('channel.trustedAuthServersHelp')}
-
- {/if}
-
-
diff --git a/frontend/src/lib/features/channels/ChannelIntakesSection.svelte b/frontend/src/lib/features/channels/ChannelIntakesSection.svelte
index f13607ac8..f76da3d69 100644
--- a/frontend/src/lib/features/channels/ChannelIntakesSection.svelte
+++ b/frontend/src/lib/features/channels/ChannelIntakesSection.svelte
@@ -65,7 +65,6 @@
item_type_id: null,
rate_limit_per_hour: '',
processing_disposition: '',
- sender_authentication: '',
send_confirmation: false,
import_existing_mail: false,
status: 'enabled'
@@ -101,9 +100,6 @@
if (editing.status === 'needs_attention') {
editing.status = 'disabled';
}
- // sender_authentication is loaded verbatim so an explicit "strict" is not
- // silently turned into "inherit" on an unrelated edit; inherit and strict
- // differ whenever the mailbox default is "off".
loadItemTypesForWorkspace(editing.workspace_id);
}
@@ -148,7 +144,6 @@
? null
: Number(editing.rate_limit_per_hour),
processing_disposition: editing.processing_disposition || '',
- sender_authentication: editing.sender_authentication || '',
send_confirmation: !!editing.send_confirmation,
import_existing_mail: !!editing.import_existing_mail,
status: editing.status || 'enabled'
@@ -386,22 +381,6 @@
/>
-
-
- {t('channel.senderAuthIntakeHelp')}
-
-
''
+ AND COALESCE(delivered_at, created_at) >= ?
ORDER BY id DESC
LIMIT 1
- `, canonicalID, bareID).Scan(&itemID, &recipient)
+ `, 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)
@@ -598,6 +617,31 @@ func (p *Processor) lookupReplyKey(ctx context.Context, canonicalID string) (ite
return itemID, recipient, true
}
+// lookupLegacyReplyItem resolves a pre-WI-2365 outbound Message-ID to the
+// ticket it was recorded on. Those rows carry no recipient and have no
+// recipient-bound outbox row, so they are tolerated only on the existing
+// ticket that recorded them; 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.from_email <> ''
+ AND NOT EXISTS (SELECT 1 FROM email_reply_outbox o WHERE o.message_id = t.message_id)
+ 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
diff --git a/internal/email/sender_auth.go b/internal/email/sender_auth.go
index f6de529bf..3aa35c822 100644
--- a/internal/email/sender_auth.go
+++ b/internal/email/sender_auth.go
@@ -8,43 +8,11 @@ import (
"windshift/internal/models"
)
-// SenderAuthPolicy controls whether the From address of inbound mail must be
-// backed by a passing, aligned SPF, DKIM, or DMARC result before intake trusts
-// it. The From header is entirely attacker-controlled; without this check
-// anyone who can deliver a message can claim to be a known customer and either
-// join a private thread or create a request in their name (WI-2362).
-type SenderAuthPolicy string
-
-const (
- // SenderAuthStrict holds mail whose From domain is not authenticated. It is
- // the default for any channel or intake that does not configure a policy,
- // so a missing or misspelled value can never silently disable the check.
- SenderAuthStrict SenderAuthPolicy = "strict"
- // SenderAuthOff trusts the From header the way intake did before sender
- // authentication existed. Intended for mailbox providers that do not add
- // Authentication-Results / Received-SPF headers.
- SenderAuthOff SenderAuthPolicy = "off"
-)
-
-// ResolveSenderAuthPolicy returns the effective policy. Anything other than an
-// explicit "off" resolves to strict.
-func ResolveSenderAuthPolicy(value string) SenderAuthPolicy {
- if strings.EqualFold(strings.TrimSpace(value), string(SenderAuthOff)) {
- return SenderAuthOff
- }
- return SenderAuthStrict
-}
-
-// IsValidSenderAuthPolicy reports whether value is a recognized policy or the
-// empty default sentinel.
-func IsValidSenderAuthPolicy(value string) bool {
- switch strings.ToLower(strings.TrimSpace(value)) {
- case "", string(SenderAuthStrict), string(SenderAuthOff):
- return true
- default:
- return false
- }
-}
+// 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.
diff --git a/internal/email/validation.go b/internal/email/validation.go
index d58b02e5d..3ebaea464 100644
--- a/internal/email/validation.go
+++ b/internal/email/validation.go
@@ -36,9 +36,6 @@ func ValidateConfigForEnable(channel *models.Channel, config *models.ChannelConf
if !IsValidEmailDisposition(config.EmailProcessingDisposition) {
return fmt.Errorf("%w: email_processing_disposition must be leave, mark_read, or delete", ErrConfigNotReady)
}
- if !IsValidSenderAuthPolicy(config.EmailSenderAuthentication) {
- return fmt.Errorf("%w: email_sender_authentication must be strict or off", ErrConfigNotReady)
- }
switch strings.ToLower(config.EmailAuthMethod) {
case "oauth":
diff --git a/internal/handlers/channel_intakes.go b/internal/handlers/channel_intakes.go
index d9c5dc139..7f3481a8f 100644
--- a/internal/handlers/channel_intakes.go
+++ b/internal/handlers/channel_intakes.go
@@ -22,7 +22,6 @@ type intakeRequest struct {
ItemTypeID *int `json:"item_type_id"`
RateLimitPerHour *int `json:"rate_limit_per_hour"`
ProcessingDisposition string `json:"processing_disposition"`
- SenderAuthentication string `json:"sender_authentication"`
SendConfirmation bool `json:"send_confirmation"`
ImportExistingMail bool `json:"import_existing_mail"`
Status string `json:"status"`
@@ -147,9 +146,6 @@ func (h *ChannelHandler) validateIntakeRequest(ctx context.Context, actorID, mai
if req.RateLimitPerHour != nil && *req.RateLimitPerHour < 0 {
return nil, fmt.Errorf("%w: rate_limit_per_hour must be 0 (unlimited) or a positive number", errIntakeInvalid)
}
- if !email.IsValidSenderAuthPolicy(req.SenderAuthentication) {
- return nil, fmt.Errorf("%w: sender_authentication must be strict or off", errIntakeInvalid)
- }
status := req.Status
if status == "" {
status = models.IntakeStatusEnabled
@@ -195,7 +191,6 @@ func (h *ChannelHandler) validateIntakeRequest(ctx context.Context, actorID, mai
ItemTypeID: req.ItemTypeID,
RateLimitPerHour: req.RateLimitPerHour,
ProcessingDisposition: req.ProcessingDisposition,
- SenderAuthentication: req.SenderAuthentication,
SendConfirmation: req.SendConfirmation,
ImportExistingMail: req.ImportExistingMail,
Status: status,
diff --git a/internal/models/intake.go b/internal/models/intake.go
index 5a26e31ad..962420895 100644
--- a/internal/models/intake.go
+++ b/internal/models/intake.go
@@ -32,10 +32,6 @@ type Intake struct {
ItemTypeID *int `json:"item_type_id,omitempty"`
RateLimitPerHour *int `json:"rate_limit_per_hour,omitempty"`
ProcessingDisposition string `json:"processing_disposition,omitempty"`
- // SenderAuthentication overrides the mailbox's inbound sender-authentication
- // policy for this intake. Empty inherits the mailbox default; see
- // ChannelConfig.EmailSenderAuthentication.
- SenderAuthentication string `json:"sender_authentication,omitempty"`
// SendConfirmation emails the sender a receipt when this intake creates a
// new item. Off by default.
SendConfirmation bool `json:"send_confirmation"`
diff --git a/internal/models/portal.go b/internal/models/portal.go
index 9e0a271b7..d2baa531f 100644
--- a/internal/models/portal.go
+++ b/internal/models/portal.go
@@ -165,16 +165,11 @@ type ChannelConfig struct {
// (DefaultEmailRateLimitPerHour), 0 = unlimited, n = n. Replies to
// existing threads are never rate-limited.
EmailRateLimitPerHour *int `json:"email_rate_limit_per_hour,omitempty"`
- // EmailSenderAuthentication is the mailbox default policy for trusting the
- // inbound From address. "strict" (the default when empty) holds mail whose
- // From domain does not pass an aligned SPF, DKIM, or DMARC check; "off"
- // disables the check for providers that do not add authentication headers.
- EmailSenderAuthentication string `json:"email_sender_authentication,omitempty"`
// EmailTrustedAuthServIDs lists the authentication servers (authserv-id)
// whose Authentication-Results / Received-SPF headers this mailbox trusts.
// They are the receiver boundary that proves a result was added by the
- // delivering MTA. Empty derives the hosts from the provider and mail host;
- // when nothing can be derived, strict mode holds every message.
+ // 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
diff --git a/internal/repository/intake_repository.go b/internal/repository/intake_repository.go
index 87bda73ad..54ad10102 100644
--- a/internal/repository/intake_repository.go
+++ b/internal/repository/intake_repository.go
@@ -25,7 +25,7 @@ func NewIntakeRepository(db database.Database) *IntakeRepository {
const intakeSelectColumns = `
i.id, i.mailbox_id, i.folder, i.workspace_id, i.portal_channel_id,
i.request_type_id, i.item_type_id, i.rate_limit_per_hour,
- i.processing_disposition, i.sender_authentication, i.send_confirmation, i.import_existing_mail, i.status, i.status_reason, i.created_at, i.updated_at,
+ i.processing_disposition, i.send_confirmation, i.import_existing_mail, i.status, i.status_reason, i.created_at, i.updated_at,
COALESCE(c.name, '') AS mailbox_name,
COALESCE(s.last_uid, 0), COALESCE(s.uid_validity, 0), s.updated_at,
COALESCE((
@@ -47,7 +47,7 @@ func scanIntake(scanner interface {
if err := scanner.Scan(
&in.ID, &in.MailboxID, &in.Folder, &in.WorkspaceID, &portalChannelID,
&requestTypeID, &itemTypeID, &rateLimit,
- &in.ProcessingDisposition, &in.SenderAuthentication, &in.SendConfirmation, &in.ImportExistingMail, &in.Status, &in.StatusReason, &in.CreatedAt, &in.UpdatedAt,
+ &in.ProcessingDisposition, &in.SendConfirmation, &in.ImportExistingMail, &in.Status, &in.StatusReason, &in.CreatedAt, &in.UpdatedAt,
&in.MailboxName,
&in.LastUID, &in.UIDValidity, &lastPolledAt, &in.RateLimitedCount,
); err != nil {
@@ -246,10 +246,10 @@ func (r *IntakeRepository) Create(ctx context.Context, in *models.Intake) (int,
err := r.db.QueryRowContext(ctx, `
INSERT INTO intakes (
mailbox_id, folder, workspace_id, portal_channel_id, request_type_id, item_type_id,
- rate_limit_per_hour, processing_disposition, sender_authentication, send_confirmation, import_existing_mail, status, status_reason, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id
+ rate_limit_per_hour, processing_disposition, send_confirmation, import_existing_mail, status, status_reason, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id
`, in.MailboxID, folder, in.WorkspaceID, in.PortalChannelID, in.RequestTypeID, in.ItemTypeID,
- in.RateLimitPerHour, in.ProcessingDisposition, in.SenderAuthentication, in.SendConfirmation, in.ImportExistingMail, status, in.StatusReason, now, now).Scan(&id)
+ in.RateLimitPerHour, in.ProcessingDisposition, in.SendConfirmation, in.ImportExistingMail, status, in.StatusReason, now, now).Scan(&id)
if err != nil {
if database.IsUniqueConstraintError(err) {
return 0, ErrDuplicateEntry
@@ -268,10 +268,10 @@ func (r *IntakeRepository) Update(ctx context.Context, in *models.Intake) error
res, err := r.db.ExecWriteContext(ctx, `
UPDATE intakes SET
folder = ?, workspace_id = ?, portal_channel_id = ?, request_type_id = ?, item_type_id = ?,
- rate_limit_per_hour = ?, processing_disposition = ?, sender_authentication = ?, send_confirmation = ?, import_existing_mail = ?, status = ?, status_reason = ?, updated_at = ?
+ rate_limit_per_hour = ?, processing_disposition = ?, send_confirmation = ?, import_existing_mail = ?, status = ?, status_reason = ?, updated_at = ?
WHERE id = ?
`, folder, in.WorkspaceID, in.PortalChannelID, in.RequestTypeID, in.ItemTypeID,
- in.RateLimitPerHour, in.ProcessingDisposition, in.SenderAuthentication, in.SendConfirmation, in.ImportExistingMail, in.Status, in.StatusReason, time.Now(), in.ID)
+ in.RateLimitPerHour, in.ProcessingDisposition, in.SendConfirmation, in.ImportExistingMail, in.Status, in.StatusReason, time.Now(), in.ID)
if err != nil {
if database.IsUniqueConstraintError(err) {
return ErrDuplicateEntry
diff --git a/internal/scheduler/email_scheduler.go b/internal/scheduler/email_scheduler.go
index 0d0eac38c..f8d017b16 100644
--- a/internal/scheduler/email_scheduler.go
+++ b/internal/scheduler/email_scheduler.go
@@ -432,7 +432,6 @@ func legacyIntakeFromConfig(config *models.ChannelConfig) *models.Intake {
ItemTypeID: config.EmailItemTypeID,
RateLimitPerHour: config.EmailRateLimitPerHour,
ProcessingDisposition: config.EmailProcessingDisposition,
- SenderAuthentication: config.EmailSenderAuthentication,
Status: models.IntakeStatusEnabled,
}
}
@@ -464,11 +463,6 @@ func (es *EmailScheduler) pollIntake(
if intake.ProcessingDisposition != "" {
effective.EmailProcessingDisposition = intake.ProcessingDisposition
}
- // Likewise an empty sender-authentication policy inherits the mailbox
- // default, whose own empty value is strict.
- if intake.SenderAuthentication != "" {
- effective.EmailSenderAuthentication = intake.SenderAuthentication
- }
mailbox := intake.Folder
if mailbox == "" {
@@ -524,7 +518,6 @@ func (es *EmailScheduler) pollIntake(
maxUID := sinceUID
processedCount := 0
rateLimitedCount := 0
- heldCount := 0
errorCount := 0
var lastBatchError string
var offenderUID uint32
@@ -582,15 +575,11 @@ func (es *EmailScheduler) pollIntake(
// Rate-limited mail is left untouched in the mailbox (unread, not
// deleted) so an operator can requeue it; the watermark still advances
- // past it so one flooding sender cannot wedge the intake. Mail held by a
- // strict sender-authentication policy is preserved the same way: it may
- // be the only copy of a legitimate message, and deleting it would make
- // the hold unrecoverable. Deduplicated mail still gets the configured
- // disposition: an earlier run may have created the ticket but expired
- // before marking or deleting it.
+ // past it so one flooding sender cannot wedge the intake. Deduplicated
+ // mail still gets the configured disposition: an earlier run may have
+ // created the ticket but expired before marking or deleting it.
rateLimited := result.Action == email.ActionRateLimited
- held := result.Action == email.ActionHeldForAuth
- if !rateLimited && !held {
+ if !rateLimited {
switch disposition {
case models.EmailDispositionMarkRead:
if markErr := client.MarkAsRead(msg.UID); markErr != nil {
@@ -609,8 +598,6 @@ func (es *EmailScheduler) pollIntake(
switch {
case rateLimited:
rateLimitedCount++
- case held:
- heldCount++
default:
processedCount++
}
@@ -651,7 +638,6 @@ func (es *EmailScheduler) pollIntake(
"intake_id", intake.ID,
"processed", processedCount,
"rate_limited", rateLimitedCount,
- "held_for_auth", heldCount,
"errors", errorCount,
)
diff --git a/internal/services/email_reply_service.go b/internal/services/email_reply_service.go
index 70e84efd0..fe8652211 100644
--- a/internal/services/email_reply_service.go
+++ b/internal/services/email_reply_service.go
@@ -212,11 +212,11 @@ func (s *EmailReplyService) handleCommentCreated(params HandleCommentParams, del
}
// 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.
+ // 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)
- if inReplyTo == "" {
- continue
- }
referencesJSON, err := json.Marshal(references)
if err != nil {
return fmt.Errorf("encode email references: %w", err)
@@ -563,10 +563,10 @@ func (s *EmailReplyService) sendItemNotice(item *models.Item, toEmail, toName, s
if err != nil {
return false, "", fmt.Errorf("query email tracking for customer notice: %w", err)
}
- inReplyTo, references := threadHeadersForRecipient(records, toEmail)
- if inReplyTo == "" {
+ 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 != "" {
@@ -617,6 +617,36 @@ func (s *EmailReplyService) sendItemNotice(item *models.Item, toEmail, toName, s
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. The notice is sent directly,
+ // so the row is stored as already delivered; a send failure leaves an
+ // unused key, which authorizes nothing.
+ 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,
+ from_email, from_name, reply_to_email, reply_to_name,
+ next_attempt_at, delivered_at, created_at, updated_at
+ ) VALUES ('notice', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
+ 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 {
+ slog.Warn("failed to persist customer notice reply key",
+ slog.String("component", "email_reply_service"),
+ slog.Int("item_id", item.ID),
+ slog.String("message_id", messageID),
+ slog.Any("error", err),
+ )
+ }
+
if err := s.smtpSender.SendThreadedEmail(smtp.ThreadedEmailParams{
ToEmail: toEmail,
ToName: toName,
@@ -632,15 +662,8 @@ 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, and persist it in the outbox as a recipient-bound
- // reply key so an inbound reply can authorize against it (WI-2365).
- // Best-effort: the mail is already sent.
- referencesJSON, err := json.Marshal(references)
- if err != nil {
- referencesJSON = []byte("[]")
- }
+ // 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,
@@ -655,27 +678,6 @@ func (s *EmailReplyService) sendItemNotice(item *models.Item, toEmail, toName, s
slog.Any("error", err),
)
}
- // The notice is sent directly rather than queued, so its outbox row is
- // recorded as already delivered: it is a reply key, not pending work.
- 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,
- from_email, from_name, reply_to_email, reply_to_name,
- next_attempt_at, delivered_at, created_at, updated_at
- ) VALUES ('notice', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
- 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 {
- slog.Warn("failed to record customer notice reply key",
- slog.String("component", "email_reply_service"),
- slog.Int("item_id", item.ID),
- slog.String("message_id", messageID),
- slog.Any("error", err),
- )
- }
return true, "", nil
}
@@ -865,8 +867,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)
}
From 03c08d7f059f96c1fa3a5115323c17b4c30f7409 Mon Sep 17 00:00:00 2001
From: Stefan Ernst <24554551+stefan-ernst@users.noreply.github.com>
Date: Tue, 24 Nov 2026 21:29:58 +0100
Subject: [PATCH 5/5] fix(email): address WI-2365 review findings
- Add key_generation to the reply outbox and tracking rows. Only generation
>= 1 authorizes a reply, and the tracking marker survives outbox pruning, so
an expired or pre-upgrade ID can never become valid again. Pre-upgrade
tracking IDs (generation 0) are tolerated only on a ticket that has never
issued a recipient-bound key.
- Record an unverified inbound sender as items.contact_email/contact_name
instead of creator_portal_customer_id. A claimed From no longer makes a new
request appear in a customer's portal or organisation sharing; a verified
reply promotes the contact to the portal owner.
- Persist a notice's reply key before SMTP and fail the notice if the key
cannot be saved, instead of sending an unroutable Message-ID.
- Merge inbound messages and delivered reply keys chronologically so a staff
reply names the customer's latest message as its parent, and exclude pending
or discarded outbox rows from the thread.
- Index email_reply_outbox(message_id) and (item_id, created_at) so reply
matching and thread assembly no longer scan the retained outbox.
---
internal/database/migrations.go | 36 +++++++
internal/database/schema/email.sql | 15 +++
internal/database/schema/email_postgres.sql | 11 ++
internal/database/schema/items.sql | 6 ++
internal/database/schema/items_postgres.sql | 3 +
internal/email/processor.go | 107 +++++++++++++-------
internal/models/item.go | 5 +
internal/repository/item_repository.go | 18 +++-
internal/services/email_reply_service.go | 107 +++++++++++---------
internal/services/item_creation.go | 1 +
internal/services/items.go | 28 ++---
11 files changed, 238 insertions(+), 99 deletions(-)
diff --git a/internal/database/migrations.go b/internal/database/migrations.go
index 3ea5bdd77..b68b25fc0 100644
--- a/internal/database/migrations.go
+++ b/internal/database/migrations.go
@@ -3750,6 +3750,42 @@ END $$;
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 fa3e46c1b..c928fbfd6 100644
--- a/internal/database/schema/email.sql
+++ b/internal/database/schema/email.sql
@@ -125,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
@@ -165,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);
@@ -189,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,
@@ -217,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 83002a74d..dce6fa66a 100644
--- a/internal/database/schema/email_postgres.sql
+++ b/internal/database/schema/email_postgres.sql
@@ -112,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')),
@@ -131,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);
@@ -153,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,
@@ -179,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/processor.go b/internal/email/processor.go
index 65cc207cf..0fce4e1d9 100644
--- a/internal/email/processor.go
+++ b/internal/email/processor.go
@@ -170,22 +170,6 @@ func (p *Processor) ProcessEmailWithIntake(
parentItemID = p.findParentItem(ctx, email)
}
- // 2. Resolve the sender to a portal customer. An authorized reply proves
- // the sender controls the address Windshift wrote to, so it also restores
- // channel access; a brand new request records a contact address only and
- // grants no portal or thread access from the claimed From.
- 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 parentItemID != nil {
- 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)
- }
- }
-
// Flood protection gates NEW conversations only; replies keep flowing.
if parentItemID == nil && p.senderIsRateLimited(ctx, channelID, intakeID, config, email.From.Address) {
p.markRateLimited(ctx, channelID, dedupKey)
@@ -198,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 {
@@ -205,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 {
@@ -213,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
@@ -604,6 +608,7 @@ func (p *Processor) lookupReplyKey(ctx context.Context, canonicalID string) (ite
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
@@ -618,18 +623,20 @@ func (p *Processor) lookupReplyKey(ctx context.Context, canonicalID string) (ite
}
// lookupLegacyReplyItem resolves a pre-WI-2365 outbound Message-ID to the
-// ticket it was recorded on. Those rows carry no recipient and have no
-// recipient-bound outbox row, so they are tolerated only on the existing
-// ticket that recorded them; synthetic anchors (from_email = ”) never
-// authorize.
+// 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.from_email <> ''
- AND NOT EXISTS (SELECT 1 FROM email_reply_outbox o WHERE o.message_id = t.message_id)
+ 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)
@@ -650,6 +657,14 @@ func (p *Processor) senderStillAuthorized(_ context.Context, itemID int, senderE
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 {
@@ -664,6 +679,24 @@ func (p *Processor) senderStillAuthorized(_ context.Context, itemID int, senderE
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
+ }
+ 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)
+ }
+}
+
// 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
@@ -693,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)
@@ -724,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/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/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/services/email_reply_service.go b/internal/services/email_reply_service.go
index fe8652211..ebaa04a03 100644
--- a/internal/services/email_reply_service.go
+++ b/internal/services/email_reply_service.go
@@ -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
}
@@ -231,10 +238,10 @@ func (s *EmailReplyService) handleCommentCreated(params HandleCommentParams, del
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,
@@ -381,16 +388,19 @@ type emailThreadRecord struct {
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; outbound reply keys come from email_reply_outbox,
-// which alone records the intended recipient (WI-2365).
+// 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, '' FROM email_message_tracking
+ 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
@@ -400,7 +410,7 @@ func (s *EmailReplyService) loadItemThread(itemID int) ([]emailThreadRecord, err
}
for rows.Next() {
var rec emailThreadRecord
- if err := rows.Scan(&rec.MessageID, &rec.Subject, &rec.Direction, &rec.ToEmail); err != nil {
+ if err := rows.Scan(&rec.MessageID, &rec.Subject, &rec.Direction, &rec.ToEmail, &rec.At); err != nil {
continue
}
records = append(records, rec)
@@ -413,12 +423,14 @@ func (s *EmailReplyService) loadItemThread(itemID int) ([]emailThreadRecord, err
return nil, fmt.Errorf("close email tracking rows: %w", err)
}
- // Outbound deliveries persist item, recipient and Message-ID together; the
- // row is the recipient-bound reply key.
+ // 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 FROM email_reply_outbox
+ SELECT message_id, subject, to_email, delivered_at FROM email_reply_outbox
WHERE item_id = ? AND message_id <> '' AND to_email <> ''
- ORDER BY created_at ASC, id ASC
+ 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)
@@ -426,7 +438,7 @@ func (s *EmailReplyService) loadItemThread(itemID int) ([]emailThreadRecord, err
defer keyRows.Close()
for keyRows.Next() {
var rec emailThreadRecord
- if err := keyRows.Scan(&rec.MessageID, &rec.Subject, &rec.ToEmail); err != nil {
+ if err := keyRows.Scan(&rec.MessageID, &rec.Subject, &rec.ToEmail, &rec.At); err != nil {
continue
}
rec.Direction = "outbound"
@@ -435,6 +447,7 @@ func (s *EmailReplyService) loadItemThread(itemID int) ([]emailThreadRecord, err
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
}
@@ -624,27 +637,21 @@ func (s *EmailReplyService) sendItemNotice(item *models.Item, toEmail, toName, s
// 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. The notice is sent directly,
- // so the row is stored as already delivered; a send failure leaves an
- // unused key, which authorizes nothing.
+ // 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, 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, delivered_at, created_at, updated_at
- ) VALUES ('notice', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
+ ) 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 {
- slog.Warn("failed to persist customer notice reply key",
- slog.String("component", "email_reply_service"),
- slog.Int("item_id", item.ID),
- slog.String("message_id", messageID),
- slog.Any("error", err),
- )
+ return false, "", fmt.Errorf("persist customer notice reply key: %w", err)
}
if err := s.smtpSender.SendThreadedEmail(smtp.ThreadedEmailParams{
@@ -667,8 +674,8 @@ func (s *EmailReplyService) sendItemNotice(item *models.Item, toEmail, toName, s
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",
@@ -692,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) {
@@ -712,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"
}
@@ -742,10 +755,10 @@ func (s *EmailReplyService) EnqueueIntakeConfirmation(itemID, customerID int) er
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,
@@ -938,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
|