Files
warmbly/internal/repository/pg_email.go
T

3019 lines
128 KiB
Go

package repository
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/warmbly/warmbly/internal/app/mailcred"
"github.com/warmbly/warmbly/internal/config"
"github.com/warmbly/warmbly/internal/errx"
"github.com/warmbly/warmbly/internal/infrastructure/db"
"github.com/warmbly/warmbly/internal/models"
"github.com/warmbly/warmbly/internal/observability/errs"
"github.com/warmbly/warmbly/internal/pkg/encrypt"
"github.com/warmbly/warmbly/internal/pkg/mailvendor"
"github.com/warmbly/warmbly/internal/utils"
"github.com/warmbly/warmbly/internal/utils/paging"
"github.com/warmbly/warmbly/internal/utils/validate"
)
// SMTPCredentials holds SMTP/IMAP server credentials
type SMTPCredentials struct {
SMTPHost string
SMTPPort int
SMTPUser string
SMTPPassword string
SMTPSecurity string
IMAPHost string
IMAPPort int
IMAPUser string
IMAPPassword string
IMAPSecurity string
// Owner opt-outs from CA verification and the pinned SPKI SHA-256 for each server.
SMTPTLSUnverified bool
SMTPTLSPin string
IMAPTLSUnverified bool
IMAPTLSPin string
}
// OAuthCredentials holds OAuth token credentials
type OAuthCredentials struct {
AccessToken string
RefreshToken string
ExpiresAt time.Time
// GrantedScopes is what the provider granted the token; nil when not recorded.
GrantedScopes []string
// OAuthAppID is the workspace client that issued the grant; nil is this deployment's own.
OAuthAppID *uuid.UUID
}
// AccountScope confines a mailbox lookup to one tenant. The organization is the
// tenant boundary: a multi-org user must never send organization A's campaign
// from an organization B mailbox, so resolution keys on organization_id and
// never on the owner.
type AccountScope struct {
// OrgID is the tenant key. Nil is not a wildcard — it resolves to no
// mailboxes at all, matching how the campaign task halts an orgless
// campaign rather than sending it unchecked.
OrgID *uuid.UUID
}
// NewAccountScope builds the scope for an organization, treating the nil UUID
// the same as no organization.
func NewAccountScope(orgID *uuid.UUID) AccountScope {
if orgID != nil && *orgID == uuid.Nil {
orgID = nil
}
return AccountScope{OrgID: orgID}
}
// tenant returns the organization to query for, and false when the scope has
// none — the caller then answers "no mailboxes" instead of running a query with
// an unbound tenant.
func (s AccountScope) tenant() (uuid.UUID, bool) {
if s.OrgID == nil {
return uuid.Nil, false
}
return *s.OrgID, true
}
type EmailRepository interface {
Search(ctx context.Context, userID, search string, cursor, tag *string, limit int32, allowedAccountIDs []uuid.UUID) (*models.EmailsResult, *errx.Error)
Get(ctx context.Context, userID, emailAccountID string) (*models.Email, *errx.Error)
GetByID(ctx context.Context, emailAccountID uuid.UUID) (*models.Email, *errx.Error)
// GetByTags returns the scope's active mailboxes carrying any of the tags.
GetByTags(ctx context.Context, scope AccountScope, tags []string) ([]models.Email, *errx.Error)
// GetAllActiveInScope returns every active mailbox in the scope (no
// tag/sender filter) — the "all" sender pool used when a campaign picks
// neither tags nor explicit accounts.
GetAllActiveInScope(ctx context.Context, scope AccountScope) ([]models.Email, *errx.Error)
// GetByCampaignSenders returns the active mailboxes in a campaign's explicit
// sender pool, carrying each sender's rotation metadata (weight,
// rotation_position, last_sent_at) for the scheduler's rotation modes.
GetByCampaignSenders(ctx context.Context, scope AccountScope, campaignID uuid.UUID) ([]CampaignSenderAccount, *errx.Error)
GetSMTPCredentials(ctx context.Context, emailAccountID uuid.UUID) (*SMTPCredentials, *errx.Error)
GetOAuthCredentials(ctx context.Context, emailAccountID uuid.UUID) (*OAuthCredentials, *errx.Error)
GetWorkerID(ctx context.Context, emailAccountID uuid.UUID) (*uuid.UUID, *errx.Error)
SetStatus(ctx context.Context, emailAccountID uuid.UUID, status string) *errx.Error
SetWorkerID(ctx context.Context, emailAccountID, workerID uuid.UUID) *errx.Error
Update(ctx context.Context, orgID, emailAccountID string, udata *models.UpdateEmail) (*models.Email, *errx.Error)
// GetSendIdentity reads the mailbox's stored sending identity: the
// provider's send-as list as last reported, which of them is in use, and
// where the stored signature came from. Organization-scoped like Get.
GetSendIdentity(ctx context.Context, orgID, emailAccountID string) (*models.SendIdentity, *errx.Error)
// SetSendIdentity records a fresh send-as list, and the imported signature
// when one was asked for. A chosen alias the provider no longer verifies
// is cleared in the same statement, so a revoked alias stops being used
// rather than failing every send.
SetSendIdentity(ctx context.Context, emailAccountID uuid.UUID, identities []models.SendAsIdentity, sig *models.ImportedSignature) *errx.Error
// BulkUpdateTags adds/removes tag links across many of the workspace's
// mailboxes in one transaction; ownership of both mailboxes and tags is
// enforced in SQL, unknown ids are skipped. Returns how many of the
// requested mailboxes the workspace owns.
BulkUpdateTags(ctx context.Context, orgID string, emailIDs, addTags, removeTags []uuid.UUID) (int, *errx.Error)
// SetWarmupLifecycle starts, pauses, resumes, or disables warmup for a
// mailbox. "start"/"resume" preserve ramp progress (a paused mailbox
// resumes where it left off); "pause" keeps progress; "disable" turns
// warmup off entirely. The timestamp math runs in SQL so the transition
// is atomic and idempotent.
SetWarmupLifecycle(ctx context.Context, orgID, emailAccountID, action string) (*models.Email, *errx.Error)
UpdateTrackingDomain(ctx context.Context, orgID, emailAccountID, domain string, verified bool, verifiedAt *time.Time) *errx.Error
UpdateTrackDirectMail(ctx context.Context, orgID, emailAccountID string, enabled bool) *errx.Error
// GetSyncSkipFolders is the folders this mailbox's sync leaves alone.
// Read without a tenant predicate by the loader, which ships it to the
// worker inside the mailbox's sync policy.
GetSyncSkipFolders(ctx context.Context, emailAccountID uuid.UUID) ([]string, *errx.Error)
// SetSyncSkipFolders replaces that list, scoped by organization like every
// other mailbox setting a workspace admin may change.
SetSyncSkipFolders(ctx context.Context, orgID, emailAccountID string, folders []string) *errx.Error
// ListOrganizationIDs names every workspace with a mailbox, for sweeps that
// run per workspace rather than per event.
ListOrganizationIDs(ctx context.Context) ([]uuid.UUID, error)
// ListTrackingDomainCheckDue returns active mailboxes with a custom
// tracking domain that has not been resolved since staleBefore (or never),
// oldest-first. Drives the background re-verification sweep.
ListTrackingDomainCheckDue(ctx context.Context, staleBefore time.Time, limit int) ([]models.TrackingDomainTarget, *errx.Error)
// SetTrackingDomainVerified records a sweep's verdict for one mailbox. It
// never touches the domain itself.
SetTrackingDomainVerified(ctx context.Context, emailAccountID uuid.UUID, verified bool, verifiedAt *time.Time) *errx.Error
// ListAuthCheckDue returns active mailboxes whose sending-domain auth state
// has not been evaluated since staleBefore (or never), oldest-first, capped
// at limit. Drives the background SPF/DKIM/DMARC sweep.
ListAuthCheckDue(ctx context.Context, staleBefore time.Time, limit int) ([]models.EmailAuthTarget, *errx.Error)
// MarkDomainAuthRecheck clears the sweep checkpoint for a sending domain so
// the next pass re-checks it first. Used when a receiving server refuses
// mail on authentication grounds: that is strong evidence, but DNS is the
// authority, so the sweep confirms rather than this asserting a verdict.
MarkDomainAuthRecheck(ctx context.Context, domain string) error
// UpdateDomainAuthState records the SPF/DKIM/DMARC result for every active
// mailbox on the given sending domain in one write (auth is a per-domain
// property). checkedAt stamps the evaluation so the sweep can skip fresh
// domains. It returns the mailboxes that entered the failing state on THIS
// call, which is what the sweep notifies on.
UpdateDomainAuthState(ctx context.Context, domain, state string, spf, dkim, dmarc bool, dmarcPolicy, reason string, checkedAt time.Time) ([]models.EmailAuthTransition, *errx.Error)
// UpdateDomainAuthStateForOrg is the same write confined to one
// organization's mailboxes. The user-facing "check again" button uses it:
// the verdict comes from public DNS so it cannot be poisoned, but one
// workspace pressing a button must not rewrite rows belonging to every
// other workspace that happens to send from the same domain.
UpdateDomainAuthStateForOrg(ctx context.Context, orgID uuid.UUID, domain, state string, spf, dkim, dmarc bool, dmarcPolicy, reason string, checkedAt time.Time) ([]models.EmailAuthTransition, *errx.Error)
// Delete removes a mailbox and refunds workerLoadRefund of its worker's
// load in the same transaction, so a deleted mailbox can never leave a
// worker permanently charged for it.
Delete(ctx context.Context, orgID, emailAccountID string, workerLoadRefund float64) *errx.Error
NewOauthAccount(ctx context.Context, userID string, data models.NewOauthAccount) (*models.Email, *errx.Error)
// NewManagedAccount creates an OAuth mailbox whose credential lives on Warmbly Cloud, so no token row is written.
NewManagedAccount(ctx context.Context, userID string, data models.NewOauthAccount) (*models.Email, *errx.Error)
NewSMTPIMAPAccount(ctx context.Context, userID string, data models.NewSMTPIMAPAccount) (*models.Email, *errx.Error)
RefreshBoxToken(ctx context.Context, id uuid.UUID, accessToken, refreshToken string, expiresAt time.Time) error
// ReplaceBoxToken stores a new consent's tokens with the scopes it granted; nil scopes records them as unknown.
ReplaceBoxToken(ctx context.Context, id uuid.UUID, accessToken, refreshToken string, expiresAt time.Time, scopes []string, appID *uuid.UUID) error
// RefreshBoxTokenSealed stores a refreshed token a worker sealed under the mailbox's organization key.
RefreshBoxTokenSealed(ctx context.Context, id uuid.UUID, sealed string, expiresAt time.Time) error
// RefreshWorkerBoxToken is RefreshBoxToken for a worker's refresh, dropped for a mailbox a workspace app signed in.
RefreshWorkerBoxToken(ctx context.Context, id uuid.UUID, accessToken, refreshToken string, expiresAt time.Time) error
// RefreshBoxTokenForApp stores a backend refresh through appID, dropped when another client issued the grant since.
RefreshBoxTokenForApp(ctx context.Context, id uuid.UUID, accessToken, refreshToken string, expiresAt time.Time, appID *uuid.UUID) error
// ReplaceSMTPIMAPCredentials overwrites a mailbox's SMTP/IMAP credential
// row, sealed on the same terms as at connect time.
ReplaceSMTPIMAPCredentials(ctx context.Context, id uuid.UUID, creds *models.SmtpImap) error
// ExistsForUser checks whether the given (user_id, email) pair is already connected.
ExistsForUser(ctx context.Context, userID, email string) (bool, *errx.Error)
// FindInOrganization is the workspace's mailbox with this address, case-insensitive; nil when none.
FindInOrganization(ctx context.Context, orgID uuid.UUID, email string) (*models.EmailRef, *errx.Error)
// FindManyInOrganization is FindInOrganization for a batch, keyed by the lower-cased address.
FindManyInOrganization(ctx context.Context, orgID uuid.UUID, emails []string) (map[string]models.EmailRef, *errx.Error)
// NewDelegatedAccount stores a mailbox reached through an administrator's grant.
NewDelegatedAccount(ctx context.Context, userID string, data models.NewDelegatedAccount) (*models.Email, *errx.Error)
// ConvertToDelegated moves a per-mailbox sign-in onto an administrator's grant in place; false when it was not one.
ConvertToDelegated(ctx context.Context, orgID, accountID uuid.UUID, provider models.InboxProvider, grantID uuid.UUID, subject, mailHost string) (bool, *errx.Error)
// ConvertGoogleToAppPassword moves a per-mailbox Google sign-in onto an app password in place; false when it was not one.
ConvertGoogleToAppPassword(ctx context.Context, orgID, accountID uuid.UUID, creds *models.SmtpImap, mailHost string) (bool, *errx.Error)
// ConvertToGoogleOAuth moves a delegated or app-password Google mailbox onto its own Google sign-in in place; false when it was neither.
ConvertToGoogleOAuth(ctx context.Context, orgID, accountID uuid.UUID, accessToken, refreshToken string, expiresAt time.Time, mailHost string, scopes []string) (bool, *errx.Error)
// ListSigninRetiring is the workspace's mailboxes still on per-mailbox Google sign-in.
ListSigninRetiring(ctx context.Context, orgID uuid.UUID) ([]models.MigrationMailbox, *errx.Error)
// RelinkDelegated points an existing delegated mailbox at a grant again (one that arrived in an archive without it).
RelinkDelegated(ctx context.Context, orgID, accountID, grantID uuid.UUID, subject string) *errx.Error
// GetDelegation is a delegated mailbox's grant and subject; nil when the mailbox is not delegated.
GetDelegation(ctx context.Context, accountID uuid.UUID) (*models.DelegatedMailbox, *errx.Error)
// DomainsOverview is every domain the workspace has mailboxes on, with their auth and tracking state.
DomainsOverview(ctx context.Context, orgID uuid.UUID) ([]models.SendingDomain, *errx.Error)
// CountDomainMailboxes is how many of the workspace's mailboxes are on a domain.
CountDomainMailboxes(ctx context.Context, orgID uuid.UUID, domain string) (int, *errx.Error)
// OwnedDomains are the domains the workspace has a mailbox on and the tracking hosts verified on them.
OwnedDomains(ctx context.Context, orgID uuid.UUID) ([]string, *errx.Error)
// SetDomainTracking sets one tracking host on every workspace mailbox on a domain.
SetDomainTracking(ctx context.Context, orgID uuid.UUID, domain, host string, verified bool, verifiedAt *time.Time) (int, *errx.Error)
// SetVendorLink records which vendor account a mailbox came from, for automatic reconnects.
SetVendorLink(ctx context.Context, accountID, connectionID uuid.UUID, vendorMailboxID string) *errx.Error
// SetMailHost records where a mailbox is hosted; an empty authMethod keeps the stored one.
SetMailHost(ctx context.Context, id uuid.UUID, mailHost, authMethod string) *errx.Error
// ListUnclassifiedDomains is up to limit domains with a mailbox whose host is not known yet.
ListUnclassifiedDomains(ctx context.Context, limit int) ([]string, *errx.Error)
// SetDomainMailHost classifies every unclassified mailbox on a domain;
// passwordAuthMethod is what a password-connected one of them signs in with.
SetDomainMailHost(ctx context.Context, domain, mailHost, passwordAuthMethod string) *errx.Error
// CountForOrganization returns the number of email accounts attached to the
// given organization. Used by the free-trial inbox cap.
CountForOrganization(ctx context.Context, orgID uuid.UUID) (int, *errx.Error)
// CountWarmingForOrganization counts the workspace's active mailboxes with warmup on and not paused.
CountWarmingForOrganization(ctx context.Context, orgID uuid.UUID) (int, *errx.Error)
// ListWarmupScheduleCandidates returns active mailboxes that should have a
// running warmup chain but currently have no pending warmup task: either
// actively warming, or backing a live campaign (the health-check lane).
// Used by the warmup reconciler to (re)seed chains.
ListWarmupScheduleCandidates(ctx context.Context, limit int) ([]uuid.UUID, error)
// ListActiveWorkerAccounts returns every active mailbox with the worker it
// is assigned to. The worker reconciler uses it to (re)load accounts onto
// their assigned workers after onboarding, worker restarts, or reassignment.
ListActiveWorkerAccounts(ctx context.Context) ([]MailboxAssignment, error)
// ListActiveAccountsByWorker returns the ids of the active mailboxes
// assigned to one worker, for reloading them after that worker restarts.
ListActiveAccountsByWorker(ctx context.Context, workerID uuid.UUID) ([]uuid.UUID, error)
}
type emailRepository struct {
DB *db.DB
Creds *mailcred.Sealer
transportSnapshot pgx.Tx
}
type EmailTransportSnapshot interface {
WithTransportSnapshot(context.Context, func(EmailRepository) error) error
}
func (r *emailRepository) WithTransportSnapshot(ctx context.Context, read func(EmailRepository) error) error {
tx, err := r.DB.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if err != nil {
return err
}
defer tx.Rollback(ctx)
snapshot := &emailRepository{DB: r.DB, Creds: r.Creds, transportSnapshot: tx}
if err := read(snapshot); err != nil {
return err
}
return tx.Commit(ctx)
}
func (r *emailRepository) transportQueryRow(ctx context.Context, query string, args ...any) pgx.Row {
if r.transportSnapshot != nil {
return r.transportSnapshot.QueryRow(ctx, query, args...)
}
return r.DB.QueryRow(ctx, query, args...)
}
// NewEmailRepostory builds the email repository with credentials sealed under
// the instance key only; nil is tolerated so deployments without the key keep
// booting, but credential reads/writes then fail with a captured error.
func NewEmailRepostory(db *db.DB, enc *encrypt.Encrypter) EmailRepository {
return NewEmailRepositoryWithSealer(db, &mailcred.Sealer{Instance: enc, Mode: mailcred.ModeInstance})
}
// NewEmailRepositoryWithSealer builds the email repository over a mailbox credential sealer.
func NewEmailRepositoryWithSealer(db *db.DB, creds *mailcred.Sealer) EmailRepository {
return &emailRepository{
DB: db,
Creds: creds,
}
}
// sealCredentials seals mailbox credentials for storage. It fails closed: without a key the caller aborts rather than writing plaintext.
func (r *emailRepository) sealCredentials(ctx context.Context, orgID *uuid.UUID, plains ...string) ([]string, error) {
if r.Creds == nil {
return nil, mailcred.ErrNoKey
}
return r.Creds.SealAll(ctx, orgID, plains...)
}
// openCredential returns the plaintext behind a stored credential, reporting
// whether the row was still in the pre-sealing plaintext format.
//
// Rows written before OAuth tokens were sealed hold the provider token verbatim
// ("ya29...", "1//0g...", a Graph JWT), none of which is valid hex, so only a
// value outside the sealed format is legacy. Callers re-seal on the spot so the
// plaintext window closes on first read.
func (r *emailRepository) openCredential(ctx context.Context, orgID *uuid.UUID, stored string) (string, bool, error) {
if r.Creds == nil {
return "", false, mailcred.ErrNoKey
}
return r.Creds.OpenOrLegacy(ctx, orgID, stored)
}
// openCredentials opens sealed credentials that have no legacy plaintext form.
func (r *emailRepository) openCredentials(ctx context.Context, orgID *uuid.UUID, stored ...*string) error {
if r.Creds == nil {
return mailcred.ErrNoKey
}
for _, v := range stored {
plain, err := r.Creds.Open(ctx, orgID, *v)
if err != nil {
return err
}
*v = plain
}
return nil
}
func (r *emailRepository) FindInOrganization(ctx context.Context, orgID uuid.UUID, email string) (*models.EmailRef, *errx.Error) {
query := `SELECT id, provider, status, auth_method, ` + managedExpr + ` FROM email_accounts ea WHERE organization_id = $1 AND lower(email) = lower($2) ORDER BY created_at LIMIT 1`
var ref models.EmailRef
err := r.DB.QueryRow(ctx, query, orgID, strings.TrimSpace(email)).Scan(&ref.ID, &ref.Provider, &ref.Status, &ref.AuthMethod, &ref.Managed)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
db.CaptureError(err, query, nil, "queryrow")
return nil, errx.InternalError()
}
return &ref, nil
}
func (r *emailRepository) FindManyInOrganization(ctx context.Context, orgID uuid.UUID, emails []string) (map[string]models.EmailRef, *errx.Error) {
out := make(map[string]models.EmailRef, len(emails))
if len(emails) == 0 {
return out, nil
}
lowered := make([]string, 0, len(emails))
for _, e := range emails {
lowered = append(lowered, strings.ToLower(strings.TrimSpace(e)))
}
query := `
SELECT DISTINCT ON (lower(email)) lower(email), id, provider, status, auth_method, ` + managedExpr + `
FROM email_accounts ea
WHERE organization_id = $1 AND lower(email) = ANY($2)
ORDER BY lower(email), created_at`
rows, err := r.DB.Query(ctx, query, orgID, lowered)
if err != nil {
db.CaptureError(err, query, nil, "query")
return nil, errx.InternalError()
}
defer rows.Close()
for rows.Next() {
var key string
var ref models.EmailRef
if err := rows.Scan(&key, &ref.ID, &ref.Provider, &ref.Status, &ref.AuthMethod, &ref.Managed); err != nil {
db.CaptureError(err, query, nil, "scan")
return nil, errx.InternalError()
}
out[key] = ref
}
if err := rows.Err(); err != nil {
db.CaptureError(err, query, nil, "rows")
return nil, errx.InternalError()
}
return out, nil
}
func withNewMailboxBehavior(query string, enabled bool) string {
return `WITH mailbox AS (` + query + ` RETURNING id)
INSERT INTO email_account_behavior(email_account_id,enabled) SELECT id,` + strconv.FormatBool(enabled) + ` FROM mailbox`
}
func (r *emailRepository) NewDelegatedAccount(ctx context.Context, userID string, data models.NewDelegatedAccount) (*models.Email, *errx.Error) {
if data.Provider != models.InboxProviderGoogle && data.Provider != models.InboxProviderOutlook {
errs.CaptureException(errors.New("delegated account: unsupported provider"))
return nil, errx.InternalError()
}
tx, err := r.DB.Begin(ctx)
if err != nil {
db.CaptureError(err, "", nil, "begin")
return nil, errx.InternalError()
}
defer tx.Rollback(ctx)
if xerr := reserveMailboxSlotTx(ctx, tx, data.OrganizationID, data.Allowance); xerr != nil {
return nil, xerr
}
if xerr := ensureMailboxAbsentTx(ctx, tx, data.OrganizationID, data.Email); xerr != nil {
return nil, xerr
}
id := uuid.New()
t := time.Now()
query := withNewMailboxBehavior(`
INSERT INTO email_accounts (id, user_id, organization_id, email, name, provider, signature_plain, signature_html,
tracking_domain, last_synced_at, created_at, updated_at, warmup_tag, mail_host, auth_method, domain_grant_id, delegated_subject)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, '', $9, $9, $9, '', $10, $11, $12, $13)`, true)
if _, err := tx.Exec(ctx, query, id, userID, data.OrganizationID, data.Email, data.Name, data.Provider,
utils.GetSignaturePlain(data.Name), utils.GetSignatureHTML(data.Name), t,
data.MailHost, models.MailAuthDelegated, data.GrantID, data.Subject); err != nil {
db.CaptureError(err, query, nil, "exec")
return nil, errx.InternalError()
}
if err := tx.Commit(ctx); err != nil {
db.CaptureError(err, "", nil, "commit")
return nil, errx.InternalError()
}
return r.GetByID(ctx, id)
}
// managedExpr is whether the mailbox aliased ea holds a token another instance
// depends on: managed through Warmbly Cloud here, or lent to a linked instance.
const managedExpr = `(EXISTS (SELECT 1 FROM cloud_link_mailboxes clm WHERE clm.email_account_id = ea.id AND clm.managed)
OR EXISTS (SELECT 1 FROM pool_link_mailboxes plm WHERE plm.email_account_id = ea.id AND plm.managed))`
// ConvertToDelegated moves a per-mailbox sign-in onto an administrator's grant
// in place, so its history, campaigns and warmup stay; the stored token goes.
func (r *emailRepository) ConvertToDelegated(ctx context.Context, orgID, accountID uuid.UUID, provider models.InboxProvider, grantID uuid.UUID, subject, mailHost string) (bool, *errx.Error) {
query := `UPDATE email_accounts ea SET auth_method = 'delegated', domain_grant_id = $4, delegated_subject = $5,
mail_host = CASE WHEN $6 = '' THEN mail_host ELSE $6 END, updated_at = now()
WHERE organization_id = $1 AND id = $2 AND provider = $3::email_provider AND auth_method = 'oauth' AND NOT ` + managedExpr
steps := []txStep{{`DELETE FROM email_accounts_oauth WHERE email_account_id = $1`, []any{accountID}}}
if provider == models.InboxProviderOutlook {
// Graph cursors name /me, which an application token cannot call; the
// worker re-primes each folder from "now" and restarts any unfinished backfill.
steps = append(steps,
txStep{`DELETE FROM email_delta_links WHERE email_id = $1`, []any{accountID}},
txStep{`UPDATE email_sync_state SET backfill_cursor = '{}'::jsonb, updated_at = now() WHERE email_id = $1`, []any{accountID}})
}
return r.convertTx(ctx, query, []any{orgID, accountID, string(provider), grantID, subject, mailHost}, steps)
}
// ConvertGoogleToAppPassword moves a Google mailbox on its own sign-in or a grant
// onto IMAP and SMTP with an app password in place. Mail already imported stays,
// so the history walk is marked done and IMAP picks up from new mail.
func (r *emailRepository) ConvertGoogleToAppPassword(ctx context.Context, orgID, accountID uuid.UUID, creds *models.SmtpImap, mailHost string) (bool, *errx.Error) {
if creds == nil || creds.SMTP == nil || creds.IMAP == nil {
return false, errx.ErrInvalid
}
sealed, err := r.sealCredentials(ctx, &orgID, creds.SMTP.Host, creds.SMTP.Username, creds.SMTP.Password, creds.IMAP.Host, creds.IMAP.Username, creds.IMAP.Password)
if err != nil {
db.CaptureError(err, "", nil, "encrypt-smtp-imap")
return false, errx.InternalError()
}
query := `UPDATE email_accounts ea SET provider = 'smtp_imap', auth_method = 'app_password',
mail_host = CASE WHEN $3 = '' THEN mail_host ELSE $3 END, last_id = NULL, domain_grant_id = NULL, delegated_subject = '', updated_at = now()
WHERE organization_id = $1 AND id = $2 AND provider = 'gmail' AND auth_method IN ('oauth', 'delegated') AND NOT ` + managedExpr
return r.convertTx(ctx, query, []any{orgID, accountID, mailHost}, []txStep{
{`DELETE FROM email_accounts_oauth WHERE email_account_id = $1`, []any{accountID}},
{`INSERT INTO email_accounts_smtp_imap (email_account_id, smtp_host, smtp_port, smtp_user, smtp_password, smtp_security,
imap_host, imap_port, imap_user, imap_password, imap_security,
smtp_tls_unverified, smtp_tls_pin, imap_tls_unverified, imap_tls_pin)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
ON CONFLICT (email_account_id) DO UPDATE SET smtp_host = EXCLUDED.smtp_host, smtp_port = EXCLUDED.smtp_port,
smtp_user = EXCLUDED.smtp_user, smtp_password = EXCLUDED.smtp_password, smtp_security = EXCLUDED.smtp_security,
imap_host = EXCLUDED.imap_host, imap_port = EXCLUDED.imap_port, imap_user = EXCLUDED.imap_user,
imap_password = EXCLUDED.imap_password, imap_security = EXCLUDED.imap_security,
smtp_tls_unverified = EXCLUDED.smtp_tls_unverified, smtp_tls_pin = EXCLUDED.smtp_tls_pin,
imap_tls_unverified = EXCLUDED.imap_tls_unverified, imap_tls_pin = EXCLUDED.imap_tls_pin`,
[]any{accountID, sealed[0], creds.SMTP.Port, sealed[1], sealed[2], models.ResolveSMTPSecurity(creds.SMTP.Security, creds.SMTP.Port),
sealed[3], creds.IMAP.Port, sealed[4], sealed[5], models.ResolveIMAPSecurity(creds.IMAP.Security, creds.IMAP.Port),
creds.SMTP.TLSUnverified, creds.SMTP.StoredTLSPin(), creds.IMAP.TLSUnverified, creds.IMAP.StoredTLSPin()}},
// The Gmail cursor means nothing to IMAP, and its history is already imported.
{`INSERT INTO email_sync_state (email_id, user_id, backfill_status, backfill_completed_at)
SELECT id, user_id, 'complete', now() FROM email_accounts WHERE id = $1
ON CONFLICT (email_id) DO UPDATE SET backfill_status = 'complete', backfill_cursor = '{}'::jsonb,
backfill_completed_at = COALESCE(email_sync_state.backfill_completed_at, now()), updated_at = now()`, []any{accountID}},
})
}
type txStep struct {
q string
args []any
}
// ConvertToGoogleOAuth moves a Google mailbox reached through a grant or an app
// password onto its own Google sign-in in place, so history, campaigns and
// warmup stay. An IMAP mailbox's history is already imported, so its walk is marked done.
func (r *emailRepository) ConvertToGoogleOAuth(ctx context.Context, orgID, accountID uuid.UUID, accessToken, refreshToken string, expiresAt time.Time, mailHost string, scopes []string) (bool, *errx.Error) {
if strings.TrimSpace(accessToken) == "" || strings.TrimSpace(refreshToken) == "" {
return false, errx.ErrInvalid
}
sealed, err := r.sealCredentials(ctx, &orgID, accessToken, refreshToken)
if err != nil {
db.CaptureError(err, "", nil, "encrypt-oauth-tokens")
return false, errx.InternalError()
}
var wasIMAP bool
if err := r.DB.QueryRow(ctx, `SELECT provider = 'smtp_imap' FROM email_accounts WHERE organization_id = $1 AND id = $2`, orgID, accountID).Scan(&wasIMAP); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
db.CaptureError(err, "", nil, "queryrow")
return false, errx.InternalError()
}
query := `UPDATE email_accounts ea SET provider = 'gmail', auth_method = 'oauth', domain_grant_id = NULL, delegated_subject = '',
mail_host = CASE WHEN $3 = '' THEN mail_host ELSE $3 END,
last_id = CASE WHEN ea.provider = 'smtp_imap' THEN NULL ELSE last_id END,
transport_generation = gen_random_uuid(), updated_at = now()
WHERE organization_id = $1 AND id = $2 AND NOT ` + managedExpr + `
AND ((provider = 'gmail' AND auth_method = 'delegated') OR (provider = 'smtp_imap' AND $4))`
steps := []txStep{
{`DELETE FROM email_accounts_smtp_imap WHERE email_account_id = $1`, []any{accountID}},
{`INSERT INTO email_accounts_oauth (email_account_id, access_token, refresh_token, expires_at, granted_scopes) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (email_account_id) DO UPDATE SET access_token = EXCLUDED.access_token, refresh_token = EXCLUDED.refresh_token,
expires_at = EXCLUDED.expires_at, granted_scopes = EXCLUDED.granted_scopes, updated_at = now()`, []any{accountID, sealed[0], sealed[1], expiresAt, scopes}},
}
if wasIMAP {
steps = append(steps,
txStep{`DELETE FROM email_history_ids WHERE email_id = $1`, []any{accountID}},
txStep{`INSERT INTO email_sync_state (email_id, user_id, backfill_status, backfill_completed_at)
SELECT id, user_id, 'complete', now() FROM email_accounts WHERE id = $1
ON CONFLICT (email_id) DO UPDATE SET backfill_status = 'complete', backfill_cursor = '{}'::jsonb,
backfill_completed_at = COALESCE(email_sync_state.backfill_completed_at, now()), updated_at = now()`, []any{accountID}})
}
return r.convertTx(ctx, query, []any{orgID, accountID, mailHost, wasIMAP}, steps)
}
// convertTx runs a guarded UPDATE and, only when it matched a row, the steps after it, in one transaction.
func (r *emailRepository) convertTx(ctx context.Context, guard string, args []any, steps []txStep) (bool, *errx.Error) {
tx, err := r.DB.Begin(ctx)
if err != nil {
return false, errx.InternalError()
}
defer func() { _ = tx.Rollback(ctx) }()
tag, err := tx.Exec(ctx, guard, args...)
if err != nil {
db.CaptureError(err, guard, nil, "exec")
return false, errx.InternalError()
}
if tag.RowsAffected() == 0 {
return false, nil
}
for _, st := range steps {
if _, err := tx.Exec(ctx, st.q, st.args...); err != nil {
db.CaptureError(err, st.q, nil, "exec")
return false, errx.InternalError()
}
}
if err := tx.Commit(ctx); err != nil {
return false, errx.InternalError()
}
return true, nil
}
// ListSigninRetiring is the workspace's mailboxes on per-mailbox Google sign-in
// whose token is not known to carry full mail access, with the inbox vendor
// that can reconnect each one, when it has one.
func (r *emailRepository) ListSigninRetiring(ctx context.Context, orgID uuid.UUID) ([]models.MigrationMailbox, *errx.Error) {
query := `SELECT ea.id, ea.email, ea.name, ea.status, c.id, COALESCE(c.vendor, '')
FROM email_accounts ea
LEFT JOIN email_accounts_oauth o ON o.email_account_id = ea.id
LEFT JOIN mailbox_vendor_connections c ON c.id = ea.vendor_connection_id AND c.organization_id = ea.organization_id
AND c.status = 'active' AND ea.vendor_mailbox_id <> '' AND c.vendor = ANY($3)
WHERE ea.organization_id = $1 AND ea.provider = 'gmail' AND ea.auth_method = 'oauth' AND NOT ` + managedExpr + `
AND NOT COALESCE($2 = ANY(o.granted_scopes), false)
ORDER BY lower(ea.email)`
rows, err := r.DB.Query(ctx, query, orgID, models.GoogleFullMailScope, mailvendor.ConsentVendors())
if err != nil {
db.CaptureError(err, query, nil, "query")
return nil, errx.InternalError()
}
defer rows.Close()
out := []models.MigrationMailbox{}
for rows.Next() {
var m models.MigrationMailbox
if err := rows.Scan(&m.ID, &m.Email, &m.Name, &m.Status, &m.VendorConnectionID, &m.Vendor); err != nil {
return nil, errx.InternalError()
}
out = append(out, m)
}
if rows.Err() != nil {
return nil, errx.InternalError()
}
return out, nil
}
func (r *emailRepository) RelinkDelegated(ctx context.Context, orgID, accountID, grantID uuid.UUID, subject string) *errx.Error {
query := `UPDATE email_accounts SET domain_grant_id = $3, delegated_subject = $4, updated_at = now()
WHERE organization_id = $1 AND id = $2 AND auth_method = 'delegated'`
if _, err := r.DB.Exec(ctx, query, orgID, accountID, grantID, subject); err != nil {
db.CaptureError(err, query, nil, "exec")
return errx.InternalError()
}
return nil
}
func (r *emailRepository) GetDelegation(ctx context.Context, accountID uuid.UUID) (*models.DelegatedMailbox, *errx.Error) {
query := `
SELECT id, organization_id, provider, email, domain_grant_id, delegated_subject, status
FROM email_accounts
WHERE id = $1 AND auth_method = 'delegated' AND domain_grant_id IS NOT NULL AND organization_id IS NOT NULL`
var d models.DelegatedMailbox
var provider string
err := r.transportQueryRow(ctx, query, accountID).Scan(&d.AccountID, &d.OrganizationID, &provider, &d.Email, &d.GrantID, &d.Subject, &d.Status)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
db.CaptureError(err, query, nil, "queryrow")
return nil, errx.InternalError()
}
d.Provider = models.InboxProvider(provider)
return &d, nil
}
func (r *emailRepository) DomainsOverview(ctx context.Context, orgID uuid.UUID) ([]models.SendingDomain, *errx.Error) {
query := `
SELECT lower(split_part(ea.email, '@', 2)) AS domain,
count(*),
COALESCE(array_agg(DISTINCT ea.mail_host) FILTER (WHERE ea.mail_host <> ''), '{}'),
CASE WHEN bool_or(ea.auth_state = 'failing') THEN 'failing'
WHEN bool_or(ea.auth_state = 'passing') THEN 'passing' ELSE 'unknown' END,
bool_or(ea.auth_spf), bool_or(ea.auth_dkim), bool_or(ea.auth_dmarc),
COALESCE(array_agg(DISTINCT vc.vendor) FILTER (WHERE vc.vendor IS NOT NULL), '{}'),
COALESCE(array_agg(DISTINCT vc.id) FILTER (WHERE vc.id IS NOT NULL), '{}')
FROM email_accounts ea
LEFT JOIN mailbox_vendor_connections vc ON vc.id = ea.vendor_connection_id AND vc.organization_id = ea.organization_id
WHERE ea.organization_id = $1 AND position('@' in ea.email) > 0
GROUP BY 1
ORDER BY count(*) DESC, 1`
rows, err := r.DB.Query(ctx, query, orgID)
if err != nil {
db.CaptureError(err, query, nil, "query")
return nil, errx.InternalError()
}
out := make([]models.SendingDomain, 0)
index := map[string]int{}
for rows.Next() {
var d models.SendingDomain
if err := rows.Scan(&d.Domain, &d.Mailboxes, &d.MailHosts, &d.AuthState, &d.AuthSPF, &d.AuthDKIM, &d.AuthDMARC, &d.Vendors, &d.VendorConnectionIDs); err != nil {
rows.Close()
db.CaptureError(err, query, nil, "scan")
return nil, errx.InternalError()
}
d.TrackingDomains = []models.TrackingDomainUse{}
index[d.Domain] = len(out)
out = append(out, d)
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, errx.InternalError()
}
query = `
SELECT lower(split_part(email, '@', 2)), tracking_domain, bool_and(tracking_domain_verified), count(*)
FROM email_accounts
WHERE organization_id = $1 AND tracking_domain <> '' AND position('@' in email) > 0
GROUP BY 1, 2
ORDER BY 1, count(*) DESC`
rows, err = r.DB.Query(ctx, query, orgID)
if err != nil {
db.CaptureError(err, query, nil, "query")
return nil, errx.InternalError()
}
defer rows.Close()
for rows.Next() {
var domain string
var t models.TrackingDomainUse
if err := rows.Scan(&domain, &t.Host, &t.Verified, &t.Mailboxes); err != nil {
db.CaptureError(err, query, nil, "scan")
return nil, errx.InternalError()
}
if i, ok := index[domain]; ok {
out[i].TrackingDomains = append(out[i].TrackingDomains, t)
}
}
if err := rows.Err(); err != nil {
return nil, errx.InternalError()
}
return out, nil
}
func (r *emailRepository) CountDomainMailboxes(ctx context.Context, orgID uuid.UUID, domain string) (int, *errx.Error) {
query := `SELECT count(*) FROM email_accounts WHERE organization_id = $1 AND lower(split_part(email, '@', 2)) = lower($2)`
var n int
if err := r.DB.QueryRow(ctx, query, orgID, domain).Scan(&n); err != nil {
db.CaptureError(err, query, nil, "queryrow")
return 0, errx.InternalError()
}
return n, nil
}
func (r *emailRepository) OwnedDomains(ctx context.Context, orgID uuid.UUID) ([]string, *errx.Error) {
query := `
SELECT lower(split_part(email, '@', 2)) FROM email_accounts
WHERE organization_id = $1 AND position('@' in email) > 0
UNION
SELECT lower(tracking_domain) FROM email_accounts
WHERE organization_id = $1 AND tracking_domain <> '' AND tracking_domain_verified`
rows, err := r.DB.Query(ctx, query, orgID)
if err != nil {
db.CaptureError(err, query, nil, "query")
return nil, errx.InternalError()
}
defer rows.Close()
out := make([]string, 0)
for rows.Next() {
var d string
if err := rows.Scan(&d); err != nil {
db.CaptureError(err, query, nil, "scan")
return nil, errx.InternalError()
}
out = append(out, d)
}
if err := rows.Err(); err != nil {
return nil, errx.InternalError()
}
return out, nil
}
func (r *emailRepository) SetDomainTracking(ctx context.Context, orgID uuid.UUID, domain, host string, verified bool, verifiedAt *time.Time) (int, *errx.Error) {
if held, xerr := trackingDomainHeldElsewhere(ctx, r.DB, orgID, host); xerr != nil {
return 0, xerr
} else if held {
return 0, errx.ErrTrackingDomainTaken
}
query := `
UPDATE email_accounts
SET tracking_domain = $3, tracking_domain_verified = $4, tracking_domain_verified_at = $5, updated_at = now()
WHERE organization_id = $1 AND lower(split_part(email, '@', 2)) = lower($2)`
tag, err := r.DB.Exec(ctx, query, orgID, domain, host, verified, verifiedAt)
if isTrackingDomainTaken(err) {
return 0, errx.ErrTrackingDomainTaken
}
if err != nil {
db.CaptureError(err, query, nil, "exec")
return 0, errx.InternalError()
}
return int(tag.RowsAffected()), nil
}
func (r *emailRepository) SetVendorLink(ctx context.Context, accountID, connectionID uuid.UUID, vendorMailboxID string) *errx.Error {
query := `UPDATE email_accounts SET vendor_connection_id = $2, vendor_mailbox_id = $3 WHERE id = $1`
if _, err := r.DB.Exec(ctx, query, accountID, connectionID, vendorMailboxID); err != nil {
db.CaptureError(err, query, nil, "exec")
return errx.InternalError()
}
return nil
}
func (r *emailRepository) SetMailHost(ctx context.Context, id uuid.UUID, mailHost, authMethod string) *errx.Error {
query := `UPDATE email_accounts SET mail_host = $2, auth_method = CASE WHEN $3 = '' THEN auth_method ELSE $3 END WHERE id = $1`
if _, err := r.DB.Exec(ctx, query, id, mailHost, authMethod); err != nil {
db.CaptureError(err, query, nil, "exec")
return errx.InternalError()
}
return nil
}
func (r *emailRepository) ListUnclassifiedDomains(ctx context.Context, limit int) ([]string, *errx.Error) {
query := `
SELECT DISTINCT lower(split_part(email, '@', 2))
FROM email_accounts
WHERE mail_host = '' AND position('@' in email) > 0
LIMIT $1`
rows, err := r.DB.Query(ctx, query, limit)
if err != nil {
db.CaptureError(err, query, nil, "query")
return nil, errx.InternalError()
}
defer rows.Close()
var out []string
for rows.Next() {
var d string
if err := rows.Scan(&d); err != nil {
db.CaptureError(err, query, nil, "scan")
return nil, errx.InternalError()
}
out = append(out, d)
}
if err := rows.Err(); err != nil {
return nil, errx.InternalError()
}
return out, nil
}
func (r *emailRepository) SetDomainMailHost(ctx context.Context, domain, mailHost, passwordAuthMethod string) *errx.Error {
query := `
UPDATE email_accounts
SET mail_host = $2,
auth_method = CASE WHEN auth_method = '' AND provider = 'smtp_imap' THEN $3 ELSE auth_method END
WHERE mail_host = '' AND lower(split_part(email, '@', 2)) = $1`
if _, err := r.DB.Exec(ctx, query, strings.ToLower(domain), mailHost, passwordAuthMethod); err != nil {
db.CaptureError(err, query, nil, "exec")
return errx.InternalError()
}
return nil
}
func (r *emailRepository) ExistsForUser(ctx context.Context, userID, email string) (bool, *errx.Error) {
var exists bool
query := `SELECT EXISTS(SELECT 1 FROM email_accounts WHERE user_id = $1 AND email = $2)`
if err := r.DB.QueryRow(ctx, query, userID, email).Scan(&exists); err != nil {
db.CaptureError(err, query, []any{userID, email}, "queryrow")
return false, errx.InternalError()
}
return exists, nil
}
func (r *emailRepository) ListWarmupScheduleCandidates(ctx context.Context, limit int) ([]uuid.UUID, error) {
query := `
SELECT ea.id
FROM email_accounts ea
WHERE ea.status = 'active'
AND ea.worker_id IS NOT NULL
AND (ea.test_mode IS NULL OR ea.test_mode='legacy' OR ea.test_mode='diagnostic' AND ea.test_send_enabled)
AND (
(ea.warmup IS NOT NULL AND ea.warmup_paused_at IS NULL)
OR EXISTS (
SELECT 1
FROM email_tags et
JOIN campaign_email_tags cet ON cet.tag_id = et.tag_id
JOIN campaigns c ON c.id = cet.campaign_id
WHERE et.email_id = ea.id AND c.status = 'active'
)
)
AND NOT EXISTS (
SELECT 1 FROM tasks t
WHERE t.email_account_id = ea.id
AND t.task_type = 'warmup'
AND t.status = 'pending'
)
LIMIT $1`
rows, err := r.DB.Query(ctx, query, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}
// MailboxAssignment is an active mailbox and the worker it is assigned to, nil when none.
type MailboxAssignment struct {
ID uuid.UUID
WorkerID *uuid.UUID
}
func (r *emailRepository) ListActiveWorkerAccounts(ctx context.Context) ([]MailboxAssignment, error) {
query := `SELECT id, worker_id FROM email_accounts WHERE status = 'active' AND NOT ` + instanceExecutedSQL("email_accounts.id")
rows, err := r.DB.Query(ctx, query)
if err != nil {
return nil, err
}
defer rows.Close()
var out []MailboxAssignment
for rows.Next() {
var a MailboxAssignment
if err := rows.Scan(&a.ID, &a.WorkerID); err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}
func (r *emailRepository) ListActiveAccountsByWorker(ctx context.Context, workerID uuid.UUID) ([]uuid.UUID, error) {
const query = `SELECT id FROM email_accounts WHERE status = 'active' AND worker_id = $1`
rows, err := r.DB.Query(ctx, query, workerID)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (r *emailRepository) CountWarmingForOrganization(ctx context.Context, orgID uuid.UUID) (int, *errx.Error) {
var count int
query := `SELECT COUNT(*) FROM email_accounts
WHERE organization_id = $1 AND status = 'active' AND warmup IS NOT NULL AND warmup_paused_at IS NULL`
if err := r.DB.QueryRow(ctx, query, orgID).Scan(&count); err != nil {
db.CaptureError(err, query, []any{orgID}, "queryrow")
return 0, errx.InternalError()
}
return count, nil
}
func (r *emailRepository) CountForOrganization(ctx context.Context, orgID uuid.UUID) (int, *errx.Error) {
var count int
query := `SELECT COUNT(*) FROM email_accounts WHERE organization_id = $1`
if err := r.DB.QueryRow(ctx, query, orgID).Scan(&count); err != nil {
db.CaptureError(err, query, []any{orgID}, "queryrow")
return 0, errx.InternalError()
}
return count, nil
}
// reserveMailboxSlotTx is the final allowance check, run inside the insert
// transaction under a per-organization lock so two connects that both saw one
// slot free cannot both take it. The service's earlier read is for feedback;
// this is what enforces.
func reserveMailboxSlotTx(ctx context.Context, tx pgx.Tx, orgID *uuid.UUID, a *models.MailboxAllowance) *errx.Error {
if a == nil || a.Allowance == nil || orgID == nil {
return nil
}
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext('email_accounts'), hashtext($1::text))`, orgID.String()); err != nil {
db.CaptureError(err, "", nil, "exec")
return errx.InternalError()
}
var count int
if err := tx.QueryRow(ctx, `SELECT COUNT(*) FROM email_accounts WHERE organization_id = $1`, *orgID).Scan(&count); err != nil {
db.CaptureError(err, "", nil, "queryrow")
return errx.InternalError()
}
if count >= *a.Allowance {
return errx.MailboxAllowanceReached(count, *a.Allowance, a.Paid)
}
return nil
}
// ensureMailboxAbsentTx refuses an address the workspace already has, under
// the same per-organization lock as the slot, so two concurrent connects of
// one address cannot both insert.
func ensureMailboxAbsentTx(ctx context.Context, tx pgx.Tx, orgID *uuid.UUID, email string) *errx.Error {
if orgID == nil {
return nil
}
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext('email_accounts'), hashtext($1::text))`, orgID.String()); err != nil {
db.CaptureError(err, "", nil, "exec")
return errx.InternalError()
}
var exists bool
query := `SELECT EXISTS(SELECT 1 FROM email_accounts WHERE organization_id = $1 AND lower(email) = lower($2))`
if err := tx.QueryRow(ctx, query, *orgID, strings.TrimSpace(email)).Scan(&exists); err != nil {
db.CaptureError(err, query, nil, "queryrow")
return errx.InternalError()
}
if exists {
return errx.ErrEmailOnboardAlreadyExists
}
return nil
}
// setNewMailboxVolumeTx starts a free Gmail or Outlook.com mailbox at the consumer volume; any other keeps the column defaults.
func setNewMailboxVolumeTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, mailHost, provider, address string) *errx.Error {
if !models.ConsumerMailboxHost(mailHost, provider, address) {
return nil
}
limit, gap, warmupMax := models.NewMailboxVolume(mailHost, provider, address)
query := `UPDATE email_accounts SET campaign_limit = $2, min_wait_time = $3, warmup_max = $4 WHERE id = $1`
if _, err := tx.Exec(ctx, query, id, limit, gap, warmupMax); err != nil {
db.CaptureError(err, query, nil, "exec")
return errx.InternalError()
}
return nil
}
func (r *emailRepository) NewOauthAccount(ctx context.Context, userID string, data models.NewOauthAccount) (*models.Email, *errx.Error) {
if data.Provider == models.InboxProviderSMTPIMAP {
errs.CaptureException(errors.New("invalid inbox provider"))
return nil, errx.InternalError()
}
// Seal before opening the transaction so a misconfigured encrypter aborts
// the connect instead of writing provider tokens in the clear.
sealedTokens, encErr := r.sealCredentials(ctx, data.OrganizationID, data.AccessToken, data.RefreshToken)
if encErr != nil {
db.CaptureError(encErr, "", nil, "encrypt-oauth-tokens")
return nil, errx.InternalError()
}
encAccessToken, encRefreshToken := sealedTokens[0], sealedTokens[1]
tx, err := r.DB.Begin(ctx)
if err != nil {
db.CaptureError(err, "", nil, "begin")
return nil, errx.InternalError()
}
defer tx.Rollback(ctx)
if xerr := reserveMailboxSlotTx(ctx, tx, data.OrganizationID, data.Allowance); xerr != nil {
return nil, xerr
}
if xerr := ensureMailboxAbsentTx(ctx, tx, data.OrganizationID, data.Email); xerr != nil {
return nil, xerr
}
sigplain := utils.GetSignaturePlain(data.Name)
sightml := utils.GetSignatureHTML(data.Name)
t := time.Now()
id := uuid.New()
if data.ID != uuid.Nil {
id = data.ID
}
// warmup_tag is the content segment (defaults to '' = generic). It used to
// be seeded with a random RID, which silently broke segment-aware content
// selection because a random tag never matches a real segment.
query := withNewMailboxBehavior(`
INSERT INTO email_accounts (id, user_id, organization_id, email, name, provider, signature_plain, signature_html, tracking_domain, last_synced_at, created_at, updated_at, warmup_tag, mail_host, auth_method)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10, $10, $11, $12, $13)
`, !data.DisableSendingBehavior)
params := []any{
id,
userID,
data.OrganizationID,
data.Email,
data.Name,
data.Provider,
sigplain,
sightml,
"",
t,
"",
data.MailHost,
models.MailAuthOAuth,
}
_, err = tx.Exec(
ctx,
query,
params...,
)
if err != nil {
db.CaptureError(err, query, nil, "queryrow")
return nil, errx.InternalError()
}
if xerr := setNewMailboxVolumeTx(ctx, tx, id, data.MailHost, string(data.Provider), data.Email); xerr != nil {
return nil, xerr
}
query = `
INSERT INTO email_accounts_oauth (email_account_id, access_token, refresh_token, expires_at, granted_scopes, oauth_app_id)
VALUES ($1, $2, $3, $4, $5, $6)
`
params = []any{
id,
encAccessToken,
encRefreshToken,
data.ExpiresAt,
data.GrantedScopes,
data.OAuthAppID,
}
_, err = tx.Exec(
ctx,
query,
params...,
)
if err != nil {
// params holds the sealed tokens; keep them out of the error report.
db.CaptureError(err, query, nil, "exec")
return nil, errx.InternalError()
}
if err := tx.Commit(ctx); err != nil {
db.CaptureError(err, "", nil, "commit")
return nil, errx.InternalError()
}
limit, gap, warmupMax := models.NewMailboxVolume(data.MailHost, string(data.Provider), data.Email)
return &models.Email{
ID: id,
UserID: userID,
OrganizationID: data.OrganizationID,
Email: data.Email,
Name: data.Name,
SignaturePlain: sigplain,
SignatureHTML: sightml,
SignatureSync: true,
SignatureCode: false,
Provider: string(data.Provider),
Status: "active",
MailHost: data.MailHost,
AuthMethod: models.MailAuthOAuth,
LastSyncedAt: t,
CampaignLimit: limit,
MinWaitTime: gap,
WarmupBase: config.WarmupBaseDefault,
WarmupMax: warmupMax,
WarmupIncrease: config.WarmupIncreaseDefault,
WarmupStartTime: "08:00",
WarmupEndTime: "20:00",
WarmupDays: 0,
CreatedAt: t,
UpdatedAt: t,
}, nil
}
func (r *emailRepository) NewManagedAccount(ctx context.Context, userID string, data models.NewOauthAccount) (*models.Email, *errx.Error) {
if data.Provider != models.InboxProviderGoogle && data.Provider != models.InboxProviderOutlook {
errs.CaptureException(errors.New("managed account: unsupported provider"))
return nil, errx.InternalError()
}
sigplain := utils.GetSignaturePlain(data.Name)
sightml := utils.GetSignatureHTML(data.Name)
t := time.Now()
id := uuid.New()
if data.ID != uuid.Nil {
id = data.ID
}
tx, err := r.DB.Begin(ctx)
if err != nil {
return nil, errx.InternalError()
}
defer tx.Rollback(ctx)
if xerr := ensureMailboxAbsentTx(ctx, tx, data.OrganizationID, data.Email); xerr != nil {
return nil, xerr
}
query := withNewMailboxBehavior(`
INSERT INTO email_accounts (id, user_id, organization_id, email, name, provider, signature_plain, signature_html, tracking_domain, last_synced_at, created_at, updated_at, warmup_tag, mail_host, auth_method)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10, $10, $11, $12, $13)
`, true)
if _, err := tx.Exec(ctx, query, id, userID, data.OrganizationID, data.Email, data.Name, data.Provider, sigplain, sightml, "", t, "", data.MailHost, models.MailAuthOAuth); err != nil {
db.CaptureError(err, query, nil, "exec")
return nil, errx.InternalError()
}
if xerr := setNewMailboxVolumeTx(ctx, tx, id, data.MailHost, string(data.Provider), data.Email); xerr != nil {
return nil, xerr
}
if err := tx.Commit(ctx); err != nil {
return nil, errx.InternalError()
}
return r.GetByID(ctx, id)
}
func (r *emailRepository) NewSMTPIMAPAccount(ctx context.Context, userID string, data models.NewSMTPIMAPAccount) (*models.Email, *errx.Error) {
// Seal before the transaction so a key lookup never holds the organization's mailbox lock.
sealed, sealErr := r.sealCredentials(ctx, data.OrganizationID, data.SMTP.Host, data.SMTP.Username, data.SMTP.Password, data.IMAP.Host, data.IMAP.Username, data.IMAP.Password)
if sealErr != nil {
errs.CaptureException(sealErr)
return nil, errx.InternalError()
}
smtphost, smtpuser, smtppass, imaphost, imapuser, imappass := sealed[0], sealed[1], sealed[2], sealed[3], sealed[4], sealed[5]
tx, err := r.DB.Begin(ctx)
if err != nil {
db.CaptureError(err, "", nil, "begin")
return nil, errx.InternalError()
}
defer tx.Rollback(ctx)
if xerr := reserveMailboxSlotTx(ctx, tx, data.OrganizationID, data.Allowance); xerr != nil {
return nil, xerr
}
if xerr := ensureMailboxAbsentTx(ctx, tx, data.OrganizationID, data.Email); xerr != nil {
return nil, xerr
}
sigplain := utils.GetSignaturePlain(data.Name)
sightml := utils.GetSignatureHTML(data.Name)
id := uuid.New()
t := time.Now()
query := withNewMailboxBehavior(`
INSERT INTO email_accounts (id, user_id, organization_id, email, name, provider, signature_plain, signature_html, tracking_domain, last_synced_at, updated_at, created_at, warmup_tag, mail_host, auth_method)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10, $10, $11, $12, $13)
`, !data.DisableSendingBehavior)
params := []any{
id,
userID,
data.OrganizationID,
data.Email,
data.Name,
"smtp_imap",
sigplain,
sightml,
"",
t,
"",
data.MailHost,
data.AuthMethod,
}
_, err = tx.Exec(
ctx,
query,
params...,
)
if err != nil {
db.CaptureError(err, query, nil, "exec")
return nil, errx.InternalError()
}
if xerr := setNewMailboxVolumeTx(ctx, tx, id, data.MailHost, string(models.InboxProviderSMTPIMAP), data.Email); xerr != nil {
return nil, xerr
}
query = `
INSERT INTO email_accounts_smtp_imap (
email_account_id,
smtp_host, smtp_port, smtp_user, smtp_password, smtp_security,
imap_host, imap_port, imap_user, imap_password, imap_security,
smtp_tls_unverified, smtp_tls_pin, imap_tls_unverified, imap_tls_pin
) VALUES (
$1, $2, $3, $4, $5, $6,
$7, $8, $9, $10, $11,
$12, $13, $14, $15)
`
params = []any{
id, smtphost, data.SMTP.Port, smtpuser, smtppass,
models.ResolveSMTPSecurity(data.SMTP.Security, data.SMTP.Port),
imaphost, data.IMAP.Port, imapuser, imappass,
models.ResolveIMAPSecurity(data.IMAP.Security, data.IMAP.Port),
data.SMTP.TLSUnverified, data.SMTP.StoredTLSPin(), data.IMAP.TLSUnverified, data.IMAP.StoredTLSPin(),
}
_, err = tx.Exec(
ctx,
query,
params...,
)
if err != nil {
db.CaptureError(err, query, nil, "exec")
return nil, errx.InternalError()
}
if err := tx.Commit(ctx); err != nil {
db.CaptureError(err, "", nil, "commit")
return nil, errx.InternalError()
}
limit, gap, warmupMax := models.NewMailboxVolume(data.MailHost, string(models.InboxProviderSMTPIMAP), data.Email)
return &models.Email{
ID: id,
UserID: userID,
OrganizationID: data.OrganizationID,
Email: data.Email,
Name: data.Name,
SignaturePlain: sigplain,
SignatureHTML: sightml,
SignatureSync: true,
SignatureCode: false,
Provider: "smtp_imap",
Status: "active",
MailHost: data.MailHost,
AuthMethod: data.AuthMethod,
LastSyncedAt: t,
CampaignLimit: limit,
MinWaitTime: gap,
WarmupBase: config.WarmupBaseDefault,
WarmupMax: warmupMax,
WarmupIncrease: config.WarmupIncreaseDefault,
WarmupStartTime: "08:00",
WarmupEndTime: "20:00",
WarmupDays: 0,
CreatedAt: t,
UpdatedAt: t,
}, nil
}
func (r *emailRepository) Search(ctx context.Context, orgID, search string, cursor, tag *string, limit int32, allowedAccountIDs []uuid.UUID) (*models.EmailsResult, *errx.Error) {
tx, err := r.DB.Begin(ctx)
if err != nil {
db.CaptureError(err, "", nil, "begin")
return nil, errx.InternalError()
}
// Read-only transaction — Commit is fine but Rollback at end is the
// safety net. Pool only has 4 connections; a single leaked tx here
// (under load) is enough to deadlock the whole backend, including
// /auth/refresh which blocks waiting for a connection.
defer tx.Rollback(ctx)
query := `
SELECT
ea.id, ea.email, ea.name, ea.signature_plain, ea.signature_html, ea.signature_sync, ea.signature_code, ea.send_as_email,
ea.provider, ea.mail_host, ea.auth_method, ea.domain_grant_id, ea.vendor_connection_id, COALESCE((SELECT vc.vendor FROM mailbox_vendor_connections vc WHERE vc.id = ea.vendor_connection_id), ''), ea.avatar_url, ea.status, COALESCE(ea.last_synced_at, ea.created_at) AS last_synced_at, ea.last_id, ea.campaign_limit,
ea.min_wait_time, ea.reply_to, ea.tracking_domain, ea.tracking_domain_verified, ea.tracking_domain_verified_at, ea.track_direct_mail,
ea.auth_state, ea.auth_spf, ea.auth_dkim, ea.auth_dmarc, ea.auth_dmarc_policy, ea.auth_reason, ea.auth_checked_at, ea.auth_failing_since,
ea.warmup, ea.warmup_paused_at, ea.warmup_base,
ea.warmup_max, ea.warmup_increase, ea.warmup_reply_rate, ea.warmup_tag, COALESCE(ea.warmup_pool_type, 'free') AS warmup_pool_type, ea.warmup_start_time, ea.warmup_end_time, ea.warmup_days, ea.test_mode, ea.test_send_enabled, ea.test_receive_enabled, ea.shared_daily_limit, ea.rolling_recipient_limit, ea.warmup_placement, ea.warmup_folder, COALESCE(ea.warmup_retention_days, 0) AS warmup_retention_days, ea.timezone, COALESCE((SELECT o.timezone FROM organizations o WHERE o.id = ea.organization_id), '') AS org_timezone, ea.save_to_sent, ea.relay_folder_moves,
ea.created_at, ea.updated_at,
COALESCE(
array_agg(eat.tag_id) FILTER (WHERE eat.tag_id IS NOT NULL), '{}'
) AS tags
FROM email_accounts ea
LEFT JOIN email_tags eat ON eat.email_id = ea.id
WHERE ea.organization_id = $1
AND ($2::uuid IS NULL OR (ea.created_at, ea.id) < (
SELECT created_at, id
FROM email_accounts
WHERE id = $2
AND organization_id = $1
AND ($6::uuid[] IS NULL OR id = ANY($6::uuid[]))
))
AND (ea.name ILIKE $3 OR ea.email ILIKE $3)
AND ($4::uuid IS NULL OR EXISTS (
SELECT 1 FROM email_tags cf WHERE cf.email_id = ea.id AND cf.tag_id = $4
))
AND ($6::uuid[] IS NULL OR ea.id = ANY($6::uuid[]))
GROUP BY ea.id
ORDER BY ea.created_at DESC, ea.id DESC
LIMIT $5
`
var allowedAccountParam any
if allowedAccountIDs != nil {
allowedAccountParam = allowedAccountIDs
}
params := []any{
orgID,
cursor,
"%" + search + "%",
tag,
limit + 1,
allowedAccountParam,
}
rows, err := tx.Query(ctx, query, params...)
if err != nil {
db.CaptureError(err, query, params, "query")
return nil, errx.InternalError()
}
defer rows.Close()
inboxes := make([]models.Email, 0)
for rows.Next() {
var i models.Email
err := rows.Scan(
&i.ID, &i.Email, &i.Name, &i.SignaturePlain, &i.SignatureHTML, &i.SignatureSync, &i.SignatureCode, &i.SendAsEmail, &i.Provider, &i.MailHost, &i.AuthMethod, &i.DomainGrantID, &i.VendorConnectionID, &i.Vendor, &i.AvatarURL, &i.Status,
&i.LastSyncedAt, &i.LastID, &i.CampaignLimit, &i.MinWaitTime, &i.ReplyTo, &i.TrackingDomain, &i.TrackingDomainVerified, &i.TrackingDomainVerifiedAt, &i.TrackDirectMail,
&i.AuthState, &i.AuthSPF, &i.AuthDKIM, &i.AuthDMARC, &i.AuthDMARCPolicy, &i.AuthReason, &i.AuthCheckedAt, &i.AuthFailingSince,
&i.Warmup, &i.WarmupPausedAt, &i.WarmupBase, &i.WarmupMax, &i.WarmupIncrease, &i.WarmupReplyRate, &i.WarmupTag, &i.WarmupPoolType,
&i.WarmupStartTime, &i.WarmupEndTime, &i.WarmupDays, &i.TestMode, &i.TestSendEnabled, &i.TestReceiveEnabled, &i.SharedDailyLimit, &i.RollingRecipientLimit, &i.WarmupPlacement, &i.WarmupFolder, &i.WarmupRetentionDays, &i.Timezone, &i.OrgTimezone, &i.SaveToSent, &i.RelayFolderMoves,
&i.CreatedAt, &i.UpdatedAt, &i.Tags,
)
if err != nil {
db.CaptureError(err, "", nil, "scan")
return nil, errx.InternalError()
}
inboxes = append(inboxes, i)
}
if err := rows.Err(); err != nil {
db.CaptureError(err, query, params, "rows")
return nil, errx.InternalError()
}
var total *int64
var nextCursor *string
var hasMore bool
if len(inboxes) > int(limit) {
hasMore = true
// The last row returned: the next page starts strictly below it.
nextCursor = paging.EncodeUUID(inboxes[limit-1].ID)
inboxes = inboxes[:limit]
}
if cursor == nil {
query = `
SELECT COUNT(DISTINCT ea.id)
FROM email_accounts ea
LEFT JOIN email_tags et ON et.email_id = ea.id
WHERE ea.organization_id = $1
AND (ea.name ILIKE $2 OR ea.email ILIKE $2)
AND ($3::uuid IS NULL OR EXISTS (
SELECT 1 FROM email_tags cf WHERE cf.email_id = ea.id AND cf.tag_id = $3
))
AND ($4::uuid[] IS NULL OR ea.id = ANY($4::uuid[]))
`
params = []any{
orgID,
"%" + search + "%",
tag,
allowedAccountParam,
}
var tmp int64
err := tx.QueryRow(
ctx,
query,
params...,
).Scan(&tmp)
if err != nil {
db.CaptureError(err, query, params, "queryrow")
return nil, errx.InternalError()
}
total = &tmp
}
return &models.EmailsResult{
Data: inboxes,
Pagination: models.Pagination{
Total: total,
NextCursor: nextCursor,
HasMore: hasMore,
},
}, nil
}
func (r *emailRepository) Get(ctx context.Context, orgID, emailAccountID string) (*models.Email, *errx.Error) {
query := `
SELECT
ea.id, ea.organization_id, ea.email, ea.name, ea.signature_plain, ea.signature_html, ea.signature_sync, ea.signature_code, ea.send_as_email,
ea.provider, ea.mail_host, ea.auth_method, ea.domain_grant_id, ea.vendor_connection_id, COALESCE((SELECT vc.vendor FROM mailbox_vendor_connections vc WHERE vc.id = ea.vendor_connection_id), ''), ea.avatar_url, ea.status, COALESCE(ea.last_synced_at, ea.created_at) AS last_synced_at, ea.last_id, ea.campaign_limit,
ea.min_wait_time, ea.reply_to, ea.tracking_domain, ea.tracking_domain_verified, ea.tracking_domain_verified_at, ea.track_direct_mail,
ea.auth_state, ea.auth_spf, ea.auth_dkim, ea.auth_dmarc, ea.auth_dmarc_policy, ea.auth_reason, ea.auth_checked_at, ea.auth_failing_since,
ea.warmup, ea.warmup_paused_at, ea.warmup_base,
ea.warmup_max, ea.warmup_increase, ea.warmup_reply_rate, ea.warmup_tag, COALESCE(ea.warmup_pool_type, 'free') AS warmup_pool_type, ea.warmup_start_time, ea.warmup_end_time, ea.warmup_days, ea.test_mode, ea.test_send_enabled, ea.test_receive_enabled, ea.shared_daily_limit, ea.rolling_recipient_limit, ea.warmup_placement, ea.warmup_folder, COALESCE(ea.warmup_retention_days, 0) AS warmup_retention_days, ea.timezone, COALESCE((SELECT o.timezone FROM organizations o WHERE o.id = ea.organization_id), '') AS org_timezone, ea.save_to_sent, ea.relay_folder_moves,
ea.created_at, ea.updated_at,
COALESCE(array_agg(eat.tag_id) FILTER (WHERE eat.tag_id IS NOT NULL), '{}') AS tags
FROM email_accounts ea
LEFT JOIN email_tags eat ON eat.email_id = ea.id
WHERE ea.organization_id = $1 AND ea.id = $2
GROUP BY ea.id
`
params := []any{
orgID,
emailAccountID,
}
var i models.Email
err := r.DB.QueryRow(
ctx,
query,
params...,
).Scan(
&i.ID, &i.OrganizationID, &i.Email, &i.Name, &i.SignaturePlain, &i.SignatureHTML, &i.SignatureSync, &i.SignatureCode, &i.SendAsEmail, &i.Provider, &i.MailHost, &i.AuthMethod, &i.DomainGrantID, &i.VendorConnectionID, &i.Vendor, &i.AvatarURL, &i.Status,
&i.LastSyncedAt, &i.LastID, &i.CampaignLimit, &i.MinWaitTime, &i.ReplyTo, &i.TrackingDomain, &i.TrackingDomainVerified, &i.TrackingDomainVerifiedAt, &i.TrackDirectMail,
&i.AuthState, &i.AuthSPF, &i.AuthDKIM, &i.AuthDMARC, &i.AuthDMARCPolicy, &i.AuthReason, &i.AuthCheckedAt, &i.AuthFailingSince,
&i.Warmup, &i.WarmupPausedAt, &i.WarmupBase, &i.WarmupMax, &i.WarmupIncrease, &i.WarmupReplyRate, &i.WarmupTag, &i.WarmupPoolType,
&i.WarmupStartTime, &i.WarmupEndTime, &i.WarmupDays, &i.TestMode, &i.TestSendEnabled, &i.TestReceiveEnabled, &i.SharedDailyLimit, &i.RollingRecipientLimit, &i.WarmupPlacement, &i.WarmupFolder, &i.WarmupRetentionDays, &i.Timezone, &i.OrgTimezone, &i.SaveToSent, &i.RelayFolderMoves,
&i.CreatedAt, &i.UpdatedAt, &i.Tags,
)
if err != nil {
// A mailbox that does not exist, or belongs to another organization, is
// a 404 — not a server error. Both cases land here as no-rows because
// the query is scoped by organization_id, which is also what keeps the
// tenancy boundary from leaking a "wrong org" signal.
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
db.CaptureError(err, query, params, "queryrow")
return nil, errx.InternalError()
}
return &i, nil
}
// Update writes a mailbox's settings. Scoped by organization, like Get, Search
// and UpdateTrackingDomain: a mailbox is a workspace asset and the route admits
// any member holding manage_emails, so keying on the user who happened to
// connect it turned that permission into a 404 for everyone else.
func (r *emailRepository) Update(ctx context.Context, orgID, emailAccountID string, udata *models.UpdateEmail) (*models.Email, *errx.Error) {
setClauses := []string{}
args := []any{orgID, emailAccountID}
argPos := 3
statusSQL := "status"
if xerr := validate.MailboxUpdate(udata); xerr != nil {
return nil, xerr
}
if udata.Name != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "name", argPos))
args = append(args, *udata.Name)
argPos++
}
if udata.SignaturePlain != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "signature_plain", argPos))
args = append(args, *udata.SignaturePlain)
argPos++
}
if udata.SignatureHTML != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "signature_html", argPos))
args = append(args, *udata.SignatureHTML)
argPos++
}
if udata.SignatureSync != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "signature_sync", argPos))
args = append(args, *udata.SignatureSync)
argPos++
}
if udata.Timezone != nil {
tz := strings.TrimSpace(*udata.Timezone)
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "timezone", argPos))
args = append(args, tz)
argPos++
}
if udata.SaveToSent != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "save_to_sent", argPos))
args = append(args, *udata.SaveToSent)
argPos++
}
if udata.RelayFolderMoves != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "relay_folder_moves", argPos))
args = append(args, *udata.RelayFolderMoves)
argPos++
}
if udata.SignatureCode != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "signature_code", argPos))
args = append(args, *udata.SignatureCode)
argPos++
}
// The alias is checked against the provider's list before it gets here
// (emailService.Update), which is what produces a real error message. That
// read and this write are two statements, so the predicate is repeated in
// SQL against the row's own list: a refresh landing in between would
// otherwise have its clearing of a revoked alias written straight back,
// and every later send would go out as an address Gmail refuses. Failing
// the predicate keeps the stored value rather than erroring, because by
// then the caller's request was valid when it was made.
if udata.SendAsEmail != nil {
setClauses = append(setClauses, fmt.Sprintf(`send_as_email = CASE
WHEN $%[1]d = '' OR lower($%[1]d) = lower(email) THEN $%[1]d
WHEN EXISTS (
SELECT 1 FROM jsonb_array_elements(send_as) AS sa
WHERE (sa->>'verified')::boolean AND lower(sa->>'email') = lower($%[1]d)
) THEN $%[1]d
ELSE send_as_email
END`, argPos))
args = append(args, strings.TrimSpace(*udata.SendAsEmail))
argPos++
}
if udata.Status != nil {
status := *udata.Status
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "status", argPos))
statusSQL = fmt.Sprintf("$%d::email_status", argPos)
args = append(args, status)
argPos++
if status == "active" {
// Re-derive the verdict, which the sweep froze while inactive.
// auth_failing_since is deliberately NOT cleared: that would make
// deactivate-then-reactivate an indefinite way to restart the grace
// window on a domain that is still broken.
setClauses = append(setClauses, "auth_checked_at = NULL")
}
}
if udata.CampaignLimit != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "campaign_limit", argPos))
args = append(args, *udata.CampaignLimit)
argPos++
}
if udata.MinWaitTime != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "min_wait_time", argPos))
args = append(args, *udata.MinWaitTime)
argPos++
}
if udata.ReplyTo != nil {
*udata.ReplyTo = strings.TrimSpace(*udata.ReplyTo)
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "reply_to", argPos))
args = append(args, *udata.ReplyTo)
argPos++
}
if udata.Warmup != nil {
if udata.TestMode == nil {
mode := models.TestParticipationOff
if *udata.Warmup {
mode = models.TestParticipationDiagnostic
}
udata.TestMode = &mode
if udata.TestSendEnabled == nil {
udata.TestSendEnabled = udata.Warmup
}
if udata.TestReceiveEnabled == nil {
udata.TestReceiveEnabled = udata.Warmup
}
}
if *udata.Warmup {
setClauses = append(setClauses, `warmup = CASE WHEN warmup IS NULL THEN now() WHEN warmup_paused_at IS NOT NULL THEN warmup+(now()-warmup_paused_at) ELSE warmup END`, "warmup_paused_at = NULL")
} else {
setClauses = append(setClauses, `warmup_paused_at = CASE WHEN warmup IS NOT NULL THEN COALESCE(warmup_paused_at,now()) ELSE NULL END`)
}
}
if udata.WarmupBase != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_base", argPos))
args = append(args, *udata.WarmupBase)
argPos++
}
if udata.WarmupMax != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_max", argPos))
args = append(args, *udata.WarmupMax)
argPos++
}
if udata.WarmupIncrease != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_increase", argPos))
args = append(args, *udata.WarmupIncrease)
argPos++
}
if udata.WarmupReplyRate != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_reply_rate", argPos))
args = append(args, *udata.WarmupReplyRate)
argPos++
}
if udata.WarmupTag != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_tag", argPos))
args = append(args, strings.ToLower(strings.TrimSpace(*udata.WarmupTag)))
argPos++
}
if udata.WarmupStartTime != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_start_time", argPos))
args = append(args, *udata.WarmupStartTime)
argPos++
}
if udata.WarmupEndTime != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_end_time", argPos))
args = append(args, *udata.WarmupEndTime)
argPos++
}
if udata.WarmupDays != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_days", argPos))
args = append(args, *udata.WarmupDays)
argPos++
}
if udata.WarmupPlacement != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_placement", argPos))
args = append(args, *udata.WarmupPlacement)
argPos++
}
if udata.WarmupFolder != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", "warmup_folder", argPos))
args = append(args, strings.TrimSpace(*udata.WarmupFolder))
argPos++
}
if udata.WarmupRetentionDays != nil {
// Zero is "follow the instance", stored as NULL so a later change to
// the instance setting reaches every mailbox that never chose.
setClauses = append(setClauses, fmt.Sprintf("%s = NULLIF($%d, 0)", "warmup_retention_days", argPos))
args = append(args, *udata.WarmupRetentionDays)
argPos++
}
participationChanged := udata.Status != nil || udata.TestMode != nil || udata.TestSendEnabled != nil || udata.TestReceiveEnabled != nil
modeSQL, sendSQL, receiveSQL := "test_mode", "test_send_enabled", "test_receive_enabled"
if udata.TestMode == nil && (udata.TestSendEnabled != nil || udata.TestReceiveEnabled != nil) {
mode := models.TestParticipationDiagnostic
udata.TestMode = &mode
}
if udata.TestMode != nil {
setClauses = append(setClauses, fmt.Sprintf("test_mode = $%d", argPos))
modeSQL = fmt.Sprintf("$%d", argPos)
args = append(args, *udata.TestMode)
argPos++
}
for _, setting := range []struct {
column string
value *bool
}{
{"test_send_enabled", udata.TestSendEnabled}, {"test_receive_enabled", udata.TestReceiveEnabled},
} {
if setting.value != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", setting.column, argPos))
if setting.column == "test_send_enabled" {
sendSQL = fmt.Sprintf("$%d", argPos)
} else {
receiveSQL = fmt.Sprintf("$%d", argPos)
}
args = append(args, *setting.value)
argPos++
}
}
if participationChanged {
setClauses = append(setClauses, "warmup_stopped_at = CASE WHEN "+statusSQL+" IN ('inactive','revoked') OR "+modeSQL+"='off' OR "+modeSQL+"='diagnostic' AND NOT ("+sendSQL+") AND NOT ("+receiveSQL+") THEN COALESCE(warmup_stopped_at,clock_timestamp()) ELSE NULL END")
}
for _, setting := range []struct {
column string
value *int
}{
{"shared_daily_limit", udata.SharedDailyLimit}, {"rolling_recipient_limit", udata.RollingRecipientLimit},
} {
if setting.value != nil {
setClauses = append(setClauses, fmt.Sprintf("%s = NULLIF($%d, 0)", setting.column, argPos))
args = append(args, *setting.value)
argPos++
}
}
// Tags are not a column on the row, so a patch that only moves them still
// leaves setClauses empty. Refusing it made the mailbox drawer's tag
// picker unable to save on its own, which is how the dashboard sends it:
// only the fields that actually changed.
if argPos == 3 && udata.Tags == nil && udata.SendRecoveryResolution == nil {
return nil, errx.ErrNotEnough
}
setClauses = append(setClauses, "updated_at = now()")
tx, err := r.DB.Begin(ctx)
if err != nil {
db.CaptureError(err, "", nil, "begin")
return nil, errx.InternalError()
}
defer tx.Rollback(ctx)
if participationChanged {
mailbox, parseErr := uuid.Parse(emailAccountID)
if parseErr != nil {
return nil, errx.ErrUuid
}
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,270))`, mailbox.String()); err != nil {
return nil, errx.InternalError()
}
var currentMode *string
var currentStatus string
var currentSend, currentReceive, currentPaused bool
if err := tx.QueryRow(ctx, `SELECT test_mode,status,test_send_enabled,test_receive_enabled,warmup_paused_at IS NOT NULL FROM email_accounts WHERE organization_id=$1 AND id=$2`, orgID, mailbox).Scan(&currentMode, &currentStatus, &currentSend, &currentReceive, &currentPaused); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
return nil, errx.InternalError()
}
direction := ""
diagnostic := currentMode != nil && *currentMode == "diagnostic"
// Pausing warmup stops both directions whatever participation flags the same request sends.
pausing := currentPaused || udata.Warmup != nil && !*udata.Warmup
sendingOff := pausing || diagnostic && !currentSend || udata.TestSendEnabled != nil && !*udata.TestSendEnabled
receivingOff := pausing || diagnostic && !currentReceive || udata.TestReceiveEnabled != nil && !*udata.TestReceiveEnabled
if currentStatus != "active" || udata.Status != nil && *udata.Status != "active" || currentMode != nil && *currentMode == "off" || udata.TestMode != nil && *udata.TestMode == "off" || sendingOff && receivingOff {
direction = "both"
} else if sendingOff {
direction = "sender"
} else if receivingOff {
direction = "receiver"
}
if direction != "" {
if err := retireStoppedWarmupDispatches(ctx, tx, mailbox, direction); err != nil {
return nil, errx.InternalError()
}
}
}
if resolution := udata.SendRecoveryResolution; resolution != nil {
mailboxID, parseErr := uuid.Parse(emailAccountID)
if parseErr != nil || resolution.HeldTaskID == uuid.Nil {
return nil, errx.ErrInvalid
}
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,268))`, resolution.HeldTaskID.String()); err != nil {
db.CaptureError(err, "lock send recovery task", nil, "exec")
return nil, errx.InternalError()
}
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,269))`, mailboxID.String()); err != nil {
db.CaptureError(err, "lock send recovery mailbox", nil, "exec")
return nil, errx.InternalError()
}
}
if udata.WarmupStartTime != nil || udata.WarmupEndTime != nil {
// Lock the stored half of a partial patch so concurrent changes cannot cross.
query := `SELECT warmup_start_time::text, warmup_end_time::text FROM email_accounts WHERE organization_id=$1 AND id=$2 FOR UPDATE`
var start, end string
if err := tx.QueryRow(ctx, query, orgID, emailAccountID).Scan(&start, &end); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
db.CaptureError(err, query, []any{orgID, emailAccountID}, "queryrow")
return nil, errx.InternalError()
}
if udata.WarmupStartTime != nil {
start = *udata.WarmupStartTime
}
if udata.WarmupEndTime != nil {
end = *udata.WarmupEndTime
}
if xerr := validate.WarmupWindow(start, end); xerr != nil {
return nil, xerr
}
}
if udata.SendRecoveryResolution != nil {
resolution := udata.SendRecoveryResolution
if strings.ContainsAny(resolution.ConfirmationReference, "\r\n") || len(resolution.ConfirmationReference) > 256 {
return nil, errx.ErrInvalid
}
if resolution.HeldReason == "unknown" {
if xerr := queueUnknownSendResolution(ctx, tx, orgID, emailAccountID, resolution); xerr != nil {
return nil, xerr
}
} else {
var evidenceTask any
if resolution.EvidenceTaskID != nil {
evidenceTask = *resolution.EvidenceTaskID
}
tag, resolveErr := tx.Exec(ctx, `WITH held AS(
SELECT ea.organization_id,ea.id,ea.send_recovery_task_id,ea.send_recovery_reason,t.completed_at,ea.last_synced_at
FROM email_accounts ea LEFT JOIN tasks t ON t.id=ea.send_recovery_task_id
WHERE ea.organization_id=$1 AND ea.id=$2 AND ea.status='active' AND ea.send_recovery_hold AND ea.send_recovery_task_id=$6 AND ea.send_recovery_reason=$7 AND ea.send_recovery_reason IN('authentication','permanent','conflict','domain_auth')
AND (ea.send_cooldown_provider IS NULL OR ea.send_cooldown_provider=ea.provider::text) FOR UPDATE OF ea),
valid AS(SELECT * FROM held WHERE NOT EXISTS(SELECT 1 FROM tasks u WHERE u.email_account_id=held.id AND u.send_result_state='unknown' AND u.send_result_applied_at IS NULL AND u.warmup_send_retired_at IS NULL AND u.campaign_send_isolated_at IS NULL AND u.send_hold_lifted_at IS NULL)
AND (($3='authentication_repaired' AND held.send_recovery_reason='authentication' AND $4::uuid IS NOT NULL
AND EXISTS(SELECT 1 FROM tasks e WHERE e.id=$4 AND e.email_account_id=held.id AND e.send_result_state='sent' AND e.send_result_applied_at>held.completed_at AND e.send_executor_started_at>held.completed_at))
OR ($3='operator_provider_confirmation' AND held.send_recovery_reason IN('authentication','permanent','conflict','domain_auth') AND length($5)>0 AND $4::uuid IS NOT NULL
AND EXISTS(SELECT 1 FROM tasks e WHERE e.id=$4 AND e.email_account_id=held.id AND e.send_result_state IN('sent','failed') AND e.send_result_applied_at IS NOT NULL)))),
history AS(INSERT INTO send_recovery_resolutions(organization_id,email_account_id,recovery_task_id,evidence_task_id,previous_reason,evidence_type,confirmation_reference,recorded_locally_at)
SELECT organization_id,id,send_recovery_task_id,$4,send_recovery_reason,$3,$5,clock_timestamp() FROM valid RETURNING email_account_id)
UPDATE email_accounts ea SET send_recovery_hold=false,send_recovery_reason=NULL,send_recovery_task_id=NULL
FROM history WHERE ea.id=history.email_account_id`, orgID, emailAccountID, resolution.EvidenceType, evidenceTask, strings.TrimSpace(resolution.ConfirmationReference), resolution.HeldTaskID, resolution.HeldReason)
if resolveErr != nil {
db.CaptureError(resolveErr, "resolve send recovery", nil, "exec")
return nil, errx.InternalError()
}
if tag.RowsAffected() != 1 {
return nil, errx.ErrInvalid
}
if resolution.HeldReason == "conflict" {
if _, resolveErr := tx.Exec(ctx, `UPDATE send_recovery_resolutions SET conflict_resolved_at=clock_timestamp()
WHERE organization_id=$1 AND email_account_id=$2 AND recovery_task_id=$3
AND conflict_detected_at IS NOT NULL AND conflict_resolved_at IS NULL
AND (previous_reason='unknown' OR evidence_type='authoritative_result_conflict')`, orgID, emailAccountID, resolution.HeldTaskID); resolveErr != nil {
db.CaptureError(resolveErr, "resolve outcome conflict", nil, "exec")
return nil, errx.InternalError()
}
}
mailboxID, parseErr := uuid.Parse(emailAccountID)
if parseErr != nil {
return nil, errx.ErrInvalid
}
if resolveErr := refreshSendHold(ctx, tx, mailboxID, nil, nil); resolveErr != nil {
db.CaptureError(resolveErr, "refresh send recovery", nil, "exec")
return nil, errx.InternalError()
}
}
}
query := fmt.Sprintf(`
UPDATE email_accounts
SET %s
WHERE organization_id = $1 AND id = $2
RETURNING id, organization_id, email, name, signature_plain, signature_html, signature_sync, signature_code, send_as_email, provider, mail_host, auth_method, domain_grant_id, vendor_connection_id, COALESCE((SELECT vc.vendor FROM mailbox_vendor_connections vc WHERE vc.id = email_accounts.vendor_connection_id), ''), avatar_url, status,
COALESCE(last_synced_at, created_at) AS last_synced_at, last_id, campaign_limit, min_wait_time, reply_to, tracking_domain, tracking_domain_verified, tracking_domain_verified_at, track_direct_mail,
auth_state, auth_spf, auth_dkim, auth_dmarc, auth_dmarc_policy, auth_reason, auth_checked_at, auth_failing_since,
warmup, warmup_paused_at, warmup_base, warmup_max, warmup_increase, warmup_reply_rate, warmup_tag, warmup_pool_type,
warmup_start_time, warmup_end_time, warmup_days, test_mode, test_send_enabled, test_receive_enabled, shared_daily_limit, rolling_recipient_limit, warmup_placement, warmup_folder, COALESCE(warmup_retention_days, 0) AS warmup_retention_days, save_to_sent, relay_folder_moves, created_at, updated_at,
timezone, COALESCE((SELECT o.timezone FROM organizations o WHERE o.id = email_accounts.organization_id), '') AS org_timezone
`, strings.Join(setClauses, ", "))
var i models.Email
err = tx.QueryRow(ctx, query, args...).Scan(
&i.ID, &i.OrganizationID, &i.Email, &i.Name, &i.SignaturePlain, &i.SignatureHTML, &i.SignatureSync, &i.SignatureCode, &i.SendAsEmail, &i.Provider, &i.MailHost, &i.AuthMethod, &i.DomainGrantID, &i.VendorConnectionID, &i.Vendor, &i.AvatarURL, &i.Status,
&i.LastSyncedAt, &i.LastID, &i.CampaignLimit, &i.MinWaitTime, &i.ReplyTo, &i.TrackingDomain, &i.TrackingDomainVerified, &i.TrackingDomainVerifiedAt, &i.TrackDirectMail,
// The client replaces its whole cached mailbox with this row, so an
// incomplete object here silently blanks the domain-auth state in the
// dashboard on every unrelated edit.
&i.AuthState, &i.AuthSPF, &i.AuthDKIM, &i.AuthDMARC, &i.AuthDMARCPolicy, &i.AuthReason, &i.AuthCheckedAt, &i.AuthFailingSince,
&i.Warmup, &i.WarmupPausedAt, &i.WarmupBase, &i.WarmupMax, &i.WarmupIncrease, &i.WarmupReplyRate, &i.WarmupTag, &i.WarmupPoolType,
&i.WarmupStartTime, &i.WarmupEndTime, &i.WarmupDays, &i.TestMode, &i.TestSendEnabled, &i.TestReceiveEnabled, &i.SharedDailyLimit, &i.RollingRecipientLimit, &i.WarmupPlacement, &i.WarmupFolder, &i.WarmupRetentionDays, &i.SaveToSent, &i.RelayFolderMoves,
&i.CreatedAt, &i.UpdatedAt,
&i.Timezone, &i.OrgTimezone,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
db.CaptureError(err, query, args, "queryrow")
return nil, errx.InternalError()
}
i.Tags = make([]string, 0)
if udata.Tags != nil {
var err *errx.Error
i.Tags, err = SyncEmailTags(ctx, tx, orgID, emailAccountID, udata.Tags)
if err != nil {
return nil, err
}
}
if err := tx.Commit(ctx); err != nil {
db.CaptureError(err, "", nil, "commit")
return nil, errx.InternalError()
}
return &i, nil
}
// BulkUpdateTags rewrites tag links across many mailboxes at once. Both sides
// are scoped by organization: the mailboxes because they belong to the
// workspace, and the tag definitions because the registry does too.
func (r *emailRepository) BulkUpdateTags(ctx context.Context, orgID string, emailIDs, addTags, removeTags []uuid.UUID) (int, *errx.Error) {
tx, err := r.DB.Begin(ctx)
if err != nil {
db.CaptureError(err, "", nil, "begin")
return 0, errx.InternalError()
}
defer tx.Rollback(ctx)
var owned int
countQuery := `SELECT count(*) FROM email_accounts WHERE organization_id = $1 AND id = ANY($2)`
if err := tx.QueryRow(ctx, countQuery, orgID, emailIDs).Scan(&owned); err != nil {
db.CaptureError(err, countQuery, []any{orgID}, "queryrow")
return 0, errx.InternalError()
}
if len(addTags) > 0 {
// Cross join the workspace's mailboxes with its tag definitions;
// the composite PK makes re-adding an existing link a no-op.
insertQuery := `
INSERT INTO email_tags (email_id, tag_id)
SELECT a.id, t.id
FROM email_accounts a
CROSS JOIN tags t
WHERE a.organization_id = $1 AND a.id = ANY($2)
AND t.organization_id = $1 AND t.id = ANY($3)
ON CONFLICT (email_id, tag_id) DO NOTHING`
if _, err := tx.Exec(ctx, insertQuery, orgID, emailIDs, addTags); err != nil {
db.CaptureError(err, insertQuery, []any{orgID}, "exec")
return 0, errx.InternalError()
}
}
if len(removeTags) > 0 {
deleteQuery := `
DELETE FROM email_tags
WHERE tag_id = ANY($3)
AND email_id IN (SELECT id FROM email_accounts WHERE organization_id = $1 AND id = ANY($2))`
if _, err := tx.Exec(ctx, deleteQuery, orgID, emailIDs, removeTags); err != nil {
db.CaptureError(err, deleteQuery, []any{orgID}, "exec")
return 0, errx.InternalError()
}
}
if err := tx.Commit(ctx); err != nil {
db.CaptureError(err, "", nil, "commit")
return 0, errx.InternalError()
}
return owned, nil
}
// UpdateTrackingDomain writes the tracking domain and its verdict. Scoped by
// organization, like Get and Search: a mailbox is a workspace asset, and the
// route already admits any member holding manage_emails, so filtering on the
// user who happened to connect it turned that permission into a 404.
func (r *emailRepository) UpdateTrackingDomain(ctx context.Context, orgID, emailAccountID, domain string, verified bool, verifiedAt *time.Time) *errx.Error {
if held, xerr := trackingDomainHeldElsewhere(ctx, r.DB, orgID, domain); xerr != nil {
return xerr
} else if held {
return errx.ErrTrackingDomainTaken
}
query := `
UPDATE email_accounts
SET tracking_domain = $1, tracking_domain_verified = $2, tracking_domain_verified_at = $3
WHERE organization_id = $4 AND id = $5
`
params := []any{
domain,
verified,
verifiedAt,
orgID,
emailAccountID,
}
cmd, err := r.DB.Exec(
ctx,
query,
params...,
)
if isTrackingDomainTaken(err) {
return errx.ErrTrackingDomainTaken
}
if err != nil {
db.CaptureError(err, query, params, "exec")
return errx.InternalError()
}
if cmd.RowsAffected() == 0 {
return errx.ErrNotFound
}
return nil
}
// ListTrackingDomainCheckDue picks the mailboxes the tracking-domain sweep
// re-resolves next. Unverified ones sort first (their verified_at is NULL), so
// a record that has just propagated is picked up on the next pass without
// anybody pressing anything.
func (r *emailRepository) ListTrackingDomainCheckDue(ctx context.Context, staleBefore time.Time, limit int) ([]models.TrackingDomainTarget, *errx.Error) {
query := `
SELECT id, COALESCE(organization_id, '00000000-0000-0000-0000-000000000000'::uuid), tracking_domain, tracking_domain_verified
FROM email_accounts
WHERE status = 'active'
AND COALESCE(tracking_domain, '') <> ''
AND (tracking_domain_verified_at IS NULL OR tracking_domain_verified_at < $1)
ORDER BY tracking_domain_verified_at ASC NULLS FIRST
LIMIT $2
`
params := []any{staleBefore, limit}
rows, err := r.DB.Query(ctx, query, params...)
if err != nil {
db.CaptureError(err, query, params, "query")
return nil, errx.InternalError()
}
defer rows.Close()
out := []models.TrackingDomainTarget{}
for rows.Next() {
var t models.TrackingDomainTarget
if err := rows.Scan(&t.ID, &t.OrganizationID, &t.Domain, &t.Verified); err != nil {
db.CaptureError(err, query, params, "scan")
return nil, errx.InternalError()
}
out = append(out, t)
}
if err := rows.Err(); err != nil {
db.CaptureError(err, query, params, "rows")
return nil, errx.InternalError()
}
return out, nil
}
func (r *emailRepository) SetTrackingDomainVerified(ctx context.Context, emailAccountID uuid.UUID, verified bool, verifiedAt *time.Time) *errx.Error {
query := `
UPDATE email_accounts
SET tracking_domain_verified = $1, tracking_domain_verified_at = $2
WHERE id = $3
`
params := []any{verified, verifiedAt, emailAccountID}
if _, err := r.DB.Exec(ctx, query, params...); err != nil {
if isTrackingDomainTaken(err) {
return errx.ErrTrackingDomainTaken
}
db.CaptureError(err, query, params, "exec")
return errx.InternalError()
}
return nil
}
func (r *emailRepository) ListAuthCheckDue(ctx context.Context, staleBefore time.Time, limit int) ([]models.EmailAuthTarget, *errx.Error) {
query := `
SELECT ea.id, ea.email
FROM email_accounts ea
WHERE ea.status = 'active'
AND (ea.auth_checked_at IS NULL OR ea.auth_checked_at < $1)
ORDER BY ea.auth_checked_at ASC NULLS FIRST
LIMIT $2
`
rows, err := r.DB.Query(ctx, query, staleBefore, limit)
if err != nil {
db.CaptureError(err, query, []any{staleBefore, limit}, "query")
return nil, errx.InternalError()
}
defer rows.Close()
targets := make([]models.EmailAuthTarget, 0)
for rows.Next() {
var t models.EmailAuthTarget
if err := rows.Scan(&t.ID, &t.Email); err != nil {
db.CaptureError(err, "", nil, "scan")
return nil, errx.InternalError()
}
targets = append(targets, t)
}
if err := rows.Err(); err != nil {
db.CaptureError(err, "", nil, "rows")
return nil, errx.InternalError()
}
return targets, nil
}
func (r *emailRepository) UpdateDomainAuthState(ctx context.Context, domain, state string, spf, dkim, dmarc bool, dmarcPolicy, reason string, checkedAt time.Time) ([]models.EmailAuthTransition, *errx.Error) {
return r.updateDomainAuthState(ctx, nil, domain, state, spf, dkim, dmarc, dmarcPolicy, reason, checkedAt)
}
func (r *emailRepository) UpdateDomainAuthStateForOrg(ctx context.Context, orgID uuid.UUID, domain, state string, spf, dkim, dmarc bool, dmarcPolicy, reason string, checkedAt time.Time) ([]models.EmailAuthTransition, *errx.Error) {
return r.updateDomainAuthState(ctx, &orgID, domain, state, spf, dkim, dmarc, dmarcPolicy, reason, checkedAt)
}
func (r *emailRepository) updateDomainAuthState(ctx context.Context, orgID *uuid.UUID, domain, state string, spf, dkim, dmarc bool, dmarcPolicy, reason string, checkedAt time.Time) ([]models.EmailAuthTransition, *errx.Error) {
// Only 'passing' clears the grace clock; 'unknown' preserves it so a domain
// cannot flap through a transient DNS error to escape the gate.
// `before` keys on auth_failing_since, not auth_state, or that same flap
// would re-report every mailbox on the domain as newly failing.
// $9 confines the write to one workspace when the caller named one, and is
// NULL for the background sweep, which is meant to cover every mailbox on
// the domain.
query := `
WITH before AS (
SELECT id
FROM email_accounts
WHERE status = 'active'
AND lower(split_part(email, '@', 2)) = $8
AND ($9::uuid IS NULL OR organization_id = $9::uuid)
AND auth_failing_since IS NOT NULL
),
updated AS (
UPDATE email_accounts
SET auth_state = $1, auth_spf = $2, auth_dkim = $3, auth_dmarc = $4,
auth_dmarc_policy = $5, auth_reason = $6, auth_checked_at = $7,
auth_failing_since = CASE
WHEN $1 = 'passing' THEN NULL
WHEN $1 = 'failing' AND auth_failing_since IS NOT NULL THEN auth_failing_since
WHEN $1 = 'failing' THEN $7
ELSE auth_failing_since
END
WHERE status = 'active' AND lower(split_part(email, '@', 2)) = $8
AND ($9::uuid IS NULL OR organization_id = $9::uuid)
RETURNING id, email, organization_id, auth_state
)
SELECT u.id, u.email, u.organization_id
FROM updated u
WHERE u.auth_state = 'failing'
AND NOT EXISTS (SELECT 1 FROM before b WHERE b.id = u.id)
`
params := []any{
state,
spf,
dkim,
dmarc,
dmarcPolicy,
reason,
checkedAt,
strings.ToLower(strings.TrimSpace(domain)),
orgID,
}
// Only records that failed and now pass release a domain-authentication hold; a domain DNS always passed cannot explain the refusal.
wasFailing := false
if state == "passing" {
if ferr := r.DB.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM email_accounts WHERE status='active' AND lower(split_part(email,'@',2))=$1
AND ($2::uuid IS NULL OR organization_id=$2::uuid) AND auth_failing_since IS NOT NULL)`, params[7], orgID).Scan(&wasFailing); ferr != nil {
db.CaptureError(ferr, "read domain auth failing", nil, "query")
}
}
rows, err := r.DB.Query(ctx, query, params...)
if err != nil {
db.CaptureError(err, query, params, "query")
return nil, errx.InternalError()
}
defer rows.Close()
transitions := make([]models.EmailAuthTransition, 0)
for rows.Next() {
var t models.EmailAuthTransition
if serr := rows.Scan(&t.ID, &t.Email, &t.OrganizationID); serr != nil {
db.CaptureError(serr, "", nil, "scan")
return nil, errx.InternalError()
}
transitions = append(transitions, t)
}
if rerr := rows.Err(); rerr != nil {
db.CaptureError(rerr, "", nil, "rows")
return nil, errx.InternalError()
}
rows.Close()
if wasFailing {
if _, herr := r.ReleaseDomainAuthHolds(ctx, orgID, strings.ToLower(strings.TrimSpace(domain))); herr != nil {
db.CaptureError(herr, "release domain auth holds", nil, "exec")
}
}
return transitions, nil
}
// Delete removes a mailbox and refunds its worker's capacity in ONE
// transaction. Split in two, the refund can be lost for good: after the row is
// gone nothing records which worker was charged for that mailbox, so a refund
// that failed on its own could never be repaired and the worker would carry a
// deleted mailbox's load forever. workerLoadRefund is the mailbox's placement
// weight, computed by the caller from the same provider and warmup flag
// assignment charged it with.
// deleteDeadlockAttempts bounds the retry below. Two is almost always enough:
// the transaction we lost to has committed by the time we come back.
const deleteDeadlockAttempts = 3
// Delete removes a mailbox, retrying a deadlock.
//
// The delete cascades into two dozen child tables (tasks, unibox_emails,
// email_sync_state, warmup_statistics and the rest) and takes a lock on each,
// while the consumer is still writing to several of them for the same mailbox.
// Postgres resolves the cycle by aborting one side, and roughly half the time
// that side is this one. Nothing is wrong when it happens and the work is
// entirely redoable, so surfacing it meant someone clicking Disconnect got an
// error for an operation that would have succeeded a moment later.
func (r *emailRepository) Delete(ctx context.Context, orgID, emailAccountID string, workerLoadRefund float64) *errx.Error {
for attempt := 1; ; attempt++ {
xerr, deadlocked := r.deleteOnce(ctx, orgID, emailAccountID, workerLoadRefund)
if !deadlocked || attempt >= deleteDeadlockAttempts {
return xerr
}
}
}
func (r *emailRepository) deleteOnce(ctx context.Context, orgID, emailAccountID string, workerLoadRefund float64) (*errx.Error, bool) {
tx, err := r.DB.Begin(ctx)
if err != nil {
db.CaptureError(err, "", nil, "begin")
return errx.InternalError(), false
}
defer tx.Rollback(ctx)
// The mailbox's standing is already mirrored by address (see migration
// 000152); removing the row only restarts the retention window on it, so
// the standing is kept for the full window after the removal rather than
// after the last time it changed. Same predicate as the delete below.
bump := `
UPDATE warmup_reputation_ledger l
SET recorded_at = now()
FROM email_accounts a
WHERE a.organization_id = $1 AND a.id = $2
AND l.organization_id = a.organization_id
AND l.email = lower(btrim(a.email))
`
bumpParams := []any{orgID, emailAccountID}
if _, err := tx.Exec(ctx, bump, bumpParams...); err != nil {
if isDeadlock(err) {
return errx.InternalError(), true
}
db.CaptureError(err, bump, bumpParams, "exec")
return errx.InternalError(), false
}
// Before the row goes: what the mailbox leaves outside Postgres. The
// sealed refresh token lives in email_accounts_oauth, which cascades away
// with the mailbox, so reading it afterwards is impossible and the grant
// would stay live at the provider forever.
const scope = `a.organization_id = $1 AND a.id = $2`
if _, err := EnqueueMailboxErasures(ctx, tx, scope, orgID, emailAccountID); err != nil {
return errx.InternalError(), isDeadlock(err)
}
// The threads this mailbox holds messages in, read while they still exist.
threads, err := CollectMailboxThreadState(ctx, tx, scope, orgID, emailAccountID)
if err != nil {
return errx.InternalError(), isDeadlock(err)
}
query := `
DELETE FROM email_accounts
WHERE organization_id = $1 AND id = $2
RETURNING worker_id
`
params := []any{orgID, emailAccountID}
var workerID *uuid.UUID
if err := tx.QueryRow(ctx, query, params...).Scan(&workerID); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return errx.ErrNotFound, false
}
// The cascade is what deadlocks, so this is the statement that loses
// most often. Not captured: a retried deadlock is not an incident.
if isDeadlock(err) {
return errx.InternalError(), true
}
db.CaptureError(err, query, params, "queryrow")
return errx.InternalError(), false
}
// After the row goes: the labels and snoozes whose threads the cascade just
// emptied. Nothing references the mailbox from those rows, so without this
// the workspace keeps labels on threads with no messages left in them.
if err := DeleteOrphanedThreadState(ctx, tx, threads); err != nil {
return errx.InternalError(), isDeadlock(err)
}
if accountID, err := uuid.Parse(emailAccountID); err == nil {
if err := ResolveAdvisorFindingsFor(ctx, tx, orgID, []uuid.UUID{accountID}); err != nil {
if isDeadlock(err) {
return errx.InternalError(), true
}
db.CaptureError(err, "", nil, "exec")
return errx.InternalError(), false
}
}
if workerID != nil {
refund := `
UPDATE workers
SET account_count = GREATEST(account_count - 1, 0),
load_score = GREATEST(0, load_score - $2),
updated_at = now()
WHERE id = $1
`
if _, err := tx.Exec(ctx, refund, *workerID, workerLoadRefund); err != nil {
if isDeadlock(err) {
return errx.InternalError(), true
}
db.CaptureError(err, refund, []any{*workerID, workerLoadRefund}, "exec")
return errx.InternalError(), false
}
}
if err := tx.Commit(ctx); err != nil {
if isDeadlock(err) {
return errx.InternalError(), true
}
db.CaptureError(err, "", nil, "commit")
return errx.InternalError(), false
}
return nil, false
}
// GetByID retrieves an email account by ID without requiring userID (for internal service use)
// SetWarmupLifecycle applies a warmup lifecycle transition. The CASE math
// keeps every transition atomic and idempotent:
//
// - start/resume: a fresh mailbox (warmup IS NULL) anchors at now(); a
// paused mailbox shifts its anchor forward by the paused duration so the
// ramp continues where it left off; an already-active mailbox is a no-op.
// - pause: stamps warmup_paused_at only while actively warming.
// - disable/stop: pauses the anchor and stamps warmup_stopped_at, which
// lifts the cold ceiling; warmup history is kept, so a restart resumes.
func (r *emailRepository) SetWarmupLifecycle(ctx context.Context, orgID, emailAccountID, action string) (*models.Email, *errx.Error) {
var setClause string
switch action {
case "start", "resume":
setClause = `warmup = CASE
WHEN warmup IS NULL THEN now()
WHEN warmup_paused_at IS NOT NULL THEN warmup + (now() - warmup_paused_at)
ELSE warmup
END,
warmup_paused_at = NULL, warmup_stopped_at = NULL,
test_receive_enabled = CASE WHEN test_mode IS NULL OR test_mode IN ('off','legacy') THEN true ELSE test_receive_enabled END,
test_mode = 'diagnostic', test_send_enabled = true`
case "pause":
setClause = `warmup_paused_at = CASE
WHEN warmup IS NOT NULL AND warmup_paused_at IS NULL THEN now()
ELSE warmup_paused_at
END,
test_receive_enabled = CASE WHEN test_mode IS NULL OR test_mode='legacy' THEN true ELSE test_receive_enabled END,
test_mode = 'diagnostic', test_send_enabled = false`
case "disable", "stop":
setClause = `warmup_paused_at = CASE WHEN warmup IS NOT NULL THEN COALESCE(warmup_paused_at,now()) ELSE NULL END,
warmup_stopped_at = COALESCE(warmup_stopped_at,clock_timestamp()),
test_mode = 'off', test_send_enabled = false, test_receive_enabled = false`
default:
return nil, errx.ErrInvalid
}
query := fmt.Sprintf(`
UPDATE email_accounts
SET %s, updated_at = now()
WHERE organization_id = $1 AND id = $2
`, setClause)
id, perr := uuid.Parse(emailAccountID)
if perr != nil {
return nil, errx.ErrUuid
}
tx, err := r.DB.Begin(ctx)
if err != nil {
return nil, errx.InternalError()
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,270))`, id.String()); err != nil {
return nil, errx.InternalError()
}
var currentMode *string
var currentSend, currentReceive, currentPaused bool
var currentStatus string
if err := tx.QueryRow(ctx, `SELECT test_mode,status,test_send_enabled,test_receive_enabled,warmup_paused_at IS NOT NULL FROM email_accounts WHERE organization_id=$1 AND id=$2`, orgID, id).Scan(&currentMode, &currentStatus, &currentSend, &currentReceive, &currentPaused); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
return nil, errx.InternalError()
}
diagnostic := currentMode != nil && *currentMode == "diagnostic"
sendingOff := currentPaused || action == "pause" || diagnostic && !currentSend
// Warmup off stops receiving as well as sending.
receivingOff := currentPaused || action == "pause" || diagnostic && !currentReceive
direction := ""
if action == "stop" || action == "disable" || currentStatus != "active" || currentMode != nil && *currentMode == "off" || sendingOff && receivingOff {
direction = "both"
} else if sendingOff {
direction = "sender"
} else if receivingOff {
direction = "receiver"
}
if direction != "" {
if err := retireStoppedWarmupDispatches(ctx, tx, id, direction); err != nil {
db.CaptureError(err, "retire stopped warmup dispatches", nil, "exec")
return nil, errx.InternalError()
}
}
tag, err := tx.Exec(ctx, query, orgID, emailAccountID)
if err != nil {
db.CaptureError(err, query, []any{orgID, emailAccountID}, "exec")
return nil, errx.InternalError()
}
if tag.RowsAffected() == 0 {
return nil, errx.ErrNotFound
}
// The UPDATE already proved the mailbox belongs to this workspace, so the
// re-read can go by id.
if err := tx.Commit(ctx); err != nil {
return nil, errx.InternalError()
}
return r.GetByID(ctx, id)
}
func (r *emailRepository) GetByID(ctx context.Context, emailAccountID uuid.UUID) (*models.Email, *errx.Error) {
query := `
SELECT
ea.transport_generation,
ea.id, ea.user_id, ea.organization_id, ea.worker_id, ea.email, ea.name, ea.signature_plain, ea.signature_html, ea.signature_sync, ea.signature_code, ea.send_as_email,
ea.provider, ea.mail_host, ea.auth_method, ea.domain_grant_id, ea.vendor_connection_id, COALESCE((SELECT vc.vendor FROM mailbox_vendor_connections vc WHERE vc.id = ea.vendor_connection_id), ''), ea.avatar_url, ea.status, COALESCE(ea.last_synced_at, ea.created_at) AS last_synced_at, ea.last_id, ea.campaign_limit,
ea.min_wait_time, ea.reply_to, ea.tracking_domain, ea.tracking_domain_verified, ea.tracking_domain_verified_at, ea.track_direct_mail, ea.warmup, ea.warmup_paused_at, ea.warmup_base,
ea.warmup_max, ea.warmup_increase, ea.warmup_reply_rate, ea.warmup_tag, ea.warmup_pool_type,
ea.warmup_start_time, ea.warmup_end_time, ea.warmup_days, ea.test_mode, ea.test_send_enabled, ea.test_receive_enabled, ea.shared_daily_limit, ea.rolling_recipient_limit, ea.warmup_placement, ea.warmup_folder, COALESCE(ea.warmup_retention_days, 0) AS warmup_retention_days, ea.timezone, COALESCE((SELECT o.timezone FROM organizations o WHERE o.id = ea.organization_id), '') AS org_timezone, ea.save_to_sent, ea.relay_folder_moves,
ea.auth_state, ea.auth_failing_since,
ea.created_at, ea.updated_at,
COALESCE(array_agg(eat.tag_id) FILTER (WHERE eat.tag_id IS NOT NULL), '{}') AS tags
FROM email_accounts ea
LEFT JOIN email_tags eat ON eat.email_id = ea.id
WHERE ea.id = $1
GROUP BY ea.id
`
var i models.Email
err := r.transportQueryRow(ctx, query, emailAccountID).Scan(
&i.TransportGeneration,
&i.ID, &i.UserID, &i.OrganizationID, &i.WorkerID, &i.Email, &i.Name, &i.SignaturePlain, &i.SignatureHTML, &i.SignatureSync, &i.SignatureCode, &i.SendAsEmail,
&i.Provider, &i.MailHost, &i.AuthMethod, &i.DomainGrantID, &i.VendorConnectionID, &i.Vendor, &i.AvatarURL, &i.Status, &i.LastSyncedAt, &i.LastID, &i.CampaignLimit,
&i.MinWaitTime, &i.ReplyTo, &i.TrackingDomain, &i.TrackingDomainVerified, &i.TrackingDomainVerifiedAt, &i.TrackDirectMail, &i.Warmup, &i.WarmupPausedAt, &i.WarmupBase,
&i.WarmupMax, &i.WarmupIncrease, &i.WarmupReplyRate, &i.WarmupTag, &i.WarmupPoolType,
&i.WarmupStartTime, &i.WarmupEndTime, &i.WarmupDays, &i.TestMode, &i.TestSendEnabled, &i.TestReceiveEnabled, &i.SharedDailyLimit, &i.RollingRecipientLimit, &i.WarmupPlacement, &i.WarmupFolder, &i.WarmupRetentionDays, &i.Timezone, &i.OrgTimezone, &i.SaveToSent, &i.RelayFolderMoves,
&i.AuthState, &i.AuthFailingSince,
&i.CreatedAt, &i.UpdatedAt, &i.Tags,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
db.CaptureError(err, query, []any{emailAccountID}, "queryrow")
return nil, errx.InternalError()
}
return &i, nil
}
// GetSendIdentity reads one mailbox's stored sending identity. Scoped by
// organization like Get: a mailbox is a workspace asset.
func (r *emailRepository) GetSendIdentity(ctx context.Context, orgID, emailAccountID string) (*models.SendIdentity, *errx.Error) {
query := `
SELECT provider, email, send_as_email, send_as, send_as_synced_at, signature_source, signature_imported_at
FROM email_accounts
WHERE organization_id = $1 AND id = $2
`
var out models.SendIdentity
var raw []byte
err := r.DB.QueryRow(ctx, query, orgID, emailAccountID).Scan(
&out.Provider, &out.MailboxEmail, &out.SendAsEmail, &raw, &out.SyncedAt, &out.SignatureSource, &out.SignatureImportedAt,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
db.CaptureError(err, query, []any{orgID, emailAccountID}, "queryrow")
return nil, errx.InternalError()
}
out.Identities = []models.SendAsIdentity{}
if len(raw) > 0 {
// A blob we cannot read is reported as no identities rather than as an
// error: the list is a cache of what the provider said, and a refresh
// rewrites it.
if err := json.Unmarshal(raw, &out.Identities); err != nil {
db.CaptureError(err, "", nil, "unmarshal-send-as")
out.Identities = []models.SendAsIdentity{}
}
}
out.Supported = models.InboxProvider(out.Provider) == models.InboxProviderGoogle
return &out, nil
}
// SetSendIdentity stores a freshly read send-as list, and the signature when
// the caller imported one.
//
// The chosen alias is re-checked against the new list in the same statement.
// An alias the customer removed at the provider would otherwise stay on the
// From header of every message until a send failed, and the provider's refusal
// names nothing a customer could act on.
func (r *emailRepository) SetSendIdentity(ctx context.Context, emailAccountID uuid.UUID, identities []models.SendAsIdentity, sig *models.ImportedSignature) *errx.Error {
if identities == nil {
identities = []models.SendAsIdentity{}
}
raw, err := json.Marshal(identities)
if err != nil {
db.CaptureError(err, "", nil, "marshal-send-as")
return errx.InternalError()
}
verified := make([]string, 0, len(identities))
for _, id := range identities {
if id.Verified {
verified = append(verified, strings.ToLower(strings.TrimSpace(id.Email)))
}
}
query := `
UPDATE email_accounts SET
send_as = $2,
send_as_synced_at = now(),
send_as_email = CASE WHEN lower(send_as_email) = ANY($3::text[]) THEN send_as_email ELSE '' END,
signature_html = CASE WHEN $4::boolean THEN $5 ELSE signature_html END,
signature_plain = CASE WHEN $4::boolean THEN $6 ELSE signature_plain END,
signature_source = CASE WHEN $4::boolean THEN $7 ELSE signature_source END,
signature_imported_at = CASE WHEN $4::boolean THEN now() ELSE signature_imported_at END,
updated_at = now()
WHERE id = $1
`
var sigHTML, sigPlain string
if sig != nil {
sigHTML, sigPlain = sig.HTML, sig.Plain
}
params := []any{emailAccountID, raw, verified, sig != nil, sigHTML, sigPlain, models.SignatureSourceProvider}
tag, err := r.DB.Exec(ctx, query, params...)
if err != nil {
db.CaptureError(err, query, nil, "exec")
return errx.InternalError()
}
if tag.RowsAffected() == 0 {
return errx.ErrNotFound
}
return nil
}
// GetByTags retrieves the scope's active mailboxes matching any of the tags.
// Tags themselves are owned by a user, not an organization, so a multi-org
// user's tag can span workspaces — the scope predicate is what keeps the
// resolved senders inside one tenant.
func (r *emailRepository) GetByTags(ctx context.Context, scope AccountScope, tags []string) ([]models.Email, *errx.Error) {
orgID, ok := scope.tenant()
if len(tags) == 0 || !ok {
return []models.Email{}, nil
}
query := `
SELECT DISTINCT ON (ea.id)
ea.id, ea.user_id, ea.email, ea.name, ea.signature_plain, ea.signature_html, ea.signature_sync, ea.signature_code, ea.send_as_email,
ea.provider, ea.mail_host, ea.auth_method, ea.domain_grant_id, ea.vendor_connection_id, COALESCE((SELECT vc.vendor FROM mailbox_vendor_connections vc WHERE vc.id = ea.vendor_connection_id), ''), ea.avatar_url, ea.status, COALESCE(ea.last_synced_at, ea.created_at) AS last_synced_at, ea.last_id, ea.campaign_limit,
ea.min_wait_time, ea.reply_to, ea.tracking_domain, ea.tracking_domain_verified, ea.tracking_domain_verified_at, ea.track_direct_mail, ea.warmup, ea.warmup_paused_at, ea.warmup_base,
ea.warmup_max, ea.warmup_increase, ea.warmup_reply_rate, ea.warmup_tag,
ea.warmup_start_time, ea.warmup_end_time, ea.warmup_days, ea.test_mode, ea.test_send_enabled, ea.test_receive_enabled, ea.shared_daily_limit, ea.rolling_recipient_limit, ea.timezone, COALESCE((SELECT o.timezone FROM organizations o WHERE o.id = ea.organization_id), '') AS org_timezone,
ea.auth_state, ea.auth_failing_since, ea.worker_id,
ea.created_at, ea.updated_at
FROM email_accounts ea
JOIN email_tags eat ON eat.email_id = ea.id
WHERE ea.organization_id = $1
AND eat.tag_id = ANY($2)
AND ea.status = 'active'
-- A seed mailbox is a placement test inbox and never sends campaign mail.
AND ea.seed_scope IS NULL
ORDER BY ea.id
`
rows, err := r.DB.Query(ctx, query, orgID, tags)
if err != nil {
db.CaptureError(err, query, []any{orgID, tags}, "query")
return nil, errx.InternalError()
}
defer rows.Close()
var emails []models.Email
for rows.Next() {
var i models.Email
err := rows.Scan(
&i.ID, &i.UserID, &i.Email, &i.Name, &i.SignaturePlain, &i.SignatureHTML, &i.SignatureSync, &i.SignatureCode, &i.SendAsEmail,
&i.Provider, &i.MailHost, &i.AuthMethod, &i.DomainGrantID, &i.VendorConnectionID, &i.Vendor, &i.AvatarURL, &i.Status, &i.LastSyncedAt, &i.LastID, &i.CampaignLimit,
&i.MinWaitTime, &i.ReplyTo, &i.TrackingDomain, &i.TrackingDomainVerified, &i.TrackingDomainVerifiedAt, &i.TrackDirectMail, &i.Warmup, &i.WarmupPausedAt, &i.WarmupBase,
&i.WarmupMax, &i.WarmupIncrease, &i.WarmupReplyRate, &i.WarmupTag,
&i.WarmupStartTime, &i.WarmupEndTime, &i.WarmupDays, &i.TestMode, &i.TestSendEnabled, &i.TestReceiveEnabled, &i.SharedDailyLimit, &i.RollingRecipientLimit, &i.Timezone, &i.OrgTimezone,
&i.AuthState, &i.AuthFailingSince, &i.WorkerID,
&i.CreatedAt, &i.UpdatedAt,
)
if err != nil {
db.CaptureError(err, "", nil, "scan")
return nil, errx.InternalError()
}
i.OrganizationID = &orgID
i.Tags = []string{} // Tags not fetched in this query
emails = append(emails, i)
}
return emails, nil
}
// GetAllActiveInScope returns every active mailbox in the scope (the "all"
// sender pool). Same projection as GetByTags, without the tag join.
func (r *emailRepository) GetAllActiveInScope(ctx context.Context, scope AccountScope) ([]models.Email, *errx.Error) {
orgID, ok := scope.tenant()
if !ok {
return []models.Email{}, nil
}
query := `
SELECT
ea.id, ea.user_id, ea.email, ea.name, ea.signature_plain, ea.signature_html, ea.signature_sync, ea.signature_code, ea.send_as_email,
ea.provider, ea.mail_host, ea.auth_method, ea.domain_grant_id, ea.vendor_connection_id, COALESCE((SELECT vc.vendor FROM mailbox_vendor_connections vc WHERE vc.id = ea.vendor_connection_id), ''), ea.avatar_url, ea.status, COALESCE(ea.last_synced_at, ea.created_at) AS last_synced_at, ea.last_id, ea.campaign_limit,
ea.min_wait_time, ea.reply_to, ea.tracking_domain, ea.tracking_domain_verified, ea.tracking_domain_verified_at, ea.track_direct_mail, ea.warmup, ea.warmup_paused_at, ea.warmup_base,
ea.warmup_max, ea.warmup_increase, ea.warmup_reply_rate, ea.warmup_tag,
ea.warmup_start_time, ea.warmup_end_time, ea.warmup_days, ea.test_mode, ea.test_send_enabled, ea.test_receive_enabled, ea.shared_daily_limit, ea.rolling_recipient_limit, ea.timezone, COALESCE((SELECT o.timezone FROM organizations o WHERE o.id = ea.organization_id), '') AS org_timezone,
ea.auth_state, ea.auth_failing_since, ea.worker_id,
ea.created_at, ea.updated_at
FROM email_accounts ea
WHERE ea.organization_id = $1
AND ea.status = 'active'
-- A seed mailbox is a placement test inbox and never sends campaign mail.
AND ea.seed_scope IS NULL
ORDER BY ea.id
`
rows, err := r.DB.Query(ctx, query, orgID)
if err != nil {
db.CaptureError(err, query, []any{orgID}, "query")
return nil, errx.InternalError()
}
defer rows.Close()
var emails []models.Email
for rows.Next() {
var i models.Email
err := rows.Scan(
&i.ID, &i.UserID, &i.Email, &i.Name, &i.SignaturePlain, &i.SignatureHTML, &i.SignatureSync, &i.SignatureCode, &i.SendAsEmail,
&i.Provider, &i.MailHost, &i.AuthMethod, &i.DomainGrantID, &i.VendorConnectionID, &i.Vendor, &i.AvatarURL, &i.Status, &i.LastSyncedAt, &i.LastID, &i.CampaignLimit,
&i.MinWaitTime, &i.ReplyTo, &i.TrackingDomain, &i.TrackingDomainVerified, &i.TrackingDomainVerifiedAt, &i.TrackDirectMail, &i.Warmup, &i.WarmupPausedAt, &i.WarmupBase,
&i.WarmupMax, &i.WarmupIncrease, &i.WarmupReplyRate, &i.WarmupTag,
&i.WarmupStartTime, &i.WarmupEndTime, &i.WarmupDays, &i.TestMode, &i.TestSendEnabled, &i.TestReceiveEnabled, &i.SharedDailyLimit, &i.RollingRecipientLimit, &i.Timezone, &i.OrgTimezone,
&i.AuthState, &i.AuthFailingSince, &i.WorkerID,
&i.CreatedAt, &i.UpdatedAt,
)
if err != nil {
db.CaptureError(err, "", nil, "scan")
return nil, errx.InternalError()
}
i.OrganizationID = &orgID
i.Tags = []string{}
emails = append(emails, i)
}
return emails, nil
}
// CampaignSenderAccount pairs an active sender mailbox with its per-campaign
// rotation metadata, so the scheduler's rotation modes (weighted / round_robin
// / least_recently_used) can pick among them without a second query.
type CampaignSenderAccount struct {
Account models.Email
Weight int
RotationPosition int
LastSentAt *time.Time
}
// GetByCampaignSenders mirrors GetByTags but resolves accounts through the
// explicit campaign_senders pool instead of email tags. Only enabled senders
// backing an active mailbox are returned; the per-sender weight/cursor/last-send
// ride along for rotation.
func (r *emailRepository) GetByCampaignSenders(ctx context.Context, scope AccountScope, campaignID uuid.UUID) ([]CampaignSenderAccount, *errx.Error) {
orgID, ok := scope.tenant()
if !ok {
return nil, nil
}
query := `
SELECT
ea.id, ea.user_id, ea.email, ea.name, ea.signature_plain, ea.signature_html, ea.signature_sync, ea.signature_code, ea.send_as_email,
ea.provider, ea.mail_host, ea.auth_method, ea.domain_grant_id, ea.vendor_connection_id, COALESCE((SELECT vc.vendor FROM mailbox_vendor_connections vc WHERE vc.id = ea.vendor_connection_id), ''), ea.avatar_url, ea.status, COALESCE(ea.last_synced_at, ea.created_at) AS last_synced_at, ea.last_id, ea.campaign_limit,
ea.min_wait_time, ea.reply_to, ea.tracking_domain, ea.tracking_domain_verified, ea.tracking_domain_verified_at, ea.track_direct_mail, ea.warmup, ea.warmup_paused_at, ea.warmup_base,
ea.warmup_max, ea.warmup_increase, ea.warmup_reply_rate, ea.warmup_tag,
ea.warmup_start_time, ea.warmup_end_time, ea.warmup_days, ea.test_mode, ea.test_send_enabled, ea.test_receive_enabled, ea.shared_daily_limit, ea.rolling_recipient_limit, ea.timezone, COALESCE((SELECT o.timezone FROM organizations o WHERE o.id = ea.organization_id), '') AS org_timezone,
ea.auth_state, ea.auth_failing_since, ea.worker_id,
ea.created_at, ea.updated_at,
cs.weight, cs.rotation_position, cs.last_sent_at
FROM email_accounts ea
JOIN campaign_senders cs ON cs.email_account_id = ea.id
WHERE cs.campaign_id = $2
AND cs.enabled
AND ea.organization_id = $1
AND ea.status = 'active'
-- A seed mailbox is a placement test inbox and never sends campaign mail.
AND ea.seed_scope IS NULL
ORDER BY ea.id
`
rows, err := r.DB.Query(ctx, query, orgID, campaignID)
if err != nil {
db.CaptureError(err, query, []any{orgID, campaignID}, "query")
return nil, errx.InternalError()
}
defer rows.Close()
var out []CampaignSenderAccount
for rows.Next() {
var i models.Email
var sender CampaignSenderAccount
err := rows.Scan(
&i.ID, &i.UserID, &i.Email, &i.Name, &i.SignaturePlain, &i.SignatureHTML, &i.SignatureSync, &i.SignatureCode, &i.SendAsEmail,
&i.Provider, &i.MailHost, &i.AuthMethod, &i.DomainGrantID, &i.VendorConnectionID, &i.Vendor, &i.AvatarURL, &i.Status, &i.LastSyncedAt, &i.LastID, &i.CampaignLimit,
&i.MinWaitTime, &i.ReplyTo, &i.TrackingDomain, &i.TrackingDomainVerified, &i.TrackingDomainVerifiedAt, &i.TrackDirectMail, &i.Warmup, &i.WarmupPausedAt, &i.WarmupBase,
&i.WarmupMax, &i.WarmupIncrease, &i.WarmupReplyRate, &i.WarmupTag,
&i.WarmupStartTime, &i.WarmupEndTime, &i.WarmupDays, &i.TestMode, &i.TestSendEnabled, &i.TestReceiveEnabled, &i.SharedDailyLimit, &i.RollingRecipientLimit, &i.Timezone, &i.OrgTimezone,
&i.AuthState, &i.AuthFailingSince, &i.WorkerID,
&i.CreatedAt, &i.UpdatedAt,
&sender.Weight, &sender.RotationPosition, &sender.LastSentAt,
)
if err != nil {
db.CaptureError(err, "", nil, "scan")
return nil, errx.InternalError()
}
i.OrganizationID = &orgID
i.Tags = []string{}
sender.Account = i
out = append(out, sender)
}
if err := rows.Err(); err != nil {
db.CaptureError(err, "", nil, "rows")
return nil, errx.InternalError()
}
return out, nil
}
// GetSMTPCredentials retrieves SMTP/IMAP credentials for an email account
func (r *emailRepository) GetSMTPCredentials(ctx context.Context, emailAccountID uuid.UUID) (*SMTPCredentials, *errx.Error) {
if r.Creds == nil {
errs.CaptureException(mailcred.ErrNoKey)
return nil, errx.InternalError()
}
query := `
SELECT ea.organization_id, s.smtp_host, s.smtp_port, s.smtp_user, s.smtp_password, s.smtp_security,
s.imap_host, s.imap_port, s.imap_user, s.imap_password, s.imap_security,
s.smtp_tls_unverified, COALESCE(s.smtp_tls_pin, ''), s.imap_tls_unverified, COALESCE(s.imap_tls_pin, '')
FROM email_accounts_smtp_imap s
JOIN email_accounts ea ON ea.id = s.email_account_id
WHERE s.email_account_id = $1
`
var creds SMTPCredentials
var orgID *uuid.UUID
err := r.transportQueryRow(ctx, query, emailAccountID).Scan(
&orgID, &creds.SMTPHost, &creds.SMTPPort, &creds.SMTPUser, &creds.SMTPPassword, &creds.SMTPSecurity,
&creds.IMAPHost, &creds.IMAPPort, &creds.IMAPUser, &creds.IMAPPassword, &creds.IMAPSecurity,
&creds.SMTPTLSUnverified, &creds.SMTPTLSPin, &creds.IMAPTLSUnverified, &creds.IMAPTLSPin,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
db.CaptureError(err, query, []any{emailAccountID}, "queryrow")
return nil, errx.InternalError()
}
if err := r.openCredentials(ctx, orgID, &creds.SMTPHost, &creds.SMTPUser, &creds.SMTPPassword,
&creds.IMAPHost, &creds.IMAPUser, &creds.IMAPPassword); err != nil {
errs.CaptureException(err)
return nil, errx.InternalError()
}
return &creds, nil
}
// GetOAuthCredentials retrieves OAuth credentials for an email account
func (r *emailRepository) GetOAuthCredentials(ctx context.Context, emailAccountID uuid.UUID) (*OAuthCredentials, *errx.Error) {
if r.Creds == nil {
errs.CaptureException(mailcred.ErrNoKey)
return nil, errx.InternalError()
}
query := `
SELECT ea.organization_id, o.access_token, o.refresh_token, o.expires_at, o.granted_scopes, o.oauth_app_id
FROM email_accounts_oauth o
JOIN email_accounts ea ON ea.id = o.email_account_id
WHERE o.email_account_id = $1
`
var orgID *uuid.UUID
var accessToken, refreshToken string
var expiresAt time.Time
var scopes []string
var appID *uuid.UUID
err := r.transportQueryRow(ctx, query, emailAccountID).Scan(
&orgID, &accessToken, &refreshToken, &expiresAt, &scopes, &appID,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
db.CaptureError(err, query, []any{emailAccountID}, "queryrow")
return nil, errx.InternalError()
}
// Decrypt tokens, tolerating rows written before OAuth tokens were sealed.
decryptedAccessToken, accessLegacy, xerr := r.openCredential(ctx, orgID, accessToken)
if xerr != nil {
errs.CaptureException(xerr)
return nil, errx.InternalError()
}
decryptedRefreshToken, refreshLegacy, xerr := r.openCredential(ctx, orgID, refreshToken)
if xerr != nil {
errs.CaptureException(xerr)
return nil, errx.InternalError()
}
if (accessLegacy || refreshLegacy) && r.transportSnapshot == nil {
r.resealOAuthCredentials(ctx, orgID, emailAccountID, accessToken, refreshToken, decryptedAccessToken, decryptedRefreshToken)
}
return &OAuthCredentials{
AccessToken: decryptedAccessToken,
RefreshToken: decryptedRefreshToken,
ExpiresAt: expiresAt,
GrantedScopes: scopes,
OAuthAppID: appID,
}, nil
}
// resealOAuthCredentials rewrites a pre-sealing row in its encrypted form. It
// is the migration path for tokens stored before sealing existed: there is no
// SQL-only migration for them because the key lives in the application, so the
// upgrade happens on first read instead. Best-effort by design, a failure here
// must not break the read that triggered it; the next read retries. The write
// only lands while the row still holds what was read, so a concurrent refresh wins.
func (r *emailRepository) resealOAuthCredentials(ctx context.Context, orgID *uuid.UUID, emailAccountID uuid.UUID, storedAccess, storedRefresh, accessToken, refreshToken string) {
sealed, err := r.sealCredentials(ctx, orgID, accessToken, refreshToken)
if err != nil {
errs.CaptureException(err)
return
}
query := `
UPDATE email_accounts_oauth
SET access_token = $1, refresh_token = $2
WHERE email_account_id = $3 AND access_token = $4 AND refresh_token = $5
`
if _, err := r.DB.Exec(ctx, query, sealed[0], sealed[1], emailAccountID, storedAccess, storedRefresh); err != nil {
db.CaptureError(err, query, nil, "reseal-oauth-credentials")
}
}
// GetWorkerID retrieves the worker ID assigned to an email account
func (r *emailRepository) GetWorkerID(ctx context.Context, emailAccountID uuid.UUID) (*uuid.UUID, *errx.Error) {
query := `SELECT worker_id FROM email_accounts WHERE id = $1`
var workerID *uuid.UUID
err := r.DB.QueryRow(ctx, query, emailAccountID).Scan(&workerID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
db.CaptureError(err, query, []any{emailAccountID}, "queryrow")
return nil, errx.InternalError()
}
return workerID, nil
}
// SetStatus sets a mailbox's status by id alone.
//
// Update is scoped to an organization because it serves a person editing their
// own mailbox. This serves the consumer reacting to a worker's report about a
// specific mailbox, where the id is already the primary key and a tenant id
// adds no safety: passing the wrong one cannot deny access, it can only turn
// the write into a silent no-op. That is exactly what happened, for months, to
// every mailbox that failed authentication.
func (r *emailRepository) SetStatus(ctx context.Context, emailAccountID uuid.UUID, status string) *errx.Error {
query := `UPDATE email_accounts SET status = $1, updated_at = NOW() WHERE id = $2`
cmd, err := r.DB.Exec(ctx, query, status, emailAccountID)
if err != nil {
db.CaptureError(err, query, []any{status, emailAccountID}, "exec")
return errx.InternalError()
}
if cmd.RowsAffected() == 0 {
return errx.ErrNotFound
}
return nil
}
// SetWorkerID assigns a worker to an email account
func (r *emailRepository) SetWorkerID(ctx context.Context, emailAccountID, workerID uuid.UUID) *errx.Error {
query := `UPDATE email_accounts SET worker_id = $1, updated_at = NOW() WHERE id = $2 AND NOT ` + instanceExecutedSQL("email_accounts.id")
cmd, err := r.DB.Exec(ctx, query, workerID, emailAccountID)
if err != nil {
db.CaptureError(err, query, []any{workerID, emailAccountID}, "exec")
return errx.InternalError()
}
if cmd.RowsAffected() == 0 {
return errx.ErrNotFound
}
return nil
}
func (r *emailRepository) MarkDomainAuthRecheck(ctx context.Context, domain string) error {
if strings.TrimSpace(domain) == "" {
return nil
}
_, err := r.DB.Pool.Exec(ctx, `
UPDATE email_accounts
SET auth_checked_at = NULL
WHERE lower(split_part(email, '@', 2)) = lower($1)
`, domain)
return err
}
// UpdateTrackDirectMail flips this mailbox's opt-in for open/click tracking on
// hand-written sends. Scoped by organization for the same reason as the
// tracking-domain write: a workspace admin who did not connect the mailbox must
// still be able to manage it.
func (r *emailRepository) UpdateTrackDirectMail(ctx context.Context, orgID, emailAccountID string, enabled bool) *errx.Error {
query := `
UPDATE email_accounts
SET track_direct_mail = $1
WHERE organization_id = $2 AND id = $3
`
params := []any{enabled, orgID, emailAccountID}
cmd, err := r.DB.Exec(ctx, query, params...)
if err != nil {
db.CaptureError(err, query, params, "exec")
return errx.InternalError()
}
if cmd.RowsAffected() == 0 {
return errx.ErrNotFound
}
return nil
}
// GetSyncSkipFolders reads the mailbox's skip list; an empty list for a
// mailbox that never set one.
func (r *emailRepository) GetSyncSkipFolders(ctx context.Context, emailAccountID uuid.UUID) ([]string, *errx.Error) {
query := `SELECT sync_skip_folders FROM email_accounts WHERE id = $1`
var folders []string
if err := r.transportQueryRow(ctx, query, emailAccountID).Scan(&folders); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, errx.ErrNotFound
}
db.CaptureError(err, query, []any{emailAccountID}, "query")
return nil, errx.InternalError()
}
return folders, nil
}
// SetSyncSkipFolders stores the skip list as given; the caller has already
// normalized it. A nil slice would bind as SQL NULL against a NOT NULL
// column, so an empty list is written as an empty array.
func (r *emailRepository) SetSyncSkipFolders(ctx context.Context, orgID, emailAccountID string, folders []string) *errx.Error {
if folders == nil {
folders = []string{}
}
query := `
UPDATE email_accounts
SET sync_skip_folders = $1, updated_at = NOW()
WHERE organization_id = $2 AND id = $3
`
params := []any{folders, orgID, emailAccountID}
cmd, err := r.DB.Exec(ctx, query, params...)
if err != nil {
db.CaptureError(err, query, params, "exec")
return errx.InternalError()
}
if cmd.RowsAffected() == 0 {
return errx.ErrNotFound
}
return nil
}
// ListOrganizationIDs returns every workspace that has at least one mailbox.
func (r *emailRepository) ListOrganizationIDs(ctx context.Context) ([]uuid.UUID, error) {
rows, err := r.DB.Query(ctx, `SELECT DISTINCT organization_id FROM email_accounts WHERE organization_id IS NOT NULL`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []uuid.UUID
for rows.Next() {
var id uuid.UUID
if err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, id)
}
return out, rows.Err()
}
// WarmingOnWorkspaceClock lists the workspace's warming mailboxes that read their hours in the workspace timezone.
func (r *emailRepository) WarmingOnWorkspaceClock(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error) {
rows, err := resultDB(ctx, r.DB).Query(ctx, `SELECT id FROM email_accounts
WHERE organization_id = $1 AND COALESCE(timezone, '') = '' AND status = 'active' AND warmup IS NOT NULL AND warmup_paused_at IS NULL`, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}